<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="目录名称" prop="cateName">
        <el-input
          v-model="queryParams.cateName"
          placeholder="请输入目录名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="cateStatus">
        <el-select
         style="width: 100px;"
          v-model="queryParams.cateStatus"
          placeholder="目录状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in optionsDirary"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button 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"
          icon="plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
          plain
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="catalogList"
      row-key="cateCode"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="cateName" label="目录名称"></el-table-column>
      <el-table-column
        prop="cateSeq"
        label="排序"
        width="200"
      ></el-table-column>
      <el-table-column prop="cateStatus" label="状态" width="100">
        <template #default="scope">
          <dict-tag
            :options="sys_normal_disable"
            :value="scope.row.cateStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
        width="260"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >
            新增
          </el-button>
          <el-button
            v-if="scope.row.catePcode != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改目录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.catePcode !== '0'">
            <el-form-item label="上级目录" prop="catePcode">
              <!-- <TreeSelect
                style="width: 100%;"
                v-model="form.catePcode"
                :objMap="{ value: 'cateCode', label: 'cateName', children: 'children' }"
                :options="deptOptions"
                placeholder="选择上级目录"
              /> -->
              <el-tree-select
                v-model="form.catePcode"
                :data="deptOptions"
                :render-after-expand="false"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目录名称" prop="cateName">
              <el-input v-model="form.cateName" placeholder="请输入目录名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="cateSeq">
              <el-input-number
                v-model="form.cateSeq"
                @change="showChange"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目录详情">
              <el-input
                v-model="form.cateDesc"
                placeholder="请输入详情"
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 8 }"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="目录状态">
              <el-radio-group v-model="form.cateStatus">
                <el-radio
                  v-for="dict in optionsDirary"
                  :key="dict.value"
                  :label="dict.label"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-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 setup>
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
</script>
<script>
import {
  listCatalog,
  getCatalog,
  delCatalog,
  addCatalog,
} from "@/api/base/catalog";
import TreeSelect from "@/components/TreeSelect";
// import Treeselect from 'vue3-treeselect';

// import 'vue3-treeselect/dist/vue3-treeselect.css';

import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Catalog",
  dicts: ["sys_normal_disable"],
  components: {TreeSelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      optionsDirary:[],
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      catalogList: [],
      // 目录树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        cataName: undefined,
        cateStatus: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        catePcode: [
          {required: true, message: "上级目录不能为空", trigger: "blur"},
        ],
        cataName: [
          {required: true, message: "目录名称不能为空", trigger: "blur"},
        ],
        cateSeq: [
          {required: true, message: "显示排序不能为空", trigger: "blur"},
        ],
      },
    };
  },
  created() {
    this.getDicts()
    this.getList();
  },
  methods: {
    showChange(){
      console.log(this.form)
    },
    async getDicts(){
      await getDicts("sys_normal_disable").then((r) => {
        for(var i =0;i<r.data.length;i++){
          var par = {
            value:r.data[i].dictCode.toString(),
            label:r.data[i].dictLabel
          }
          this.optionsDirary.push(par)
        }
      });
    },
    /** 查询目录列表 */
    getList() {
      this.loading = true;
      listCatalog(this.queryParams).then((r) => {
        this.catalogList = this.handleTree(r.data, "cateCode", "catePcode");
        this.loading = false;
      });
    },
    /** 转换目录数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        value: node.cateCode,
        label: node.cateName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cateCode: undefined,
        catePcode: undefined,
        cateName: undefined,
        cateSeq: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        cateStatus: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.catePcode = row.cateCode;
      }
      this.open = true;
      this.title = "添加目录";
      listCatalog(this.queryParams).then((r) => {
        this.catalogList = this.handleTree(r.data, "cateCode", "catePcode");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await listCatalog(this.queryParams).then((r) => {
        this.deptOptions = this.buildTree(r.data);
        this.deptOptions = this.renameTreeProperties(this.deptOptions,{ cateName: 'label', cateCode: 'value' }, { childrenKey: 'children' })
        
      });
      await getCatalog(row.cateCode).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改目录";
      });
      console.log(this.deptOptions)
    },
     buildTree(flatData, { 
        codeKey = 'cateCode', 
        parentKey = 'catePcode', 
        childrenKey = 'children' 
      } = {}) {
        const nodeMap = new Map();
        const tree = [];
        flatData.forEach(node => {
          nodeMap.set(node[codeKey], { ...node, [childrenKey]: [] });
        });
        flatData.forEach(node => {
          const parentCode = node[parentKey];
          const currentNode = nodeMap.get(node[codeKey]);
          if (!parentCode || !nodeMap.has(parentCode)) {
            tree.push(currentNode);
          } else {
            const parentNode = nodeMap.get(parentCode);
            parentNode[childrenKey].push(currentNode);
          }
        });
        return tree;
      },
    renameTreeProperties(tree, nameMap, {
      childrenKey = 'children',
      checkCircular = true
      } = {}) {
        const visited = new WeakSet(); // 用于检测循环引用

      function processNode(node) {
          if (!node || typeof node !== 'object') return node;
          
          // 检测循环引用
          if (checkCircular) {
            if (visited.has(node)) {
              console.warn('检测到循环引用，跳过处理:', node);
              return node;
            }
            visited.add(node);
          }

          // 创建新节点（浅拷贝）
          const newNode = Array.isArray(node) ? [] : {};
          
          // 重命名属性
          for (const [oldName, newName] of Object.entries(nameMap)) {
            if (oldName in node) {
              newNode[newName] = node[oldName];
            }
          }

          // 复制未映射的原始属性
          for (const key in node) {
            if (!nameMap.hasOwnProperty(key) && !newNode.hasOwnProperty(key)) {
              newNode[key] = node[key];
            }
          }

          // 递归处理子节点
          if (node[childrenKey]) {
            newNode[childrenKey] = node[childrenKey].map(processNode);
            
            // 可选：移除空子节点数组
            if (newNode[childrenKey].length === 0) {
              delete newNode[childrenKey];
            }
          }

          return newNode;
        }

      return Array.isArray(tree) 
        ? tree.map(processNode) 
        : processNode(tree);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addCatalog(this.form).then((response) => {
            this.$modal.msgSuccess(
              this.form.cateCode != undefined ? "修改成功" : "新增成功"
            );
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.cateName + '"的数据项？')
        .then(function () {
          return delCatalog(row.cateCode);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
  },
};
</script>
