<template>
  <div class="p-3 bg-white dark:!bg-[#060818]">
    <div class="toolbar">
      <div class="inner-toolbar">
        <div class="toolbar-btns">
          <span class="pr-2.5">商品类别</span>
          <el-button size="mini" type="primary" @click="handleAddCategary">新增类别</el-button>
        </div>
      </div>
    </div>
    <el-tree :data="categorys" node-key="category_id" :expand-on-click-node="false" :default-expanded-keys="expandedKeys" ref="categoryTree">
      <template #default="{ node, data }">
        <span class="custom-tree-node" @click="handleSeachShop(data)">
          <span>{{ data.name }}</span>
          <span>
            <el-button
              type="text"
              size="mini"
              :disabled="node.level === 3"
              icon="el-icon-plus"
              :title="node.level === 3 ? '类别最多添加三级' : '增加'"
              @click.stop="handleAddCategary(data)"
            ></el-button>
            <el-button type="text" style="color: #f56c6c" size="mini" icon="el-icon-minus" @click.stop="handleDeleteCategory(data)"></el-button>
            <el-button type="text" size="mini" icon="el-icon-edit" @click.stop="handleEditCategary(data)"></el-button>
          </span>
        </span>
      </template>
    </el-tree>
    <!--编辑分类dialog-->
    <el-dialog
      :title="categoryForm.name ? '编辑类别' : '添加类别'"
      v-model="dialogCategoryVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="categoryForm" ref="categoryFormRef" label-width="100px">
        <el-form-item label="上级类别名称" prop="parent_id">
          <el-cascader
            v-model="categoryForm.parent_id"
            ref="cascaderHandle"
            :options="categorys"
            :props="{
              label: 'name',
              value: 'category_id',
              emitPath: false,
              checkStrictly: true,
            }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品类别名称" prop="category_name">
          <el-input v-model="categoryForm.category_name" :maxlength="12"></el-input>
        </el-form-item>
        <el-form-item label="商品类别编号" prop="custom_sn">
          <el-input v-model="categoryForm.custom_sn"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCategoryForm('categoryForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { defineComponent, ref, onMounted, nextTick } from 'vue';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import * as API_Goods from '@/api/goods';
/* 分类数据 */
const categorys = ref([]);
const expandedKeys = ref<string[]>([]);
/*分类表单*/
const categoryForm = ref<any>({});
const dialogCategoryVisible = ref(false);
/** 添加类别 */
const handleAddCategary = (category) => {
  categoryForm.value = {
    parent_id: category ? category.category_id : 0,
  };
  dialogCategoryVisible.value = true;
};
/* 删除分类 */
const categoryTree = ref();
const handleDeleteCategory = (data: any) => {
  nextTick(() => {
    const node = categoryTree.value.getNode(data.category_id);
    if (!node) {
      console.error('Node not found for category_id:', data.category_id);
      return;
    }

    // 保持父节点展开
    const parentNode = node.parent;
    if (parentNode && !expandedKeys.value.includes(parentNode.data.category_id)) {
      expandedKeys.value.push(parentNode.data.category_id);
    }

    // 执行删除操作
    ElMessageBox.confirm('确定要删除这个分类吗？', '提示', { type: 'warning' })
      .then(() => {
        API_Goods.deleteCategory(data.category_id).then(() => {
          ElMessage.success('删除成功！');
          // 重新设置展开的节点，以防止收缩
          nextTick(() => {
            categoryTree.value.store.expandedKeys = expandedKeys.value;
          });
        });
      })
      .catch(() => {});
  });
};
/*  */
const params = ref<any>({});
const handleSeachShop = (data) => {
  params.value.page_no = 1;
  params.value.category_id = data.category_id;
};
/** 编辑类别  */
const handleEditCategary = (category) => {
  categoryForm.value = {
    parent_id: category.parent_id,
    category_id: category.category_id,
    category_name: category.name,
    custom_sn: category.custom_sn,
  };
  dialogCategoryVisible.value = true;
};
/* select监听 */
const cascaderHandle = ref();
const handleChange = (val) => {
  categoryForm.value.parent_id = val;
  cascaderHandle.value.dropDownVisible = false; // 监听值发生变化就关闭它
};
/* 提交表单 */
const submitCategoryForm = (formName) => {
  /*     const [formName]= */
  const { category_id } = categoryForm.value;
  if (!category_id) {
    API_Goods.addCategory(categoryForm.value).then(() => {
      dialogCategoryVisible.value = false;
      ElMessage.success('保存成功！');
      /* [formName].values.resetFields(); */
    });
  } else {
    API_Goods.editCategory(category_id, categoryForm.value).then((response) => {
      dialogCategoryVisible.value = false;
      ElMessage.success('修改成功！');
      /*    this.$refs[formName].resetFields(); */
    });
  }
};
</script>
  
  <style scoped>
.inner-toolbar {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 0 20px;
}
.spec-values-select {
  width: 100%;
}
</style>