<template>
  <basic-container class="mti-container">
    <div class="mti-flex">
      <div class="mti-tree">
        <el-tree
          :data="treeData"
          node-key="id"
          highlight-current
          :props="{ children: 'children', label: 'name' }"
          :filter-node-method="filterNode"
          :render-after-expand="true"
          @node-click="getNodeData"
        />
      </div>
      <div class="mti-form">
        <div class="filter-container">
          <el-button size="mini" :icon="Plus" type="primary" round @click="handlerAdd">新增</el-button>
          <el-button size="mini" :icon="Edit" round @click="handlerEdit">编辑</el-button>
          <el-button size="mini" :icon="Delete" round @click="handleDelete">删除</el-button>
        </div>
        <div class="box-card">
          <el-form
            ref="form"
            label-position="right"
            label-width="100px"
            :rules="formRules"
            :model="formData"
            :disabled="formEdit"
            size="small"
          >
            <el-form-item label="父级节点" prop="parentId">
              <el-input v-model="formData.parentId" disabled />
            </el-form-item>
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入分类名称" />
            </el-form-item>
            <el-form-item label="节点内容" prop="content">
              <el-input v-model="formData.content" placeholder="请输入节点内容" />
            </el-form-item>
            <el-form-item label="是否有效" prop="delFlag">
              <el-select v-model="formData.delFlag" clearable>
                <el-option v-for="item in del_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="物资类型" prop="difference">
              <el-select v-model="formData.difference" clearable>
                <el-option v-for="item in material_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="父级行政编码" prop="parentCode">
              <el-input v-model="formData.parentCode" disabled />
            </el-form-item>
            <el-form-item label="行政编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入行政编码" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formData.sort" type="number" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item v-if="formStatus == 'update'">
              <el-button type="primary" round size="mini" @click="update">更新</el-button>
              <el-button size="mini" class="mti-cancle-btn" round @click="onCancel('update')">取消</el-button>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create'" size="mini">
              <el-button type="primary" round @click="create">保存</el-button>
              <el-button size="mini" class="mti-cancle-btn" round @click="onCancel('create')">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

import { deepClone } from "@/utils/util";
import { useDict } from "@/hooks/dict";
import { dictTree, getObj, delObj, putDict, addDict } from "@/api/orderType";

interface IFormData {
  type?: number;
  parentId?: number;
  delFlag?: string;
  id?: string;
  name?: string;
  content?: string;
  sort?: number;
  difference?: string;
  parentCode?: string | number;
  code?: string;
}

const treeData = ref([]);
const form = ref<FormInstance>();
const formRules = ref<FormRules>({
  id: [{ required: true, message: "请输入节点编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  delFlag: [{ required: true, message: "请选择是否有效", trigger: "change" }],
  sort: [
    { required: true, message: "请输入排序字段", trigger: "blur" },
    { max: 5, message: "长度在 0 到 5 个数字", trigger: "blur" }
  ]
});
const formData = ref<IFormData>({});
const tmpForm = ref<IFormData>({
  type: 2
});
const currentItem = ref({
  id: 0,
  code: 0
});
const formEdit = ref(true);
const formStatus = ref("");

const { del_type } = useDict("del_type");

const getList = () => {
  dictTree(2).then((res: any) => {
    treeData.value = res.data == null ? [] : res.data;
  });
};

getList();

const filterNode = (value: any, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

// 点击时获取对应节点数据
const getNodeData = (data: any) => {
  form.value?.clearValidate();
  formEdit.value = true;
  getObj(data.id).then((res: any) => {
    formData.value = res.data;
    tmpForm.value = deepClone(res.data);
    currentItem.value.id = data.id;
    currentItem.value.code = data.code;
  });
};

// 添加节点
const handlerAdd = () => {
  resetForm();
  formEdit.value = false;
  formStatus.value = "create";
};

// 编辑节点
const handlerEdit = () => {
  form.value?.clearValidate();
  formEdit.value = false;
  formStatus.value = "update";
};

// 删除节点
const handleDelete = () => {
  if (currentItem.value.id !== 0) {
    ElMessageBox.confirm(`此操作将永久删除改父节点及其下的所有子节点, 是否继续?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      delObj(currentItem.value.id).then((res: any) => {
        currentItem.value.id = 0;
        onCancel();
        getList();
        if (res.code === 0) {
          ElMessage.success(`删除成功`);
        } else {
          ElMessage.error(`失败`);
        }
      });
    });
  } else {
    ElMessage.warning(`请选择需要删除的数据`);
  }
};

// 更新节点
const update = () => {
  form.value?.validate((valid: boolean) => {
    if (!valid) return;
    putDict({ ...formData.value }).then(() => {
      ElMessage.success(`更新成功`);
      formEdit.value = true;
    });
  });
};

// 创建节点
const create = () => {
  form.value?.validate((valid: boolean) => {
    if (!valid) return;
    addDict({ ...formData.value }).then(() => {
      getList();
      onCancel();
      formStatus.value = "";
      ElMessage.success(`创建成功`);
    });
  });
};

// 编辑时初始化表单
const resetForm = () => {
  formData.value = {
    parentId: currentItem.value.id,
    parentCode: currentItem.value.code,
    difference: "",
    type: 2,
    id: "",
    code: "",
    delFlag: "0",
    name: "",
    content: "",
    sort: 1
  };
};

// 取消修改时处理数据
const onCancel = (val?: string) => {
  form.value?.clearValidate();
  if (val === "update") {
    formData.value = JSON.parse(JSON.stringify(tmpForm.value));
  } else {
    formData.value = {};
  }
  formEdit.value = true;
  formStatus.value = "";
};
</script>

<style lang="scss" scoped>
.mti-container {
  .mti-flex {
    display: flex;
    .mti-tree {
      width: 250px;
      overflow-y: auto;
      margin-bottom: 0;
      .el-tree {
        padding: 10px;
        background-color: #e2f1fe !important;
        color: #606266;
        border: 1px solid #d9ebf8;
        &.el-tree--highlight-current {
          .el-tree-node.is-current {
            > .el-tree-node__content {
              background-color: #ffffff;
            }
          }
        }
        .el-tree-node__content {
          height: 30px;
          &:hover {
            background-color: #fff;
          }
        }
      }
      .filter-tree.avue-tree {
        .el-tree-node {
          &:focus {
            > .el-tree-node__content {
              background-color: #ffffff !important;
            }
          }
        }
        position: relative;
        padding-top: 10px;
        background-color: #e2f1fe;
        color: #606266;
        border: 1px solid #d9ebf8;
        height: 100%;
        .avue-tree__filter {
          margin-bottom: 5px;
          padding: 0 12px;
        }
        .el-tree {
          padding-top: 0;
          border-style: none;
        }
      }
    }
    .mti-form {
      flex-grow: 1;
      position: relative;
      padding: 10px 20px;

      .filter-container {
        margin-bottom: 20px;
      }
      .box-card {
        border: 1px solid #d9ebf8;
        padding: 30px 32px;

        .el-button.mti-cancle-btn {
          background-color: #fd5f43;
          color: #fff;

          &:hover {
            background-color: #e26f5a;
          }
        }
      }
    }
  }
}
</style>
