<template>
  <PageWrapper dense>
    <Row>
      <!-- 左边部门选择 -->
      <Col v-bind="{ xs: 24, sm: 24, md: 24, lg: 4 }" class="h-[calc(100vh-80px)]">
        <Skeleton :active="true" :paragraph="{ rows: 8 }" :loading="showTreeSkeleton">
          <BasicTree
            v-if="data.tree.length"
            :fieldNames="{ title: 'label', key: 'id' }"
            :tree-data="data.tree"
            :showLine="{ showLeafIcon: false }"
            :search="true"
            v-model:searchValue="deptSearchText"
            defaultExpandAll
            @select="handleSelectDept"
            v-model:selectedKeys="data.selectDeptId"
          />
          <!-- 仅本人数据权限 可以考虑直接不显示 -->
          <div class="mt-5" v-else>
            <Empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="无部门数据" />
          </div>
        </Skeleton>
      </Col>
      <!-- 右边表格及菜单 -->
      <Col v-bind="{ xs: 24, sm: 24, md: 24, lg: 20 }">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <Space class="<sm:hidden">
              <a-button
                v-auth="'system:post:export'"
                @click="downloadExcel(postExport, '岗位数据', getForm().getFieldsValue())"
                >导出</a-button
              >
              <a-button
                class="<sm:hidden"
                type="primary"
                danger
                @click="multipleRemove(postRemove)"
                v-auth="'system:post:remove'"
                :disabled="!selected"
                >删除</a-button
              >
              <a-button type="primary" @click="handleAdd" v-auth="'system:post:add'">新增</a-button>
            </Space>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                stopButtonPropagation
                dropDownBtnDisplay
                :actions="[
                  {
                    label: '修改',
                    icon: IconEnum.EDIT,
                    type: 'primary',
                    ghost: true,
                    auth: 'system:user:edit',
                    ifShow: record.userId !== 1,
                    onClick: handleEdit.bind(null, record),
                  },
                  {
                    label: '删除',
                    icon: IconEnum.DELETE,
                    type: 'primary',
                    danger: true,
                    ghost: true,
                    auth: 'system:user:remove',
                    ifShow: record.userId !== 1,
                    popConfirm: {
                      placement: 'left',
                      title: `是否删除用户[${record.userName}]-${record.nickName}?`,
                      confirm: handleDelete.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </Col>
    </Row>
    <PostDrawer @register="registerPostDrawer" @reload="reload" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '@/components/Page';
  import { Row, Col, Space, Empty, Skeleton } from 'ant-design-vue';
  import { BasicTree } from '@/components/Tree/index';
  import { postList, postExport, postRemove } from '@/api/system/post';
  import { departmentTree } from '@/api/system/user';
  import type { DeptTree } from '@/api/system/user/model';
  import { onMounted, reactive, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { downloadExcel } from '@/utils/file/download';
  import { columns, formSchemas } from './post.data';
  import { IconEnum } from '@/enums/appEnum';
  import PostDrawer from './PostDrawer.vue';
  import { useDrawer } from '@/components/Drawer';
  import { eachTree } from '@/utils/helper/treeHelper';

  // 缓存
  defineOptions({ name: 'User' });

  interface TreeProps {
    tree: DeptTree[];
    selectDeptId: string[];
  }
  /** 左边搜索框 */
  const deptSearchText = ref<string>('');
  const data: TreeProps = reactive({
    tree: [],
    selectDeptId: [],
  });
  /** 骨架屏加载 */
  const showTreeSkeleton = ref<boolean>(true);

  // 选中部门后刷新表格
  async function handleSelectDept() {
    await reload();
  }

  onMounted(async () => {
    const ret = await departmentTree();
    // 添加部门前图标 不需要 注释eachTree即可
    eachTree(ret, (item) => {
      item.icon = 'el:group';
    });
    data.tree = ret;
    showTreeSkeleton.value = false;
  });

  const [registerTable, { reload, selected, multipleRemove, getForm }] = useTable({
    rowSelection: {
      type: 'checkbox',
    },
    title: '岗位列表',
    showIndexColumn: false,
    api: postList,
    rowKey: 'postId',
    useSearchForm: true,
    formConfig: {
      schemas: formSchemas,
      name: 'post',
      baseColProps: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 6,
      },
      labelWidth: 100,
      resetFunc: async () => {
        data.selectDeptId = [];
        deptSearchText.value = '';
        await reload();
      },
      // 日期选择格式化
      fieldMapToTime: [
        [
          'createTime',
          ['params[beginTime]', 'params[endTime]'],
          ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
        ],
      ],
    },
    columns,
    // 需要添加上部门参数
    beforeFetch(params: Recordable) {
      if (data.selectDeptId.length === 1) {
        params.belongDeptId = data.selectDeptId[0];
      }
      return params;
    },
    actionColumn: {
      width: 220,
      title: '操作',
      key: 'action',
      fixed: 'right',
    },
  });

  const [registerPostDrawer, { openDrawer }] = useDrawer();

  function handleEdit(record: Recordable) {
    openDrawer(true, { update: true, record });
  }

  function handleAdd() {
    openDrawer(true, { update: false });
  }

  async function handleDelete(record: Recordable) {
    await postRemove([record.postId]);
    await reload();
  }
</script>

<style lang="less" scoped>
  /** 去掉表格padding */
  :deep(.vben-basic-table-form-container) {
    padding: 5px;
  }
</style>
