<script setup lang="tsx">
import { nextTick, useTemplateRef } from 'vue';
import { NButton, NPopconfirm, NSwitch } from 'naive-ui';
import {
  fetchAddUser,
  fetchDeleteUser,
  fetchEditUser,
  fetchEditUserStatus,
  fetchExportUser,
  fetchGetImportRecordList,
  fetchGetUserList
} from '@/service/api/government/user-list';
import { fetchGetLoginUserList } from '@/service/api/common';
import { fetchGetAllChannelList } from '@/service/api/goods-center/store-goods';
import { useAuth } from '@/hooks/business/auth';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import SVGIcon from '@/components/custom/svg-icon.vue';
const importTemplateRef = useTemplateRef('importTemplateRef');
const columns: NaiveUI.TableColumn<Api.government.userList>[] = [
  {
    key: 'channelName',
    title: '所属企业',
    align: 'center'
  },
  {
    key: 'realName',
    title: '员工姓名',
    align: 'center'
  },
  {
    key: 'userMobile',
    title: '手机号码',
    align: 'center'
  },
  {
    key: 'total',
    title: '总充值积分',
    align: 'center'
  },
  {
    key: 'available',
    title: '当前可用积分',
    align: 'center'
  },
  {
    key: 'expired',
    title: '已过期积分',
    align: 'center'
  },
  {
    key: 'used',
    title: '已消耗积分',
    align: 'center'
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    render: row => {
      return (
        <NSwitch
          uncheckedValue={0}
          checkedValue={1}
          value={row.status}
          disabled={!useAuth().hasAuth('user:list:statusbtn')}
          onUpdate:value={val => {
            row.status = val;
            editStatus(row);
          }}
        ></NSwitch>
      );
    }
  }
];

const [registerTable, { refresh, setTableLoading, setFieldsValue: setSearchValues, getSeachForm }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'channelNoList',
        label: '所属企业',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetLoginUserList,
          labelFeild: 'channelName',
          valueFeild: 'channelNo',
          multiple: true,
          onUpdateValue: () => {
            nextTick(() => {
              handleSearch();
            });
          },
          getOptions: async (options: any) => {
            await setSearchValues({ channelNoList: [options[0].channelNo] });
            handleSearch();
          }
        }
      },
      {
        field: 'realName',
        label: '员工姓名',
        component: 'NInput'
      },
      {
        field: 'userMobile',
        label: '手机号码',
        component: 'NInput'
      },
      {
        field: 'userAttrType',
        label: '人员属性',
        component: 'dictSelect',
        componentProps: {
          dictCode: 'user_attr_type',
          immediate: true
        },
        show: useAuth().hasAuth('user:attr:type')
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'memberId',
    title: '员工列表',
    showAddButton: useAuth().hasAuth('user:list:add'),
    defaultParamsNotReset: 'channelIdList'
  }
});
const [registerModalTable] = useTable({
  tableConfig: {
    keyField: 'id',
    title: '导入记录',
    showTableHeaderAction: false,
    showSearch: false,
    minHeight: 400
  }
});
const failColumns: NaiveUI.TableColumn<Api.government.importRecordList>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'taskName',
    title: '任务名称',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center'
  },
  {
    key: 'operator',
    title: '操作人',
    align: 'center'
  },
  {
    key: 'result',
    title: '状态',
    align: 'center',
    width: 240,
    render(row) {
      return (
        <div class={'flex items-center'}>
          共{Number(row.success) + Number(row.error)}条，成功：{row.success}，
          <span class={'flex items-center text-red-500'}>
            失败：
            {row.error}
            {row.error != 0 && (
              <div onClick={() => hanleExportFailure(row.batchNo)}>
                <SVGIcon
                  icon={'tdesign:download'}
                  class={'ml-1 cursor-pointer text-20px'}
                  style={'color:var(--n-loading-color)'}
                ></SVGIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];
async function hanleExportFailure(batchNo: string) {
  await commonExport(`/smqjh-system/api/v1/members/enterprise/downloadErrorExcel`, { batchNo }, '员工失败列表.xlsx');
}
async function handleDelete(row: Api.government.userList) {
  setTableLoading(true);
  await fetchDeleteUser(row.memberId);
  // console.log(row, 'row');

  refresh();
}
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue }] = useModalFrom({
  modalConfig: {
    title: '员工 ',
    width: 600,
    isShowHeaderText: true,
    height: 400
  },
  formConfig: {
    schemas: [
      {
        label: '',
        field: 'memberId',
        component: 'NInput',
        show: false
      },
      {
        field: 'realName',
        label: '员工姓名',
        component: 'NInput',
        required: true
      },
      {
        field: 'userMobile',
        label: '手机号码',
        component: 'NInput',
        required: true,
        componentProps: {
          maxlength: 11
        },
        rules: [
          {
            // pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'input'],
            required: true,
            validator: (_rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入手机号'));
              } else if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号'));
              }
              callback();
              return true;
            }
          }
        ]
      },
      {
        field: 'channelId',
        label: '所属企业',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetAllChannelList,
          labelFeild: 'channelName',
          valueFeild: 'id'
        },
        required: true
      },
      {
        field: 'userAttrType',
        label: '人员属性',
        component: 'dictSelect',
        componentProps: {
          dictCode: 'user_attr_type',
          immediate: true,
          disabledLables: ['全部']
        },
        required: true
      }
    ],
    gridProps: {
      cols: '1'
    },
    labelWidth: 120
  }
});
const [registerModalFail, { openModal: openModalFail }] = useModal({
  title: '导入记录',
  height: 600,
  showFooter: false,
  width: 1200
});
async function handleSubmit() {
  const form = await getFieldsValue();
  if (form.memberId) {
    await fetchEditUser(form);
  } else {
    await fetchAddUser(form);
  }
  closeModal();
  refresh();
}

