<template>
  <div class="base-data-layout">
    <!-- 左侧分类导航 -->
    <div class="category-sidebar">
      <div class="category-list-wrapper" v-loading="categoriesLoading">
        <div
          v-for="category in categoriesList"
          :key="category.id"
          :class="[
            'category-item',
            { 'is-active': selectedCategoryId === category.id },
          ]"
          @click="selectCategory(category)"
        >
          <span class="category-name">{{ category.name }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
        <el-empty
          v-if="!categoriesList.length && !categoriesLoading"
          description="暂无分类数据"
          :image-size="80"
        ></el-empty>
      </div>
    </div>

    <!-- 右侧主内容区 -->
    <div class="main-content-area">
      <div v-if="!selectedCategory" class="placeholder-view card">
        <el-empty
          description="请从左侧选择一个分类进行操作"
          :image-size="120"
        ></el-empty>
      </div>

      <div v-else class="data-view">
        <div class="filter-container">
          <div class="search-filters">
            <el-input
              v-model="searchForm.productCode"
              placeholder="按商品编号搜索"
              clearable
              @clear="handleSearch"
              @keyup.enter.native="handleSearch"
              style="width: 160px"
              size="small"
              class="filter-item"
            ></el-input>
            <el-input
              v-model="searchForm.productName"
              placeholder="按商品名称搜索"
              clearable
              @clear="handleSearch"
              @keyup.enter.native="handleSearch"
              style="width: 160px"
              size="small"
              class="filter-item"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              size="small"
              style="margin-right: 0"
            ></el-button>
            <el-button
              icon="el-icon-refresh"
              @click="resetSearch"
              size="small"
              style="margin-left: 0"
            ></el-button>

            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
              size="small"
              style="margin-left: auto"
              >新增数据</el-button
            >
            <el-divider direction="vertical"></el-divider>
            <el-upload
              ref="upload"
              :action="uploadUrl"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              :show-file-list="false"
              accept=".xlsx,.xls"
              size="small"
            >
              <el-button
                type="success"
                plain
                icon="el-icon-upload2"
                size="small"
                >导入Excel</el-button
              >
            </el-upload>
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              @click="handleExport"
              :disabled="!baseDataList.length"
              size="small"
              >导出Excel</el-button
            >
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleBatchDelete"
              :disabled="!selectedRows.length"
              plain
              size="small"
              >批量删除</el-button
            >
          </div>
        </div>

        <!-- 数据表格 -->
        <el-table
          v-loading="dataLoading"
          :data="baseDataList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          row-key="id"
          size="small"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="productCode"
            label="商品编号"
            min-width="140"
            show-overflow-tooltip
            sortable
          ></el-table-column>
          <el-table-column
            prop="productName"
            label="商品名称"
            min-width="180"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="brand"
            label="品牌"
            min-width="110"
            show-overflow-tooltip
          ></el-table-column>

          <el-table-column
            v-for="field in categoryFields"
            :key="field.fieldName"
            :label="field.displayLabel"
            :prop="'categorySpecs.' + field.fieldName"
            min-width="120"
            show-overflow-tooltip
            sortable
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.categorySpecs
                  ? scope.row.categorySpecs[field.fieldName]
                  : ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.row)"
                plain
                >编辑</el-button
              >
              <el-popconfirm
                title="确定删除这条数据吗？"
                @confirm="handleDelete(scope.row)"
                style="margin-left: 10px"
              >
                <el-button slot="reference" type="danger" size="mini" plain
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="pagination.total > 0"
          :total="pagination.total"
          :page.sync="pagination.page"
          :limit.sync="pagination.pageSize"
          @pagination="fetchBaseDataList"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      top="8vh"
      custom-class="data-dialog"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataRules"
        label-width="110px"
        label-position="top"
        class="data-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编号" prop="productCode">
              <el-input
                v-model="dataForm.productCode"
                placeholder="请输入商品编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input
                v-model="dataForm.brand"
                placeholder="请输入品牌"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="dataForm.productName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>

        <!-- 动态分类规格字段 -->
        <div v-if="categoryFields.length" class="spec-section">
          <el-divider>分类规格 ({{ selectedCategory.name }})</el-divider>
          <el-row :gutter="20">
            <el-col
              :span="12"
              v-for="field in categoryFields"
              :key="field.fieldName"
            >
              <el-form-item
                :label="field.displayLabel"
                :prop="`categorySpecs.${field.fieldName}`"
                :rules="
                  field.isRequired
                    ? [
                        {
                          required: true,
                          message: `${field.displayLabel}不能为空`,
                          trigger: 'blur',
                        },
                      ]
                    : []
                "
              >
                <el-input
                  v-if="field.fieldType === 'text'"
                  v-model="dataForm.categorySpecs[field.fieldName]"
                  :placeholder="`请输入${field.displayLabel}`"
                ></el-input>
                <el-input-number
                  v-else-if="field.fieldType === 'number'"
                  v-model="dataForm.categorySpecs[field.fieldName]"
                  :placeholder="`请输入${field.displayLabel}`"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
                <el-date-picker
                  v-else-if="field.fieldType === 'date'"
                  v-model="dataForm.categorySpecs[field.fieldName]"
                  type="date"
                  :placeholder="`请选择${field.displayLabel}`"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { formatDateTime } from "@/utils/filters";
