<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="default"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table
      :data="sysIndustryList"
      style="width: 100%"
      v-loading="loading"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="领域名称" />
      <el-table-column label="操作" align="center">
        <template #default="props">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(props.row)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(props.row)"
            >删除</el-button
          >
          <el-button
            v-if="props.row.level < 3"
            size="small"
            type="text"
            icon="Plus"
            @click="handleAdd(props.row)"
            >新增子领域</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改领域对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showEditDialog"
      width="680px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级领域" prop="parentId">
          <TreeSelect
            :objMap="{
              value: 'id', // ID字段名
              label: 'name', // 显示名称
              children: 'children', // 子级字段名
            }"
            :options="menuOptions"
            v-model:value="form.parentId"
            placeholder="选择上级领域"
          />
        </el-form-item>
        <el-form-item label="领域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入领域名称" />
        </el-form-item>
      </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 name="Industry">
import {
  listSysIndustry,
  sysIndustryAdd,
  sysIndustryEdit,
  industryDelete,
} from "@/api/platform/industry.js";
import { reactive, ref, toRefs } from "vue";
import TreeSelect from "@/components/TreeSelect";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";

const loading = ref(true);
const sysIndustryList = ref([]); // 领域列表
const menuOptions = ref([]); // 领域树选项
const showEditDialog = ref(false); //是否显示编辑、添加弹窗
const dialogTitle = ref(""); // 弹穿标题
const formRef = ref(null);
const data = reactive({
  form: {},
  // 表单校验
  rules: {
    name: [{ required: true, message: "领域名称不能为空", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(data);
const getSysIndustryList = async () => {
  loading.value = true;
  const { data } = await listSysIndustry();

  setTreeLevel(data);
  getTreeselect(data);
  sysIndustryList.value = data;
  loading.value = false;
};

/** 转换领域数据结构 */
const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.id,
    label: node.name,
    children: node.children,
  };
};

/** 查询领域下拉树结构 */
const getTreeselect = (options) => {
  const data = setThreeLevelTree(options);
  menuOptions.value = [];
  const menu = { id: "", name: "主类目", level: 0, children: [] };
  menu.children = data;
  menuOptions.value.push(menu);
};

// 为每一个对象添加级别属性
const setTreeLevel = (node, index = 1) => {
  node.forEach((item) => {
    item["level"] = index;
    if (item.children && item.children.length) {
      item.children = setTreeLevel(item.children, index + 1);
    }
  });
  return node;
};

// 查询领域下拉树结构限制级别
const setThreeLevelTree = (node) => {
  return node.map((item) => {
    const result = { ...item };
    if (item.children && item.children.length && item.level < 2) {
      result.children = setThreeLevelTree(item.children);
    } else {
      delete result.children;
    }
    return result;
  });
};

// 重置表单
const reset = () => {
  form.value = {
    parentId: undefined,
    name: undefined,
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 点击弹框取消按钮操作
const cancel = () => {
  showEditDialog.value = false;
  reset();
};

// 添加按钮操作
const handleAdd = (row) => {
  reset();
  if (row != null && row.parentId != undefined && row.id !== undefined) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = "";
  }
  showEditDialog.value = true;
  dialogTitle.value = "添加领域";
};

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  form.value = cloneDeep(row);
  showEditDialog.value = true;
  dialogTitle.value = "修改领域";
};

/** 提交按钮 */
const submitForm = async () => {
  await formRef.value.validate();
  if (form.value.id) {
    await sysIndustryEdit(form.value);
    ElMessage.success("修改成功");
    showEditDialog.value = false;
    getSysIndustryList();
  } else {
    sysIndustryAdd(form.value);
    ElMessage.success("新增成功");
    showEditDialog.value = false;
    getSysIndustryList();
  }
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除名称为${row.name}的数据项？`, "删除领域", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await industryDelete(row.id);
      getSysIndustryList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
getSysIndustryList();
</script>
