<template>
  <div class="categories-container app-container">
    <div class="filter-container">
      <div class="search-filters">
        <el-input
          v-model="searchForm.name"
          placeholder="按分类名称搜索"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          class="filter-item"
          style="width: 240px"
          size="small"
        >
        </el-input>
        <el-button icon="el-icon-search"  type="primary" @click="handleSearch" size="small"></el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          size="small"
          style="margin-left: auto"
          >新增分类</el-button
        >
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="categoryList"
      style="width: 100%"
      row-key="id"
      size="small"
    >
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="分类名称"
        min-width="180"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="description"
        label="分类描述"
        min-width="150"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="字段配置" min-width="300">
        <template slot-scope="scope">
          <div
            v-if="scope.row.fieldConfig && scope.row.fieldConfig.length"
            class="field-tags-container"
          >
            <el-tag
              v-for="field in parseFieldConfig(scope.row.fieldConfig)"
              :key="field.fieldName"
              :type="getFieldTagType(field.fieldType)"
              size="small"
              class="field-tag"
              style="margin-right: 10px"
            >
              <i
                :class="getFieldIcon(field.fieldType)"
                style="margin-right: 4px"
              ></i>
              <strong>{{ field.displayLabel }}</strong> ({{ field.fieldType }})
              <span v-if="field.isRequired" class="required-indicator">*</span>
            </el-tag>
          </div>
          <span v-else class="text-placeholder">暂无配置</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" style="margin-right: 5px"></i>
          <span>{{ formatDateTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除这个分类吗？"
            @confirm="handleDelete(scope.row)"
            style="margin-left: 10px"
          >
            <el-button slot="reference" type="danger" plain size="mini"
              >删除</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="fetchCategoryList"
    />

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="850px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      top="5vh"
      custom-class="category-dialog"
    >
      <el-form
        ref="categoryForm"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="字段配置">
          <div class="field-config-panel">
            <div class="field-config-header">
              <h4 class="field-config-title">自定义字段</h4>
              <el-button
                type="primary"
                size="small"
                @click="addField"
                icon="el-icon-plus"
                plain
                >添加字段</el-button
              >
            </div>
            <div
              v-if="categoryForm.fieldConfig.length"
              class="field-list-container"
            >
              <transition-group name="fade" tag="div">
                <div
                  v-for="(field, index) in categoryForm.fieldConfig"
                  :key="field.id || index"
                  class="field-item-row"
                >
                  <el-row :gutter="15" align="middle">
                    <el-col :span="5">
                      <el-form-item
                        :prop="'fieldConfig.' + index + '.fieldName'"
                        :rules="{
                          required: true,
                          message: '字段名不能为空',
                          trigger: 'blur',
                        }"
                      >
                        <el-input
                          v-model="field.fieldName"
                          placeholder="字段名称 (英文)"
                          size="small"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <el-form-item
                        :prop="'fieldConfig.' + index + '.displayLabel'"
                        :rules="{
                          required: true,
                          message: '显示标签不能为空',
                          trigger: 'blur',
                        }"
                      >
                        <el-input
                          v-model="field.displayLabel"
                          placeholder="显示标签 (中文)"
                          size="small"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <el-select
                        v-model="field.fieldType"
                        placeholder="字段类型"
                        size="small"
                        style="width: 100%"
                      >
                        <el-option label="文本" value="text"></el-option>
                        <el-option label="数字" value="number"></el-option>
                        <el-option label="日期" value="date"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="4" class="text-center">
                      <el-checkbox v-model="field.isRequired"
                        >设为必填</el-checkbox
                      >
                    </el-col>
                    <el-col :span="3" class="text-center">
                      <el-button
                        type="danger"
                        size="mini"
                        @click="removeField(index)"
                        icon="el-icon-delete"
                        circle
                        plain
                      ></el-button>
                    </el-col>
                  </el-row>
                </div>
              </transition-group>
            </div>
            <div v-else class="no-fields-placeholder">
              <i class="el-icon-document-add placeholder-icon"></i>
              <p>暂无字段配置，点击 "添加字段" 开始创建</p>
            </div>
          </div>
        </el-form-item>
      </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 {
  getCategoriesList,
  createCategory,
  updateCategory,
  deleteCategory,
} from "@/api/sales-analysis";

