<template>
  <div>
    <BasicTable @register="registerTable" :searchInfo="modelRef">
      <template #toolbar>
        <a-button v-power="[RoleEnum.PLAT_ADMIN]" type="primary" @click="handleOpenModal">
          新增</a-button
        >
      </template>
      <template #status="{ record }">
        {{ renderStatus(record.state) }}
      </template>
      <template #createTime="{ record, field }">
        <Time :value="record[field]" mode="datetime" />
      </template>
      <!-- onClick: handleOpenModal.bind(null, record), -->
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '查看',
              ifShow: !!record.userId,
              onClick: handleDelete.bind(null, record),
            },
            {
              label: '绑定',
              color: 'success',
              ifShow: (record.state == 0 || record.state == 1) && !record.userId,
              onClick: handleDelete.bind(null, record),
            },
            {
              label: '解绑',
              ifShow:
                getCheckRole([RoleEnum.PLAT_ADMIN]) &&
                (record.state == 0 || record.state == 1) &&
                !!record.userId &&
                dayjs(record.activationTime).isAfter(dayjs()),
              color: 'error',
              onClick: handleUpBind.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <addModal @register="register" @update="reload" />
    <BindModal @register="registerDelList" @update="reload" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, onMounted, ref, watch, reactive } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormProps, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { uploadApi } from '/@/api/sys/upload';
  import BindModal from './BindModal.vue';
  import addModal from './addModal.vue';
  import { staffList, unbindRights } from '/@/api/rightsEnterprises/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import dayjs from 'dayjs';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { useGo } from '/@/hooks/web/usePage';
  import { Time } from '/@/components/Time';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    name: 'StaffList',
    components: {
      BasicTable,
      TableAction,
      Time,
      BindModal,
      addModal,
      // DelListModal,
    },
    props: {
      companyInfo: {
        type: Object,
        default: function () {
          return {};
        },
      },
    },
    setup(props) {
      const [register, { openModal }] = useModal();
      const surplusSubNum = ref({
        lookNum: 0,
        shotNum: 0,
      });
      const [registerDetail, { openModal: openDetaileModal }] = useModal();
      const [registerDelList, { openModal: openDelListeModal }] = useModal();
      const { createConfirm, createMessage } = useMessage();
      const userStore = useUserStore();
      const { getCheckRole } = userStore;
      const userinfo = computed(() => userStore.getUserInfo);
      // const {companyInfo} = toRefs(props)
      const modelRef = reactive({
        companyId: userinfo.value.companyId,
        companyName: userinfo.value.companyName,
        companyPhone: userinfo.value.phone,
      });
      const go = useGo();
      const { t } = useI18n();
      watch(
        () => props.companyInfo,
        (newProps) => {
          modelRef.companyId = newProps.companyId;
          modelRef.companyName = newProps.companyName;
          modelRef.companyPhone = newProps.companyPhone;
          reload();
        },
        {
          deep: true,
        },
      );
      onMounted(() => {
        getNumByStaffData();
      });

      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          fixed: 'left',
          ifShow: false,
          width: 0,
        },
        {
          title: t('routes.rightsEnterprises.permName'),
          dataIndex: 'permName',
          width: 160,
        },
        {
          title: t('routes.staff.userName'),
          dataIndex: 'staffName',
          width: 80,
        },
        {
          title: '手机',
          dataIndex: 'staffPhone',
          width: 160,
        },

        {
          title: t('common.roleName'),
          dataIndex: 'staffRoleName',
          // slots: { customRender: 'role' },
          sorter: true,
          width: 80,
        },
        {
          title: t('routes.rightsEnterprises.createTime'),
          dataIndex: 'createTime',
          // slots: { customRender: 'createTime' },
          width: 160,
        },
        {
          title: t('routes.rightsEnterprises.activationTime'),
          dataIndex: 'activationTime',
          // slots: { customRender: 'createTime' },
          width: 160,
        },
        {
          title: t('routes.rightsEnterprises.expirationTime'),
          dataIndex: 'expirationTime',
          // slots: { customRender: 'createTime' },
          width: 160,
        },
        {
          title: t('common.state'),
          dataIndex: 'status',
          slots: { customRender: 'status' },
          width: 80,
        },
        {
          title: '操作',
          dataIndex: '',
          ifShow: !getCheckRole('tourist'),
          slots: { customRender: 'action' },
          fixed: 'right',
          width: 100,
        },
      ];

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

      const [registerTable, { reload }] = useTable({
        title: t('routes.rightsEnterprises.staffList'),
        api: staffList,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: true,
        rowKey: 'id',
        immediate: userinfo.value.companyId ? true : false,
        pagination: { pageSize: 20 },
        searchInfo: modelRef,
        afterFetch: (T) => {
          getNumByStaffData();
          return T;
        },
        bordered: true,
        sortFn: (sortInfo) => {
          let order = sortInfo.order && sortInfo.order.replace('end', '');
          return { ...sortInfo, sidx: sortInfo.field, order: order };
        },
      });

      function renderStatus(type: number): string {
        switch (type) {
          // case 0:
          //   return t('routes.rightsEnterprises.state.0');
          // case 1:
          //   return t('routes.rightsEnterprises.state.1');
          case 2:
            return t('routes.rightsEnterprises.state.2');
          default:
            return t('routes.rightsEnterprises.state.9');
        }
      }
      function handleOpenModal(record: Recordable) {
        console.log('userinfo', userinfo);
        openModal(true, {
          ...record,
          ...modelRef,
        });
      }
      function handleCreate() {
        // if (
        //   getCheckRole([RoleEnum.COMPANY_ADMIN]) &&
        //   surplusSubNum.value.lookNum == 0 &&
        //   surplusSubNum.value.shotNum == 0
        // ) {
        //   return createMessage.error('新增失败，可添加员工数量为0个');
        // }
        openDetaileModal(true, {});
      }
      function handleEdit(record: Recordable) {
        openDetaileModal(true, record);
      }
      function getNumByStaffData() {
        // getNumByStaff({}).then((res) => {
        //   surplusSubNum.value.lookNum = res.lookNum;
        //   surplusSubNum.value.shotNum = res.shotNum;
        // });
      }
      async function handleDelete(record) {
        return openDelListeModal(true, {
          ...record,
          ...modelRef,
        });
      }
      function handleUpBind(record) {
        createConfirm({
          iconType: 'warning',
          title: '解绑权益',
          content: `解绑权益后，公司员工的权益时间将缩减，是否继续解绑？`,
          onOk: async () => {
            await unbindRights({ id: record.id });
            reload();
          },
        });
      }
      return {
        registerTable,
        registerDetail,
        registerDelList,
        openDelListeModal,
        createMessage,
        modelRef,
        handleUpBind,
        t,
        reload,
        go,
        renderStatus,
        handleCreate,
        handleOpenModal,
        register,
        handleEdit,
        handleDelete,
        uploadApi: uploadApi as any,
        RoleEnum,
        surplusSubNum,
        getCheckRole,
        getNumByStaffData,
        dayjs,
      };
    },
  });
</script>
