<template>
  <div>
    <layout-card>
      <el-row :gutter="12">
        <el-col :span="5">
          <layout-department-tree
            :department-id="DEPARTMENT_ID"
            @throw-data="data.treeData = $event"
            @node-click="
              router.push({
                path: '/enterprise_management/department',
                query: {
                  DEPARTMENT_ID: $event.id,
                  DEPARTMENT_NAME: $event.name,
                },
              })
            "
            v-model:refresh="data.refreshTreeData"
          />
        </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
                    v-if="buttonJurisdiction.edit"
                    @click="fnAddOrEdit(row.DEPARTMENT_ID, 'edit')"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="primary"
                    text
                    link
                    v-if="buttonJurisdiction.del"
                    @click="fnDelete(row.DEPARTMENT_ID, row.NAME)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </template>
            <template #button v-if="DEPARTMENT_ID !== '0'">
              <el-button
                type="primary"
                v-if="buttonJurisdiction.add"
                @click="fnAddOrEdit('', 'add')"
              >
                新增
              </el-button>
              <el-button @click="router.back"> 返回 </el-button>
            </template>
          </layout-table>
        </el-col>
      </el-row>
    </layout-card>
    <structural-diagram
      v-model:visible="data.structuralDiagramVisible"
      :tree-data="data.treeData"
    />
    <add
      v-model:visible="data.addOrEditDialog.visible"
      v-model:form="data.addOrEditDialog.form"
      :type="data.addOrEditDialog.type"
      :parent-name="DEPARTMENT_NAME"
      :parent-id="DEPARTMENT_ID"
      @get-data="fnResetPaginationTransfer"
    />
  </div>
</template>

<script setup>
import { serialNumber } from "@/assets/js/utils.js";
import useListData from "@/assets/js/useListData.js";
import {
  getDepartmentList,
  getDepartmentView,
  setDepartmentDelete,
} from "@/request/enterprise_management.js";
import { nextTick, reactive, ref } 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";
import LayoutDepartmentTree from "@/components/department_tree/index.vue";
import Add from "./components/add.vue";
import useButtonJurisdiction from "@/assets/js/useButtonJurisdiction.js";

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 { list, pagination, fnGetData, fnResetPagination } = useListData(
  getDepartmentList,
  {
    otherParams: {
      DEPARTMENT_ID: DEPARTMENT_ID.value,
    },
  }
);
const data = reactive({
  treeData: [],
  refreshTreeData: false,
  structuralDiagramVisible: false,
  addOrEditDialog: {
    visible: false,
    type: "",
    form: {
      NAME: "",
      LEVEL: "",
      DEP_ORDER: "",
      HEADMAN: "",
      TEL: "",
      FUNCTIONS: "",
      BZ: "",
      ISSUPERVISE: "0",
      checkedIds: [],
    },
  },
});
const buttonJurisdiction = await useButtonJurisdiction("department");
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 fnAddOrEdit = async (DEPARTMENT_ID, type) => {
  data.addOrEditDialog.visible = true;
  await nextTick();
  data.addOrEditDialog.type = type;
  if (type === "edit") {
    const resData = await getDepartmentView({
      DEPARTMENT_ID,
    });
    data.addOrEditDialog.form = resData.pd;
    data.addOrEditDialog.form.checkedIds = resData.varlist.map(
      (item) => item.SUB_DEPARTMENT_ID
    );
  }
};
const fnDelete = debounce(
  1000,
  async (DEPARTMENT_ID, NAME) => {
    await ElMessageBox.confirm(`确定要删除【${NAME}】吗？`, {
      type: "warning",
    });
    await setDepartmentDelete({ DEPARTMENT_ID });
    ElMessage.success("删除成功");
    fnResetPaginationTransfer();
    data.refreshTreeData = true;
  },
  { atBegin: true }
);
</script>

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