<template>
  <div v-loading="loading">
    <div style="margin-bottom: 10px;">
      <el-input v-model="searchValue" placeholder="请输入区域名称" @input="handleSearch" size="small" />
    </div>
    <el-tree
      :data="treeData"
      :props="defaultProps"
      node-key="partId"
      default-expand-all
      :filter-node-method="filterNode"
      v-on="$listeners"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span class="operation-group">
          <el-button type="text" size="mini" icon="el-icon-plus" @click.stop="handleAdd(data)"></el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" v-if="data.partId" @click.stop="handleEdit(data)"></el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" @click.stop="handleDelete(data)"></el-button>
        </span>
      </span>
    </el-tree>

    <part-edit-dialog
      :visible.sync="dialogVisible"
      :id="row.partId"
      :form-data="this.formData"
      :store-options="this.stores.rows"
      @success="getList"
    />

  </div>
</template>

<script>
import { listPart ,delPart } from "@/api/bst/part";
import {delStore, listStore} from "@/api/bst/store";
import PartEditDialog from "@/views/bst/part/components/PartEditDialog.vue";

export default {
  name: 'PartTree',
  components: {
    PartEditDialog
  },
  props: {
    storeId: { // 新增storeId prop
      type: [Number, String],
      default: null
    },
    query: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      queryParams: {
        storeId: null,
      },
      stores: { // 声明 stores
        rows: []
      },
      loading: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formData: {
        id: null,
        storeId: '',
        parentId: '0',
        partName: '',
        orderNum: 1,
        picture: null
      },
      // 弹窗相关
      dialogVisible: false,
      row: {},
      parentId: null,
      searchValue: null,
    }
  },
  mounted() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList()

  },
  methods: {
    handleSearch() {
      this.$refs.tree.filter(this.searchValue)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },
    // 获取数据列表
    async getList() {
      this.loading = true;
      try {
        // 同时获取店铺和区域数据
        const [stores, parts] = await Promise.all([
          listStore({ storeId: this.storeId }),
          listPart({ storeId: this.storeId })
        ]);
        this.stores.rows = stores.rows
        // 构建复合树结构
        this.treeData = stores.rows.map(store => ({
          id: `store_${store.storeId}`,
          storeId:store.storeId,
          partId:null,
          name: store.storeName,
          type: 'store',
          children: this.buildStoreTree(parts.data, store.storeId)
        })).filter(store => store.children.length > 0);
      } 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}`,
          storeId: p.storeId,
          partId:p.partId,
          name: p.partName,
          type: 'part',
          parentId: p.parentId ? `part_${p.parentId}` : null
        })),
        'id',
        'parentId',
        'children'
      );
    },
    // 新增按钮操作
    handleAdd(row) {
      this.row = {};
      this.formData = {
        storeId: row.storeId ? row.storeId : '',
        parentId:row.partId.replace(/^part_/, '')
      };
      console.log("fromData",this.formData)
      this.dialogVisible = true
    },
    // 修改按钮操作
    handleEdit(row) {
      this.row = row;
      this.formData = {
        partId : row.partId? row.partId.replace(/^part_/, ''): null,
        storeId: row.storeId? row.storeId.replace(/^store_/, ''): null,
        parentId: row.parentId? row.parentId.replace(/^part_/, '') : null
      };
      console.log("formData",this.formData)
      this.dialogVisible = true
    },
    // 删除按钮操作
    handleDelete(row) {
      if (row.type === 'store') {
        if (row.children?.length > 0) {
          this.$modal.msgError('店铺下存在区域，不能删除');
          return;
        }
      } else {
        if (row.children?.length > 0) {
          this.$modal.msgError('存在子区域不能删除');
          return;
        }
      }
      const confirmMsg = row.type === 'store'
        ? `是否确认删除店铺【${row.name}】`
        : `是否确认删除区域【${row.name}】`;

      this.$modal.confirm(confirmMsg).then(() => {
        const api = row.type === 'store'
          ? delStore(row.id.replace('store_', ''))
          : delPart(row.id.replace('part_', ''));

        return api.then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .operation-group {
    .el-button {
      opacity: 0;
      margin-left: 8px;

      &:first-child {
        margin-left: 0;
      }

      &[class*="el-icon-delete"] {
        color: #f56c6c;
      }
    }
  }

  &:hover {
    .operation-group {
      .el-button {
        opacity: 1;
      }
    }
  }
}
</style>