export default {
  name: "Categories",
  data() {
    return {
      loading: false,
      submitting: false,
      categoryList: [],
      searchForm: {
        name: "",
      },
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      dialogVisible: false,
      isEdit: false,
      categoryForm: {
        id: null,
        name: "",
        description: "",
        fieldConfig: [],
      },
      categoryRules: {
        name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "分类名称长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        description: [{ required: false }],
      },
    };
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? "编辑分类" : "新增分类";
    },
  },
  created() {
    this.fetchCategoryList();
  },
  methods: {
    formatDateTime,

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

    // 获取分类列表
    async fetchCategoryList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          name: this.searchForm.name,
        };

        const response = await getCategoriesList(params);

        console.log(response);

        if (response.code === 200) {
          // 处理返回的数据，将 fieldConfig 字符串转换为 JSON 对象
          const categoryList = response.data.list || [];
          this.categoryList = categoryList.map(category => ({
            ...category,
            fieldConfig: this.parseFieldConfig(category.fieldConfig)
          }));
          this.pagination.total = response.data.pagination.total || 0;
        } else {
          this.$message.error(response.message || "获取分类列表失败");
        }
      } catch (error) {
        console.error("获取分类列表失败:", error);
        this.$message.error("获取分类列表失败");
      } finally {
        this.loading = false;
      }
    },

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

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

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

    getFieldTagType(type) {
      switch (type) {
        case "text":
          return "primary";
        case "number":
          return "warning";
        case "date":
          return "success";
        case "select":
          return "info";
        default:
          return "info";
      }
    },

    getFieldIcon(type) {
      switch (type) {
        case "text":
          return "el-icon-tickets";
        case "number":
          return "el-icon-sort";
        case "date":
          return "el-icon-date";
        case "select":
          return "el-icon-arrow-down";
        default:
          return "el-icon-document";
      }
    },

    // 新增分类
    handleAdd() {
      this.isEdit = false;
      this.categoryForm = {
        id: null,
        name: "",
        description: "",
        fieldConfig: [],
      };
      this.dialogVisible = true;
    },

    // 编辑分类
    handleEdit(row) {
      this.isEdit = true;
      this.categoryForm = {
        id: row.id,
        name: row.name,
        description: row.description || "",
        fieldConfig: JSON.parse(JSON.stringify(this.parseFieldConfig(row.fieldConfig))),
      };
      this.dialogVisible = true;
    },

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

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

    // 添加字段
    addField() {
      this.categoryForm.fieldConfig.push({
        id: Date.now(), // 添加一个唯一ID用于key
        fieldName: "",
        displayLabel: "",
        fieldType: "text",
        isRequired: false,
      });
    },

    // 移除字段
    removeField(index) {
      this.categoryForm.fieldConfig.splice(index, 1);
    },

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

        // 验证字段配置
        if (this.categoryForm.fieldConfig.length > 0) {
          const invalidFields = this.categoryForm.fieldConfig.filter(
            (field) =>
              !field.fieldName || !field.displayLabel || !field.fieldType
          );

          if (invalidFields.length > 0) {
            this.$message.error("请完善字段配置信息");
            return;
          }
        }

        this.submitting = true;

        // 创建提交数据，将 fieldConfig 转换为字符串
        const submitData = {
          ...this.categoryForm,
          fieldConfig: JSON.stringify(this.categoryForm.fieldConfig)
        };

        const response = this.isEdit
          ? await updateCategory(this.categoryForm.id, submitData)
          : await createCategory(submitData);

        if (response.code === 200) {
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.dialogVisible = false;
          this.fetchCategoryList();
        } 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.categoryForm.resetFields();
      this.categoryForm.fieldConfig = [];
    },
  },
};
</script>
