<template>
  <div>
    <layout-card>
      <el-row :gutter="12">
        <el-col :span="5">
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            class="mb-10"
          />
          <el-tree
            ref="treeRef"
            :props="{
              children: 'nodes',
              label: 'name',
            }"
            accordion
            :data="data.treeData"
            :filter-node-method="fnFilterNode"
            @node-click="fnResetPagination({ DEPARTMENT_ID: $event.id })"
          />
        </el-col>
        <el-col :span="19">
          <el-button
            class="mb-10"
            @click="data.structuralDiagramVisible = true"
          >
            结构图
          </el-button>
          <layout-table
            :data="list"
            v-model:pagination="pagination"
            @get-data="fnGetDataTransfer"
          >
            <el-table-column label="序号" width="70">
              <template v-slot="{ $index }">
                {{ serialNumber(pagination, $index) }}
              </template>
            </el-table-column>
            <el-table-column label="名称">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  text
                  link
                  @click="
                    router.push({
                      path: '/enterprise_management/department',
                      query: {
                        DEPARTMENT_ID: row.DEPARTMENT_ID,
                        DEPARTMENT_NAME: row.NAME,
                      },
                    })
                  "
                >
                  {{ row.NAME }}<el-icon><ArrowRight /></el-icon>
                </el-button>
              </template>
            </el-table-column>
            <template v-if="DEPARTMENT_ID !== '0'">
              <el-table-column prop="HEADMAN" label="负责人" />
              <el-table-column prop="leName" label="部门级别" />
              <el-table-column prop="DEP_ORDER" label="排序" width="100" />
              <el-table-column label="操作" width="100">
                <template v-slot="{ row }">
                  <el-button
                    type="primary"
                    text
                    link
                    @click="fnAddOrEdit(row.DEPARTMENT_ID, 'edit')"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="primary"
                    text
                    link
                    @click="fnDelete(row.DEPARTMENT_ID, row.NAME)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </template>
            <template #button>
              <el-button type="primary" @click="fnAddOrEdit('', 'add')">
                新增
              </el-button>
            </template>
          </layout-table>
        </el-col>
      </el-row>
    </layout-card>
    <structural-diagram
      v-model:visible="data.structuralDiagramVisible"
      :tree-data="data.treeData"
    />
  </div>
</template>

<script setup>
import { serialNumber } from "@/assets/js/utils.js";
import useListData from "@/assets/js/useListData.js";
import {
  getDepartmentList,
  setDepartmentDelete,
} from "@/request/department.js";
import { layoutFnGetDepartmentTree } from "@/assets/js/data_dictionary.js";
import { reactive, ref, watch } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { ArrowRight } from "@element-plus/icons-vue";
import { debounce } from "throttle-debounce";
import { ElMessage, ElMessageBox } from "element-plus";
import StructuralDiagram from "./components/structural_diagram.vue";

const router = useRouter();
const route = useRoute();
const parentIdDefault = "0";
const parentNameDefault = "（无）此项为顶级部门";
const DEPARTMENT_ID = ref(route.query.DEPARTMENT_ID || parentIdDefault);
const DEPARTMENT_NAME = ref(route.query.DEPARTMENT_NAME || parentNameDefault);
const treeRef = ref(null);
const filterText = ref("");
const { list, pagination, fnGetData, fnResetPagination } = useListData(
  getDepartmentList,
  {
    otherParams: {
      DEPARTMENT_ID: DEPARTMENT_ID.value,
    },
  }
);
const data = reactive({
  treeData: [],
  structuralDiagramVisible: false,
});
watch(filterText, (val) => {
  treeRef.value.filter(val);
});
const fnFilterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
const fnGetTreeData = async () => {
  const treeData = await layoutFnGetDepartmentTree();
  data.treeData = treeData.value;
};
fnGetTreeData();
const fnGetDataTransfer = () => {
  fnGetData({
    DEPARTMENT_ID: DEPARTMENT_ID.value,
  });
};
const fnResetPaginationTransfer = () => {
  fnResetPagination({
    DEPARTMENT_ID: DEPARTMENT_ID.value,
  });
};
onBeforeRouteUpdate((to) => {
  DEPARTMENT_ID.value = to.query.DEPARTMENT_ID || parentIdDefault;
  DEPARTMENT_NAME.value = to.query.DEPARTMENT_NAME || parentNameDefault;
  fnResetPaginationTransfer();
});
const fnDelete = debounce(
  1000,
  async (DEPARTMENT_ID, NAME) => {
    await ElMessageBox.confirm(`确定要删除[${NAME}]吗？`, { type: "warning" });
    await setDepartmentDelete({ DEPARTMENT_ID });
    ElMessage.success("删除成功");
    await fnResetPaginationTransfer();
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss"></style>
