<template>
  <PageWrapper>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        row-key="deptId"
        :tableSetting="{
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :pagination="false"
      >
        <template #tableTitle>
          <el-space align="center">
            <el-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <el-icon>
                  <FileAddOutlined />
                </el-icon>
              </template>
              添加
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>

    <CreateDrawer_shangfei
      ref="createDrawerRef"
      :title="drawerTitle"
      :deptList="tableData"
      @change="reloadTable"
      v-if="disableDepartmentEdit"
    />
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :deptList="tableData"
      :data-source="currentDept"
      :width="450"
      @change="reloadTable"
      v-else
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { BasicTable, TableAction, BasicColumn } from '@/components/Table';
  import { getAllDepartments , deleteDepartments} from '@/api/auth/dept';
  import { FileAddOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import CreateDrawer_shangfei from './CreateDrawer-shangfei.vue';
  import { columns } from './columns';
  import { useGlobSetting } from '@/hooks/setting';
  import type { DeptTreeItem } from '@/types/dept/type';

  const globSetting = useGlobSetting();
  const disableDepartmentEdit = globSetting.disableDepartmentEdit;

  const message = ElMessage;
  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref<string>();
  const tableData = ref<any[]>([]);
  const createDrawerRef = ref();
  const drawerTitle = ref('添加部门');
  const currentDept = ref<DeptTreeItem>({
    id: null,
    deptName: '',
    parentId: null,
    orderNum: undefined,
    isDisabled: 0,
    createdBy: 0,
    updatedBy: 0,
    createdAt: '',
    updatedAt: '',
    isDeleted: 0,
    tenantId: 0
  });

  const actionColumn: BasicColumn = reactive({
    width: 150,
    title: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      const { index } = record;
      if (index === 0 && disableDepartmentEdit) return null;
      return h(TableAction as any, {
        actions: [
          {
            label: '删除',
            isConfirm: true,
            popConfirm: {
              onConfirm: handleDelete.bind(null, record.row),
              title: '您确定要删除吗？',
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            },
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record.row),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    const result = await getAllDepartments();
    tableData.value = result;
    return { list: result };
  };

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value
      .filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.username;
      })
      .join('，');
  }

  function reloadTable() {
    basicTableRef.value.reload();
  }

  function openCreateDrawer() {
    drawerTitle.value = '添加部门';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function handleEdit(record: Recordable) {
    drawerTitle.value = '编辑部门';
    currentDept.value = record;
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.deptId);
  }

  function handleDelete(record: Recordable) {
    deleteDepartments(record.id).then(() => {
      message.success('删除成功');
      reloadTable();
    });
  }
</script>
