<template>
  <div class="data-list-page app-container">
    <!-- 搜索筛选 -->
    <div class="filter-container" style="gap: 0">
      <div class="search-filters">
        <el-form :model="searchForm" :inline="true" size="small">
          <el-form-item label="商品编号">
            <el-input
              v-model="searchForm.productCode"
              placeholder="请输入商品编号"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入商品名称"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input
              v-model="searchForm.customerName"
              placeholder="请输入客户名称"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item label="店铺名称">
            <el-input
              v-model="searchForm.shopName"
              placeholder="请输入店铺名称"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              style="width: 160px"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="正常" value="1" />
              <el-option label="客户未匹配" value="2" />
              <el-option label="规格未匹配" value="3" />
            </el-select>
          </el-form-item>
          <br />
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="searchForm.startDate"
              type="date"
              placeholder="选择开始日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="searchForm.endDate"
              type="date"
              placeholder="选择结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 160px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" icon="el-icon-search"></el-button>
            <el-button @click="handleReset" icon="el-icon-refresh"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="actions" style="margin-top: 0; justify-content: flex-end;">
        <el-button
          type="success"
          plain
          @click="goToImport"
          icon="el-icon-upload2"
          size="small"
          >导入Excel</el-button
        >
        <el-button
          type="success"
          plain
          @click="handleExport"
          icon="el-icon-download"
          size="small"
          >导出Excel</el-button
        >
        <el-divider direction="vertical"></el-divider>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
          size="small"
          >批量删除</el-button
        >
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="loading"
      size="small"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="date" label="日期" width="100" sortable />
      <el-table-column
        prop="shopName"
        label="店铺"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="productCode"
        label="商品编号"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="productName"
        label="商品名称"
        show-overflow-tooltip
      />
      <el-table-column
        prop="customerName"
        label="客户"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="category"
        label="分类"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="
              scope.row.status === 1
                ? 'success'
                : scope.row.status === 2
                ? 'warning'
                : 'danger'
            "
            size="mini"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            :disabled="scope.row.status === 1"
            size="mini"
            plain
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pagination.total > 0"
      :total="pagination.total"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      :page-sizes="[50, 100, 300, 500, 1000]"
      @pagination="fetchData"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑分析数据"
      :visible.sync="editDialogVisible"
      width="800px"
      @close="handleEditDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editForm"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="editForm.date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="editForm.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="商品编号" prop="productCode">
          <el-input
            v-model="editForm.productCode"
            placeholder="请输入商品编号"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="editForm.productName"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="editForm.customerName"
            placeholder="请输入客户名称"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="editForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="分类规格" prop="categorySpecs">
          <el-input
            v-model="editForm.categorySpecs"
            placeholder="请输入分类规格"
          />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="editForm.quantity"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="合计金额" prop="totalAmount">
          <el-input-number
            v-model="editForm.totalAmount"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="出库类型" prop="deliveryType">
          <el-input
            v-model="editForm.deliveryType"
            placeholder="请输入出库类型"
          />
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input v-model="editForm.destination" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="editForm.remarks"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAnalysisDataList,
  updateAnalysisData,
  deleteAnalysisData,
  batchDeleteAnalysisData,
  exportAnalysisData,
} from "@/api/sales-analysis";

export default {
  name: "DataList",
  data() {
    return {
      loading: false,
      tableData: [],
      selectedRows: [],
      searchForm: {
        productCode: "",
        productName: "",
        customerName: "",
        shopName: "",
        status: "",
        startDate: "",
        endDate: "",
      },
      pagination: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      editDialogVisible: false,
      editForm: {
        id: null,
        date: "",
        shopName: "",
        productCode: "",
        productName: "",
        customerName: "",
        category: "",
        categorySpecs: "",
        quantity: 0,
        totalAmount: 0,
        deliveryType: "",
        destination: "",
        remarks: "",
      },
      editRules: {
        date: [{ required: true, message: "请选择日期", trigger: "change" }],
        shopName: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "请输入商品编号", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    // 获取数据
    async fetchData() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...this.searchForm,
        };

        const response = await getAnalysisDataList(params);

        if (response.code === 200) {
          this.tableData = response.data.list || [];
          this.pagination = response.data.pagination || {};
        } else {
          this.$message.error(response.message || "获取数据失败");
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1;
      this.fetchData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        productCode: "",
        productName: "",
        customerName: "",
        shopName: "",
        status: "",
        startDate: "",
        endDate: "",
      };
      this.pagination.page = 1;
      this.fetchData();
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.page = 1;
      this.fetchData();
    },

    // 当前页改变
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.fetchData();
    },

    // 选择行改变
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 编辑
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        date: row.date,
        shopName: row.shopName,
        productCode: row.productCode,
        productName: row.productName,
        customerName: row.customerName,
        category: row.category,
        categorySpecs: row.categorySpecs,
        quantity: row.quantity,
        totalAmount: row.totalAmount,
        deliveryType: row.deliveryType,
        destination: row.destination,
        remarks: row.remarks,
      };
      this.editDialogVisible = true;
    },

    // 提交编辑
    handleEditSubmit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await updateAnalysisData(
              this.editForm.id,
              this.editForm
            );

            if (response.code === 200) {
              this.$message.success("编辑成功");
              this.editDialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(response.message || "编辑失败");
            }
          } catch (error) {
            console.error("编辑失败:", error);
            this.$message.error("编辑失败");
          }
        }
      });
    },

    // 编辑对话框关闭
    handleEditDialogClose() {
      this.$refs.editForm.resetFields();
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确定要删除这条记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await deleteAnalysisData(row.id);

            if (response.code === 200) {
              this.$message.success("删除成功");
              this.fetchData();
            } else {
              this.$message.error(response.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }

      this.$confirm(
        `确定要删除选中的 ${this.selectedRows.length} 条记录吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const ids = this.selectedRows.map((row) => row.id).join(",");
            const response = await batchDeleteAnalysisData(ids);

            if (response.code === 200) {
              this.$message.success("批量删除成功");
              this.fetchData();
            } else {
              this.$message.error(response.message || "批量删除失败");
            }
          } catch (error) {
            console.error("批量删除失败:", error);
            this.$message.error("批量删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 导出数据
    async handleExport() {
      const response = await exportAnalysisData(this.searchForm);
      const blob = new Blob([response], { type: "application/vnd.ms-excel" });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `analysis-data-${new Date().toLocaleDateString()}.xlsx`;
      a.click();
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: "正常",
        2: "客户未匹配",
        3: "规格未匹配",
      };
      return statusMap[status] || "未知";
    },

    // 跳转到导入页面
    goToImport() {
      this.$router.push("/sales-analysis/analysis-data/import");
    },
  },
};
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: center;
}
</style>
