<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm, NSwitch } from 'naive-ui';
import {
  fetchAddUser,
  fetchDeleteUser,
  fetchEditUser,
  fetchExportUser,
  fetchGetImportRecordList,
  fetchGetUserList
} from '@/service/api/government/user-list';
import { fetchGetAllChannelList } from '@/service/api/goods/store-goods';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import type { ModalMethods } from '@/components/zt/Modal/types';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import SVGIcon from '@/components/custom/svg-icon.vue';

const importTemplateRef = ref<ModalMethods>();
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}
          onUpdate:value={val => {
            row.status = val;
            fetchEditUser(row);
          }}
        ></NSwitch>
      );
    }
  }
];

const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'channelId',
        label: '所属企业',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetAllChannelList,
          labelFeild: 'channelName',
          valueFeild: 'id'
        }
      },
      {
        field: 'realName',
        label: '员工姓名',
        component: 'NInput'
      },
      {
        field: 'userMobile',
        label: '手机号码',
        component: 'NInput'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'userId',
    title: '员工列表',
    showAddButton: true
  }
});
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>
      );
    }
  }
];
function hanleExportFailure(batchNo: string) {
  window.open(
    `${import.meta.env.VITE_SERVICE_BASE_URL}/admin/enterprise/downloadErrorExcel?batchNo=${batchNo}`,
    '_blank'
  );
}
async function handleDelete(row: Api.government.userList) {
  setTableLoading(true);
  await fetchDeleteUser(row.userId);
  console.log(row, 'row');

  refresh();
}
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue }] = useModalFrom({
  modalConfig: {
    title: '员工 ',
    width: 600,
    isShowHeaderText: true,
    height: 200
  },
  formConfig: {
    schemas: [
      {
        label: '',
        field: 'userId',
        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']
          }
        ]
      },
      {
        field: 'channelId',
        label: '所属企业',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetAllChannelList,
          labelFeild: 'channelName',
          valueFeild: 'id'
        },
        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.userId) {
    await fetchEditUser(form);
  } else {
    await fetchAddUser(form);
  }
  closeModal();
  refresh();
}

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);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetUserList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" :disabled="Boolean(row.available)" @click="edit(row)">编辑</NButton>
        <NPopconfirm @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost :disabled="Boolean(row.available)">删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
      <template #prefix>
        <NSpace>
          <NButton size="small" @click="openImportModal">导入员工</NButton>
          <NButton size="small" @click="openModalFail">导入记录</NButton>
        </NSpace>
      </template>
    </ZTable>
    <ZImportTemplate
      ref="importTemplateRef"
      url="/admin/enterprise/downloadExcel"
      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>
