<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-has-permi="['bst:goodsCategory:add']"
        >新增分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-has-permi="['bst:goodsCategory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table ref="treeTable" v-loading="loading" :data="parentOptions" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="handleSelectionChange"
              :default-sort="defaultSort"  @sort-change="onSortChange" :default-expand-all="true" >
      <el-table-column label="分类结构" width="300">
        <template slot-scope="{ row }">
      <span v-if="row.isStore">
        {{ row.storeName }}
      </span>
          <span v-else>
        {{ row.name }}
      </span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="55" align="center">
        <template slot-scope="{ row }">
          <span v-if="!row.isStore">{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:goodsCategory:edit']"
            v-if="!scope.row.isStore"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst:goodsCategory:remove']"
            v-if="!scope.row.isStore"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col label="选择店铺" prop="storeId">
            <el-select
              v-model="form.storeId"
              placeholder="请选择店铺"
              filterable
              clearable
              style="width: 100%"
              @change="handleStoreChange"
            >
              <el-option
                v-for="store in storeOptions"
                :key="store.storeId"
                :label="store.storeName"
                :value="store.storeId"
              />
            </el-select>
          </form-col>
          <form-col :span="span"  label="分类名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入分类名称" />
          </form-col>
          <form-col label="父级分类" prop="hasParent">
            <el-radio-group v-model="form.hasParent">
              <el-radio :label="false">无父级分类</el-radio>
              <el-radio :label="true">有父级分类</el-radio>
            </el-radio-group>
          </form-col>
          <form-col :span="span" label="排序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" style="width: 12" placeholder="请输入排序" />
          </form-col>
          <form-col v-if="form.hasParent" label="所属分类" prop="pid">
            <el-cascader
              v-model="form.pid"
              :options="categoryOptions"
              :props="cascaderProps"
              clearable
              :show-all-levels="false"
              placeholder="请先选择店铺"
              :disabled="!form.storeId"
            >

              <template slot-scope="{ node, data }">
                <span v-if="node.level === 1">{{ data.name }}</span>
              </template>
            </el-cascader>
          </form-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoodsCategory, getGoodsCategory, delGoodsCategory, addGoodsCategory, updateGoodsCategory } from "@/api/bst/goodsCategory";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import {handleTree} from "@/utils/ruoyi";
import {listStore} from "@/api/bst/store";

  // 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "GoodsCategory",
  mixins: [$showColumns],
  components: {FormCol},
  data() {
    return {
      categoryOptions: [],
      cascaderProps: {
        value: 'id',
        children: 'children',
        label: 'name',
        checkStrictly: true,// 可单选任意级
        emitPath:false,
        disabled: (data) => data.parentId !== 0
      },
      parentOptions: [], // 父区域树数据
      storeOptions: [], // 店铺列表数据
      span: 24,
      // 字段列表
      columns: [
        {key: 'name', visible: true, label: '分类名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'sort', visible: true, label: '排序', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        pid: null,
        name: null,
        storeId: null,
      },
      // 表单参数
      form: {
        hasParent: false,
      },
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: "所属店铺不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        hasParent: [ // 新增校验规则
          { required: true, message: "必须选择父级分类选项", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        pid: [
          {
            required: true,
            message: "必须选择父级分类",
            trigger: "change",
            validator: (rules, value, callback) => {
              if (this.form.hasParent && !value) {
                callback(new Error("必须选择父级分类"));
              } else {
                callback();
              }
            }
          }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getStoreList();
  },
  methods: {
    async handleStoreChange() {
      this.form.pid = null;
      if (!this.form.storeId) {
        this.categoryOptions = [];
        return;
      }

      // 调用接口获取该店铺下的分类（不传分页参数）
      const res = await listGoodsCategory({
        storeId: this.form.storeId // 仅传店铺ID
      });

      // 处理树形结构并更新级联选项
      this.categoryOptions = handleTree(res.rows, "id", "pid");
    },

    // 切换展开状态
    toggleExpand(row) {
      this.$refs.treeTable.toggleRowExpansion(row)
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询商品分类列表 */
    async getList() {
      this.loading = true;
      try {
        // 并行获取店铺和分类数据
        const [storeRes, allCategoriesRes] = await Promise.all([
          listStore(),
          listGoodsCategory() // 获取全部分类数据
        ]);

        // 创建店铺映射表（O(1)查找）
        const storeMap = new Map(storeRes.rows.map(store =>
          [store.storeId, {
            ...store,
            id: `store_${store.storeId}`,
            isStore: true,
            children: [],
            sort: 0
          }])
        );

        // 处理分类数据（复杂度O(n)）
        allCategoriesRes.rows.forEach(cat => {
          const storeNode = storeMap.get(cat.storeId);
          if (storeNode) {
            const processedCat = {
              ...cat,
              id: `${cat.id}`,
              pid: cat.pid ? `${cat.pid}` : `store_${cat.storeId}`
            };
            storeNode.children.push(processedCat);
          }
        });

        // 构建树形结构并过滤空店铺
        this.parentOptions = Array.from(storeMap.values())
          .filter(store => store.children.length > 0)
          .map(store => ({
            ...store,
            children: handleTree(store.children, "id", "pid")
          }))
          .sort((a, b) => a.id.localeCompare(b.id));

        this.total = this.parentOptions.length;

      } catch (error) {
        console.error('数据获取失败:', error);
      } finally {
        this.loading = false;
      }
    },
    getStoreList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeOptions = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        name: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品分类";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      try {
        const response = await getGoodsCategory(id);
        this.form = {
          ...response.data,
          hasParent: !!response.data.pid,
        };

        // 如果有店铺ID，加载分类树
        if (this.form.storeId) {
          await this.handleStoreChange(this.form.storeId);
        }

        // 设置级联选择器的值
        this.$nextTick(() => {
          this.form.pid = response.data.pid;
        });

        this.open = true;
        this.title = "修改商品分类";
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoodsCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品分类编号为"' + ids + '"的数据项？').then(function() {
        return delGoodsCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/goodsCategory/export', {
        ...this.queryParams
      }, `goodsCategory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