import {
  getCategoriesSimple,
  getCategoryDetail,
  getBaseDataList,
  deleteBaseData,
  batchDeleteBaseData,
  exportBaseData,
  BaseDataAdd,
  BaseDataUpdate,
} from "@/api/sales-analysis";

export default {
  name: "BaseData",
  data() {
    return {
      categoriesLoading: false,
      dataLoading: false,
      submitting: false,
      categoriesList: [],
      baseDataList: [],
      selectedCategory: null,
      selectedCategoryId: null,
      selectedRows: [],
      searchForm: {
        productCode: "",
        productName: "",
      },
      pagination: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      dialogVisible: false,
      isEdit: false,
      dataForm: {
        id: null,
        productCode: "",
        productName: "",
        brand: "",
        categorySpecs: {},
      },
      dataRules: {
        productCode: [
          { required: true, message: "请输入商品编号", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? "编辑基准数据" : "新增基准数据";
    },
    categoryFields() {
      return this.selectedCategory && this.selectedCategory.fieldConfig
        ? this.parseFieldConfig(this.selectedCategory.fieldConfig)
        : [];
    },
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + "/basedata/import";
    },
    uploadData() {
      return {
        categoryId: this.selectedCategoryId,
      };
    },
  },
  created() {
    this.fetchCategoriesList();
  },
  methods: {
    formatDateTime,

    // 解析字段配置字符串为 JSON 对象
    parseFieldConfig(fieldConfig) {
      try {
        if (!fieldConfig || typeof fieldConfig === "object") {
          return fieldConfig || [];
        }
        return JSON.parse(fieldConfig);
      } catch (error) {
        console.warn("解析字段配置失败:", error);
        return [];
      }
    },

    // 解析分类规格字符串为对象
    parseCategorySpecs(categorySpecs) {
      try {
        if (!categorySpecs) {
          return {};
        }
        if (typeof categorySpecs === "object") {
          return categorySpecs;
        }
        return JSON.parse(categorySpecs);
      } catch (error) {
        console.warn("解析分类规格失败:", error);
        return {};
      }
    },

    // 将分类规格对象转换为字符串
    stringifyCategorySpecs(categorySpecs) {
      try {
        if (!categorySpecs || typeof categorySpecs === "string") {
          return categorySpecs || "";
        }
        return JSON.stringify(categorySpecs);
      } catch (error) {
        console.warn("转换分类规格为字符串失败:", error);
        return "";
      }
    },

    // 获取分类列表
    async fetchCategoriesList() {
      try {
        this.categoriesLoading = true;
        const response = await getCategoriesSimple();

        if (response.code === 200) {
          this.categoriesList = response.data || [];
        } else {
          this.$message.error(response.message || "获取分类列表失败");
        }
      } catch (error) {
        console.error("获取分类列表失败:", error);
        this.$message.error("获取分类列表失败");
      } finally {
        this.categoriesLoading = false;
      }
    },

    // 选择分类
    async selectCategory(category) {
      if (this.selectedCategoryId === category.id) return;

      this.selectedCategoryId = category.id;
      this.pagination.page = 1;
      this.resetSearch();
      await this.fetchCategoryDetails(category.id);
      await this.fetchBaseDataList();
    },

    // 获取分类详情
    async fetchCategoryDetails(categoryId) {
      try {
        const response = await getCategoryDetail(categoryId);
        if (response.code === 200) {
          this.selectedCategory = response.data;
        } else {
          this.$message.error(response.message || "获取分类详情失败");
          this.selectedCategory = null; // 获取失败时重置
        }
      } catch (error) {
        console.error("获取分类详情失败:", error);
        this.$message.error("获取分类详情失败");
        this.selectedCategory = null;
      }
    },

    // 获取基准数据列表
    async fetchBaseDataList() {
      if (!this.selectedCategoryId) return;

      try {
        this.dataLoading = true;
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          categoryId: this.selectedCategoryId,
          productCode: this.searchForm.productCode,
          productName: this.searchForm.productName,
        };

        const response = await getBaseDataList(params);

        if (response.code === 200) {
          // 处理 categorySpecs 字段，将字符串转换为对象
          const list = response.data.list || [];
          this.baseDataList = list.map((item) => ({
            ...item,
            categorySpecs: this.parseCategorySpecs(item.categorySpecs),
          }));
          this.pagination.total = response.data.pagination.total;
        } else {
          this.$message.error(response.message || "获取基准数据失败");
        }
      } catch (error) {
        console.error("获取基准数据失败:", error);
        this.$message.error("获取基准数据失败");
      } finally {
        this.dataLoading = false;
      }
    },

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

    // 重置搜索
    resetSearch() {
      this.searchForm.productCode = "";
      this.searchForm.productName = "";
      this.handleSearch();
    },

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

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

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

    // 新增数据
    handleAdd() {
      this.isEdit = false;
      this.dataForm = {
        id: null,
        productCode: "",
        productName: "",
        brand: "",
        categorySpecs: {},
      };

      // 初始化分类规格字段
      this.categoryFields.forEach((field) => {
        this.$set(this.dataForm.categorySpecs, field.fieldName, "");
      });

      this.dialogVisible = true;
    },

    // 编辑数据
    handleEdit(row) {
      this.isEdit = true;
      this.dataForm = {
        id: row.id,
        productCode: row.productCode,
        productName: row.productName,
        brand: row.brand || "",
        categorySpecs: { ...row.categorySpecs },
      };
      this.dialogVisible = true;
    },

    // 删除数据
    handleDelete(row) {
      this.$confirm(`确定要删除商品"${row.productName}"吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await deleteBaseData(row.id);

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

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

      const ids = this.selectedRows.map((row) => row.id).join(",");

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

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

    // 导出Excel
    async handleExport() {
      try {
        const response = await exportBaseData(this.selectedCategoryId);

        // 创建下载链接
        const blob = new Blob([response], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `basedata-${
          this.selectedCategory?.name || "data"
        }-${new Date().toLocaleDateString()}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },

    // 上传前验证
    beforeUpload(file) {
      const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
      if (!isExcel) {
        this.$message.error("只能上传Excel文件！");
        return false;
      }

      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过10MB！");
        return false;
      }

      return true;
    },

    // 上传成功
    onUploadSuccess(response) {
      if (response.code === 200) {
        const data = response.data || {};
        let message = response.message || "导入成功";

        // 如果有错误详情，显示详细信息
        if (data.errors > 0) {
          message += `\n${data.errors}条数据有问题已跳过`;
          if (data.errorDetails && data.errorDetails.length > 0) {
            this.$alert(
              `导入完成！\n\n统计信息：\n- 总共处理：${
                data.total
              }条\n- 成功导入：${data.imported}条\n- 跳过错误：${
                data.errors
              }条\n\n错误详情（前10条）：\n${data.errorDetails
                .slice(0, 10)
                .join("\n")}`,
              "导入结果",
              {
                confirmButtonText: "确定",
                type: "warning",
              }
            );
          } else {
            this.$message.warning(message);
          }
        } else {
          this.$message.success(message);
        }

        this.fetchBaseDataList();
      } else {
        this.$message.error(response.message || "导入失败");
      }
    },

    // 上传失败
    onUploadError(error) {
      console.error("上传失败:", error);
      this.$message.error("文件上传失败");
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.dataForm.validate();

        this.submitting = true;

        // 将 categorySpecs 对象转换为字符串
        const submitData = {
          ...this.dataForm,
          categoryId: this.selectedCategoryId,
          categorySpecs: this.stringifyCategorySpecs(
            this.dataForm.categorySpecs
          ),
        };

        const response = this.isEdit
          ? await BaseDataUpdate(this.dataForm.id, submitData)
          : await BaseDataAdd(submitData);

        if (response.code === 200) {
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.dialogVisible = false;
          this.fetchBaseDataList();
        } else {
          this.$message.error(response.message || "操作失败");
        }
      } catch (error) {
        if (error.message !== "validation failed") {
          console.error("提交失败:", error);
          this.$message.error("操作失败");
        }
      } finally {
        this.submitting = false;
      }
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.dataForm.resetFields();
      this.dataForm.categorySpecs = {};
    },
  },
};
</script>

<style scoped>
.base-data-layout {
  display: flex;
  gap: 10px;
  padding: 10px;
}

.category-sidebar {
  width: 280px;
  height: 100%;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 10px;
  border-radius: 6px;
}

.sidebar-header i {
  margin-right: 8px;
}

.category-list-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s, color 0.2s;
  margin-bottom: 5px;
}

.category-item:hover {
  background-color: #f5f7fa;
}

.category-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
}

.category-name {
  font-size: 14px;
}

.main-content-area {
  width: 0;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.placeholder-view {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.data-view {
  display: flex;
  flex-direction: column;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.search-filters {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
</style>
