<template>
  <div class="p-4">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button
          v-power="[RoleEnum.COMPANY_ADMIN, RoleEnum.PLAT_ADMIN]"
          type="primary"
          @click="handleCreate"
          >新增</a-button
        >
        <a-button
          v-power="[RoleEnum.COMPANY_ADMIN, RoleEnum.PLAT_ADMIN]"
          type="error"
          @click="handleExport"
          >导出数据</a-button
        >
      </template>
      <template #headerTop v-if="getCheckRole([RoleEnum.COMPANY_ADMIN])">
        <Alert
          :message="`剩余带看权益为 ${surplusSubNum.lookNum} 个、拍摄权益为 ${surplusSubNum.shotNum} 个`"
          type="info"
        />
      </template>
      <template #role="{ record }">
        {{ renderRoleType(record.role) }}
      </template>
      <template #status="{ record }">
        {{ renderStatus(record.status) }}
      </template>
      <template #createTime="{ record }">
        <Time :value="record.createTime" mode="datetime" />
      </template>
      <template #head="{ record }">
        <TableImg
          :size="80"
          :simpleShow="true"
          style="border-radius: 50%"
          :imgList="[record.head || headerImg]"
        />
      </template>
      <!-- , -->
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              onClick: handleEdit.bind(null, record),
            },
            {
              color: 'warning',
              label: t('routes.staff.setpaswd'),
              onClick: handleOpenModal.bind(null, record),
            },
            {
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <DetailsModal @register="registerDetail" @ok="reload" />
    <SetpaswordModal @register="register" @reload="reload" />
    <DelListModal @register="registerDelList" @reload="reload" />
  </div>
</template>
<script lang="ts">
  import headerImg from '/@/assets/images/header.jpg';
  import { defineComponent, computed, onMounted, ref, reactive } from 'vue';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormProps,
    TableAction,
    TableImg,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { uploadApi } from '/@/api/sys/upload';
  import SetpaswordModal from './setpaswordModal.vue';
  import DetailsModal from './detailsModal.vue';
  import DelListModal from './delListModal.vue';
  import { Alert } from 'ant-design-vue';
  // import { h } from 'vue';
  import { ListApi, delApi, preDelApi, getNumByStaff, exportApi } from '/@/api/staff/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { useGo } from '/@/hooks/web/usePage';
  import { Time } from '/@/components/Time';
  import { useUserStore } from '/@/store/modules/user';
  import { ExportParams } from '/@/api/staff/model';
  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      Time,
      SetpaswordModal,
      DetailsModal,
      DelListModal,
      Alert,
      TableImg,
    },
    emits: ['register'],
    setup() {
      const [register, { openModal }] = useModal();
      const surplusSubNum = ref({
        lookNum: 0,
        shotNum: 0,
      });
      const [registerDetail, { openModal: openDetailModal }] = useModal();
      const [registerDelList, { openModal: openDelListModal }] = useModal();
      const { createConfirm, createMessage } = useMessage();
      const userStore = useUserStore();
      const { getCheckRole } = userStore;
      const roleList = computed(() => userStore.getRoleList);
      console.log('getRoleList', roleList);
      const go = useGo();
      const { t } = useI18n();
      onMounted(() => {
        getNumByStaffData();
      });

      let searchInfo: ExportParams = reactive({
        staffName: '',
        staffPhone: '',
      });

      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          fixed: 'left',
          width: 60,
        },
        {
          title: t('routes.staff.deptName'),
          dataIndex: 'companyName',
          width: 160,
        },
        // {
        //   title: t('routes.staff.userName'),
        //   dataIndex: 'userName',
        //   width: 80,
        // },
        {
          title: t('routes.staff.userName'),
          dataIndex: 'nickName',
          width: 80,
        },
        {
          title: '手机',
          dataIndex: 'phone',
          width: 160,
        },

        {
          title: t('common.roleName'),
          dataIndex: 'roleName',
          // slots: { customRender: 'role' },
          sorter: true,
          width: 80,
        },
        {
          title: t('routes.staff.permList'),
          dataIndex: 'permList',
          // slots: { customRender: 'status' },
          // sorter: true,
          width: 80,
          customRender: ({ record }) => {
            return record.permList && record.permList.join();
          },
        },
        {
          title: '头像',
          dataIndex: 'head',
          slots: { customRender: 'head' },
          width: 130,
        },

        {
          title: t('routes.staff.createTime'),
          dataIndex: 'createTime',
          slots: { customRender: 'createTime' },
          width: 130,
        },
        {
          title: '操作',
          dataIndex: '',
          ifShow: !getCheckRole('tourist'),
          slots: { customRender: 'action' },
          fixed: 'right',
          width: 150,
        },
      ];

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'staffName',
            label: t('routes.staff.userName'),
            component: 'Input',
            componentProps: {
              maxLength: 15,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'staffPhone',
            label: t('routes.corporation.phone'),
            component: 'Input',
            componentProps: {
              maxLength: 15,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
        ],
      };

      const [registerTable, { reload }] = useTable({
        title: t('routes.staff.staffList'),
        api: ListApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'id',
        pagination: { pageSize: 20 },
        afterFetch: (T) => {
          getNumByStaffData();
          return T;
        },
        bordered: true,
        searchInfo: searchInfo,
        handleSearchInfoFn(data) {
          searchInfo = Object.assign(searchInfo, data);
        },
      });

      function renderRoleType(type: number): string {
        switch (type) {
          case 0:
            return t('routes.staff.roleType.0');
          case 1:
            return t('routes.staff.roleType.1');
          default:
            return '';
        }
      }
      function renderStatus(type: number): string {
        switch (type) {
          case 1:
            return t('common.normal');
          case 0:
            return t('common.unNormal');
          default:
            return '';
        }
      }
      function handleOpenModal(record: Recordable) {
        openModal(true, record);
      }
      function handleCreate() {
        // if (
        //   getCheckRole([RoleEnum.COMPANY_ADMIN]) &&
        //   surplusSubNum.value.lookNum == 0 &&
        //   surplusSubNum.value.shotNum == 0
        // ) {
        //   return createMessage.error('新增失败，可添加员工数量为0个');
        // }
        openDetailModal(true, {});
      }
      function handleEdit(record: Recordable) {
        openDetailModal(true, record);
      }
      function getNumByStaffData() {
        getNumByStaff({}).then((res) => {
          surplusSubNum.value.lookNum = res.lookNum;
          surplusSubNum.value.shotNum = res.shotNum;
        });
      }
      async function handleDelete(record) {
        let check = await preDelApi(record.id); //
        if (Array.isArray(check)) {
          return openDelListModal(true, {
            ...record,
            option: check,
          });
        }
        createMessage.success(t('common.optSuccess'));
        reload();
        // handDelconfirm(record);
      }
      function handDelconfirm(record) {
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: `此操作将对${record.userName}进行删除, 是否继续?`,
          onOk: async () => {
            await delApi({ userId: record.id });
            reload();
          },
        });
      }
      async function handleExport() {
        const data = await exportApi(searchInfo);
        const downloadBlob = new Blob([data], {
          type: 'application/msexcel',
        });
        const url = URL.createObjectURL(downloadBlob);
        const a: HTMLAnchorElement = document.createElement('a');
        document.body.appendChild(a);
        a.style.display = 'none';
        a.href = url;
        const name = new Date().getTime();
        a.download = `${name}.csv`;
        a.click();
        window.URL.revokeObjectURL(url);
      }

      return {
        registerTable,
        registerDetail,
        registerDelList,
        openDelListModal,
        createMessage,
        handDelconfirm,
        headerImg,
        t,
        reload,
        go,
        renderRoleType,
        renderStatus,
        handleCreate,
        handleOpenModal,
        register,
        handleEdit,
        handleDelete,
        uploadApi: uploadApi as any,
        RoleEnum,
        surplusSubNum,
        getCheckRole,
        getNumByStaffData,
        handleExport,
      };
    },
  });
</script>