function editStatus(row: Recordable) {
  const obj = {
    memberId: row.memberId,
    channelId: row.channelId,
    realName: row.realName,
    userMobile: row.userMobile,
    userAttrType: row.userAttrType,
    status: row.status
  };
  fetchEditUserStatus(obj);
}

async function edit(row: Recordable) {
  openModal(row);
  setFieldsValue(row);
}

function openImportModal() {
  importTemplateRef.value?.openModal();
}
async function handleSubmitImport(file: File) {
  const { error } = await fetchExportUser({ file });
  if (!error) {
    importTemplateRef.value?.closeModal();
    refresh();
  }
  importTemplateRef.value?.setSubLoading(false);
}
function handleSearch() {
  refresh();
}
async function handleExport() {
  setTableLoading(true);
  try {
    await commonExport('/smqjh-system/api/v1/members/enterprise/export', getSeachForm(), '员工列表.xlsx');
  } finally {
    setTableLoading(false);
  }
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :immediate="false" :api="fetchGetUserList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton
          v-if="useAuth().hasAuth('user:list:edit')"
          size="small"
          ghost
          type="primary"
          :disabled="Boolean(row.available)"
          @click="edit(row)"
        >
          编辑
        </NButton>
        <NPopconfirm v-if="useAuth().hasAuth('user:list:del')" @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost :disabled="Boolean(row.available)">删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
      <template #prefix="{ loading }">
        <NSpace>
          <NButton
            v-if="useAuth().hasAuth('user:list:export-btn')"
            size="small"
            :loading="loading"
            @click="handleExport"
          >
            导出
          </NButton>
          <NButton v-if="useAuth().hasAuth('user:list:export')" size="small" @click="openImportModal">导入员工</NButton>
          <NButton v-if="useAuth().hasAuth('user:list:exportRecord')" size="small" @click="openModalFail">
            导入记录
          </NButton>
        </NSpace>
      </template>
    </ZTable>
    <ZImportTemplate
      ref="importTemplateRef"
      url="/smqjh-system/api/v1/members/enterprise/downloadXlsx"
      template-text="员工导入模版.xlsx"
      modal-text="导入员工"
      @submit="handleSubmitImport"
    ></ZImportTemplate>
    <BasicModal @register="registerModalFail">
      <LayoutTable>
        <ZTable
          :columns="failColumns"
          :show-table-action="false"
          :api="fetchGetImportRecordList"
          @register="registerModalTable"
        ></ZTable>
      </LayoutTable>
    </BasicModal>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
