<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable" isMenuTable>
      <template #toolbar>
        <a-button v-auth="'department:approval'" type="primary" @click="handleSetting">
          {{ t('审批专员') }}
        </a-button>
        <a-button type="primary" v-auth="'department:add'" @click="handleCreate">
          {{ t('新增组织') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'name'">
          <a-tag color="processing" v-if="record.departmentType === 1">公司</a-tag>
          <a-tag color="orange" v-else-if="record.departmentType === 0">部门</a-tag>
          &nbsp;{{ record.name }}
        </template>
        <template v-if="column.dataIndex == 'approvalPerson'">
          <a-button type="link" class="!p-0" @click="handleView(record.id)">查看专员 ></a-button>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                auth: 'department:addUser',
                label: '添加人员',
                onClick: handleAddUser.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'department:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                auth: 'department:delete',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DeptDrawer @register="registerDrawer" @success="handleSuccess" />
    <SelectMember
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :width="1060"
      :selectedIds="selectedUserIds"
      :isShowTree="false"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleDeptUser"
    />
  </PageWrapper>
  <ApprovalSetting @register="registerSettingModal" />
  <ApprovalView @register="registerViewModal" />
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';

  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { PageWrapper } from '/@/components/Page';
  import DeptDrawer from './components/DeptDrawer.vue';
  import ApprovalSetting from './components/ApprovalSetting.vue';
  import ApprovalView from './components/ApprovalView.vue';
  import { Switch } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermission } from '/@/hooks/web/usePermission';
  // import { useI18n } from 'vue-i18n';
  import { SelectMember } from '/@/components/SelectOrganizational/index';
  import {
    deleteDepartment,
    getDepartmentEnabledTree,
    getDepartmentUserList,
    updateDepartmentUser,
    getApprovalList,
  } from '/@/api/system/department';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('组织名称'),
      dataIndex: 'name',
      width: 400,
      align: 'left',
      resizable: true,
    },
    {
      title: '组织编码',
      dataIndex: 'code',
      width: 120,
      resizable: true,
    },

    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 100,
      resizable: true,
      customRender: ({ record }) => {
        const enabledMark = record.enabledMark == 1 ? true : false;

        return h(Switch, { checked: enabledMark });
      },
    },
    {
      title: '审批专员',
      dataIndex: 'approvalPerson',
      resizable: true,
      width: 120,
    },
    {
      title: t('主页'),
      dataIndex: 'website',
      resizable: true,
    },
    {
      title: t('地址'),
      dataIndex: 'address',
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      resizable: true,
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('组织名称'),
      component: 'Input',
    },
    {
      field: 'code',
      label: t('组织编码'),
      component: 'Input',
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
    },
  ];

  export default defineComponent({
    name: 'DeptManagement',
    components: {
      BasicTable,
      TableAction,
      DeptDrawer,
      PageWrapper,
      SelectMember,
      ApprovalSetting,
      ApprovalView,
    },
    setup() {
      const { notification } = useMessage();
      const { hasPermission } = usePermission();

      const [registerDrawer, { openModal }] = useModal();
      const [registerSettingModal, { openModal: openSettingModal }] = useModal();
      const [registerViewModal, { openModal: openViewModal }] = useModal();

      const [registerTable, { reload }] = useTable({
        title: t('组织列表'),
        api: getDepartmentEnabledTree,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          actionColOptions: { span: 16 },
          showResetButton: false,
        },
        beforeFetch: (params) => {
          return {
            ...params,
            isOrg: 1,
          };
        },
        pagination: {
          pageSize: 20,
        },
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        showIndexColumn: false,
        actionColumn: {
          width: 180,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('department:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });

      const visible = ref<boolean>(false);
      const selectedUserIds = ref<string[]>([]);
      const deptId = ref('');

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        deleteDepartment([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }
      function handleAddUser(record: Recordable) {
        deptId.value = record.id;
        getDepartmentUserList({ id: record.id }).then((res) => {
          selectedUserIds.value = res.map((it) => {
            return it.id;
          });
          visible.value = true;
        });
      }

      function handleDeptUser(v) {
        updateDepartmentUser({ id: deptId.value, userIds: v }).then(() => {
          notification.success({
            message: '添加人员',
            description: t('成功'),
          });
        });
      }

      function handleSuccess() {
        reload();
      }

      async function handleSetting() {
        const datasource = await getApprovalList();
        openSettingModal(true, { datasource });
      }

      function handleView(id) {
        openViewModal(true, { id });
      }

      return {
        registerTable,
        registerDrawer,
        registerSettingModal,
        registerViewModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleAddUser,
        handleDeptUser,
        handleSuccess,
        handleView,
        visible,
        selectedUserIds,
        t,
        handleSetting,
      };
    },
  });
</script>
