<template>
  <div class="app-container">

    <el-row :gutter="40">
      <el-col :lg="4" :md="8" :xs="24" style="border-right: 1px solid #ebeef5;">
        <part-tree :store-id="queryParams.storeId"  @node-click="handlePartNodeClick" ref="partTree"/>
      </el-col>
      <el-col :lg="20" :md="16" :xs="24">
        <booth-copy :store-id="queryParams.storeId" :part-id="queryParams.partId" :part-parent-id="queryParams.partParentId"  ref="boothCopy" />
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {listPart, getPart, delPart, addPart, updatePart} from "@/api/bst/part";
import {$showColumns} from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import {listStore} from "@/api/bst/store";
import DeptSelect from "@/components/Business/Dept/DeptSelect.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import PartTree from "@/views/bst/part/components/PartTree.vue";
import {isSysAdmin} from "@/utils/permission";
import BoothCopy from "@/views/bst/part/boothCopy.vue";
import {listBooth} from "@/api/bst/booth";
import PartEditDialog from "@/views/bst/part/components/PartEditDialog.vue";

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

export default {
  name: "Part",
  mixins: [$showColumns],
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  components: {PartEditDialog, BoothCopy: BoothCopy, PartTree, StoreLink, DeptSelect, FormCol},
  data() {
    return {
      row: {},
      // 是否展开，默认全部展开
      isExpandAll: true,
      refreshTable: true,
      storeOptions: [], // 店铺域树数据
      parentOptions: [], // 父区域树数据
      cascaderProps: {
        value: 'partId',
        label: 'partName',
        children: 'children',
        checkStrictly: true,// 可单选任意级
        emitPath: false
      },
      span: 24,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域列表表格数据
      partList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        storeId: null,
        parentId: null,
        partParentId: null,
        partId: null,
        partName: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          {required: true, message: "所属店铺不能为空", trigger: "blur"}
        ],
        partName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "显示顺序不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
    this.getStoreList();
  },
  methods: {
    handleDialogSubmit(formData) {
      const api = formData.partId ? updatePart : addPart;
      api(formData).then(() => {
        this.$modal.msgSuccess(formData.partId ? "修改成功" : "新增成功");
        this.getList(); // 刷新数据
        this.open = false;
      });
    },
    isSysAdmin,
    // 分类树节点点击事件
    handlePartNodeClick(node) {
      console.log("节点",node)
      if (node.type === 'store') {
        this.queryParams.storeId = node.storeId;
        this.queryParams.partId = null;
        this.queryParams.partParentId = null;
      } else if (node.type === 'part') {
        this.queryParams.storeId = node.storeId;
        this.queryParams.partId = node.partId;
        this.queryParams.partParentId = node.partId;
      }
      console.log("查询参数",this.queryParams)
      // 触发数据更新（根据你的实际需求）
      this.$nextTick(() => {
        if (this.$refs.boothCopy) {
          this.$refs.boothCopy.getList();
        }
      });
    },
    loadParentTree(storeId) {
      listPart({
        storeId: storeId,
      }).then(res => {
        this.parentOptions = this.handleTree(res.data, "partId", "parentId", "children");
        console.log(this.parentOptions)
      });
    },
    // 店铺选择变化处理
    handleStoreChange(storeId) {
      this.form.parentId = null;
      if (storeId) {
        this.loadParentTree(storeId);
      } else {
        this.parentOptions = [];
      }
    },
    /** 当排序按钮被点击时触发 **/
    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();
    },
    /** 查询店铺列表 */
    getStoreList() {
      this.loading = true;
      listStore().then(response => {
        this.storeOptions = (response.rows || []).map(item => ({
          value: item.storeId,
          label: item.storeName
        }))
        this.loading = false
      });
    },
    /** 查询区域列表列表 */
    async getList() {
      this.loading = true;
      try {
        // 获取所有店铺
        const stores = await listStore();
        // 获取所有区域
        const parts = await listPart(this.queryParams);

        // 构建混合树形结构
        this.parentOptions = stores.rows.map(store => ({
          id: `store_${store.storeId}`, // 添加唯一标识前缀
          storeId: store.storeId,
          storeName: store.storeName,
          partName: store.storeName, // 统一使用partName字段显示名称
          isStore: true, // 标记为店铺节点
          children: this.buildStoreTree(parts.data, store.storeId)
        })).filter(storeNode => storeNode.children.length > 0);

        console.log('完整树形结构:', this.parentOptions);
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },
    buildStoreTree(parts, storeId) {
      const storeParts = parts.filter(p => p.storeId === storeId);
      return this.handleTree(storeParts.map(p => ({
        ...p,
        id: `part_${p.partId}`,  // 区域复合主键
        parentId: p.parentId ? `part_${p.parentId}` : `store_${storeId}`
      })), 'id', 'parentId', 'children');
    },
    // getList() {
    //   this.loading = true;
    //   listPart(this.queryParams).then(response => {
    //     this.parentOptions = this.handleTree(response.data, "partId", "parentId", "children");
    //     console.log("树形数据：", this.parentOptions); // 调试用
    //     this.loading = false;
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        partId: null,
        storeId: null,
        parentId: null,
        partName: null,
        picture: null,
        createTime: null,
        orderNum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.partId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.parentOptions = [];
      this.open = true;
      this.title = "添加区域列表";
      if (this.form.storeId) {
        this.loadParentTree(this.form.storeId);
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.parentOptions = [];
      const partId = row.partId || this.ids
      getPart(partId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域列表";
        if (this.form.storeId) {
          this.loadParentTree(this.form.storeId);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.partId != null) {
            updatePart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partIds = row.partId || this.ids;
      this.$modal.confirm('是否确认删除区域列表编号为"' + partIds + '"的数据项？').then(function () {
        return delPart(partIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/part/export', {
        ...this.queryParams
      }, `part_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

