<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <DeptTree @select="handleSelect" />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable>
        <template #toolbar>
          <a-button type="primary" v-auth="'post:add'" @click="handleCreate">
            {{ t('新增岗位') }}
          </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '添加人员',
                auth: 'post:addPeople',
                onClick: handleAddUser.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'post:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'post:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <PostDrawer @register="registerModal" @success="handleSuccess" />
    <SelectDepartment
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedList="selectedUserList"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleUserpost"
    />
  </ResizePageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';

  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getTreePostList,
    deletePost,
    getPostUserList,
    updatePostByUser,
    updatePostStatus,
  } from '/@/api/system/post';
  import { SelectDepartment } from '/@/components/SelectOrganizational/index';
  import PostDrawer from './components/PostDrawer.vue';
  import { Switch } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  // import { PageWrapper } from '/@/components/Page';
  import { ResizePageWrapper } from '/@/components/Page';
  import { usePermission } from '/@/hooks/web/usePermission';

  import DeptTree from '../user/components/DeptTree.vue';
  import { getUserInfo } from '/@/api/system/login';
  import { UserInfo } from '/#/store';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { cloneDeep } from 'lodash-es';
  import { getFileUrl } from '/@/utils/event/design';

  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('岗位名称'),
      dataIndex: 'name',
      align: 'left',
      sorter: true,
      resizable: true,
    },
    {
      title: t('岗位编码'),
      dataIndex: 'code',
      sorter: true,
      resizable: true,
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      resizable: true,
      sorter: true,
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          onChange(checked: boolean) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 0;
            const { createMessage } = useMessage();
            updatePostStatus(record.id, newStatus)
              .then(() => {
                record.enabledMark = newStatus;
                createMessage.success(t('已成功修改岗位状态'));
              })
              .catch(() => {
                createMessage.error(t('修改岗位状态失败'));
              })
              .finally(() => {
                record.pendingStatus = false;
              });
          },
        });
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      sorter: true,
      resizable: true,
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('岗位名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'code',
      label: t('岗位编码'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { lg: 8, md: 12, sm: 12 },
    },
  ];

  export default defineComponent({
    name: 'PostManagement',
    components: {
      BasicTable,
      PostDrawer,
      TableAction,
      ResizePageWrapper,
      DeptTree,
      SelectDepartment,
    },
    setup() {
      const { notification } = useMessage();
      const selectDeptId = ref('');
      const postId = ref('');
      const selectedUserList = ref<any>([]);
      const visible = ref<boolean>(false);
      const { hasPermission } = usePermission();

      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload, getDataSource }] = useTable({
        title: t('岗位列表'),
        api: getTreePostList,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          actionColOptions: { span: 16 },
          showResetButton: false,
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, deptId: selectDeptId.value };
        },
        rowKey: 'id',
        pagination: {
          pageSize: 20,
        },
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        showIndexColumn: false,
        defaultExpandAllRows: true,
        actionColumn: {
          width: 170,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('post:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });
      function handleSelect(deptId = '') {
        selectDeptId.value = deptId;
        reload({ searchInfo: { deptId: deptId } });
      }
      function handleCreate() {
        openModal(true, {
          isUpdate: false,
          treeData: getDataSource(),
          deptId: selectDeptId.value,
        });
      }

      function findSelf(data, id) {
        if (!data || !data.length) return;
        data?.map((item) => {
          if (item.id === id) {
            item.disabled = true;
          } else if (item.children) {
            findSelf(item.children, id);
          }
        });
      }

      function handleEdit(record: Recordable) {
        const datasource = cloneDeep(getDataSource());
        findSelf(datasource, record.id);
        openModal(true, {
          record,
          isUpdate: true,
          treeData: datasource,
          deptId: selectDeptId.value,
        });
      }
      function handleAddUser(record: Recordable) {
        postId.value = record.id;
        getPostUserList({ id: record.id }).then((res) => {
          selectedUserList.value = res.map((item) => {
            return {
              name: item.name, //姓名
              id: item.id, //ID
              code: item.code, //code
              gender: !isNaN(item.gender) ? item.gender : -1, //性别
            };
          });
          visible.value = true;
        });
      }
      function handleDelete(record: Recordable) {
        deletePost([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('删除岗位'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleUserpost(v, type) {
        let paramas;
        if (type === 0) {
          paramas = { type, deptId: selectDeptId.value, postId: postId.value, userIds: v };
        } else {
          paramas = { type, departmentIds: v, deptId: selectDeptId.value, postId: postId.value };
        }
        updatePostByUser(paramas).then(() => {
          reload();
          notification.success({
            message: t('岗位关联人员成功'),
            description: t('成功'),
          });
          getUserInfo().then((userInfoResult) => {
            const { roles = [] } = userInfoResult;
            const userStore = useUserStore();
            const userInfo = userInfoResult as unknown as UserInfo;
            userInfo.avatar = getFileUrl(userInfo, 'avatar');
            userStore.setUserInfo(userInfo);
            userStore.setRoleList(roles);
          });
        });
      }
      function handleSuccess() {
        reload();
      }

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleAddUser,
        handleUserpost,
        visible,
        selectedUserList,
        t,
      };
    },
  });
</script>
