<script setup lang="tsx">
import { nextTick, ref, useTemplateRef } from 'vue';
import {
  fetchGetFailPointsList,
  fetchGetPointsList,
  fetchGetPointsOutList,
  fetchImportPoints
} from '@/service/api/government/points';
import { fetchGetLoginUserList } from '@/service/api/common';
import { useAuth } from '@/hooks/business/auth';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import type { FormSchema } from '@/components/zt/Form/types/form';
import SVGIcon from '@/components/custom/svg-icon.vue';
const importTemplateRef = useTemplateRef('importTemplateRef');
const loading = ref(false);

const ModalColumns: NaiveUI.TableColumn<Api.government.PointsRecharge>[] = [
  {
    key: 'channelName',
    title: '所属企业',
    align: 'center'
  },
  {
    key: 'userName',
    title: '员工姓名',
    align: 'center'
  },
  {
    key: 'userPhone',
    title: '员工手机号',
    align: 'center'
  },
  {
    key: 'points',
    title: '充值积分',
    align: 'center'
  },
  {
    key: 'expiryDate',
    title: '过期日期',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '创建时间',
    align: 'center'
  }
];
const outColumns: NaiveUI.TableColumn<Api.government.PointsRechargeVO>[] = [
  {
    key: 'channelName',
    title: '所属企业',
    align: 'center'
  },
  {
    key: 'totalPoints',
    title: '总充值积分',
    align: 'center'
  },
  {
    key: 'totalUserCount',
    title: '总充值人次',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '操作时间',
    align: 'center'
  }
];
const searchSchemas: FormSchema[] = [
  {
    field: 'channelNoList',
    label: '所属企业',
    component: 'ApiSelect',
    componentProps: {
      api: fetchGetLoginUserList,
      labelFeild: 'channelName',
      valueFeild: 'channelNo',
      multiple: true,
      onUpdateValue: () => {
        nextTick(() => {
          handleSearch();
        });
      },
      getOptions: async (options: any) => {
        await setSearchForm({ channelNoList: [options[0].channelNo] });
        handleSearch();
      }
    }
  },
  {
    field: 'userAttrType',
    label: '人员属性',
    component: 'dictSelect',
    componentProps: {
      dictCode: 'user_attr_type',
      immediate: true
    },
    show: useAuth().hasAuth('user:attr:type')
  },
  {
    field: 'userPhone',
    label: '员工手机号',
    component: 'NInput'
  },
  {
    field: 'userName',
    label: '员工姓名',
    component: 'NInput'
  },
  {
    label: '创建时间',
    component: 'NDatePicker',
    field: 'createTime',
    componentProps: {
      type: 'datetimerange',
      defaultTime: ['00:00:00', '23:59:59']
    }
  }
];
const failColumns: NaiveUI.TableColumn<Api.government.PointsFailureRecordVO>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'name',
    title: '任务名称',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center',
    render(row) {
      return (
        <div>
          <div>创建时间：{row.createTime}</div>
          <div>完成时间：{row.createTime}</div>
        </div>
      );
    }
  },
  {
    key: 'totalUserCount',
    title: '操作人',
    align: 'center',
    render(row) {
      return (
        <div>
          <div>{row.createByRole}</div>
          <div>({row.createByName})</div>
        </div>
      );
    }
  },
  {
    key: 'successStatus',
    title: '状态',
    align: 'center',
    width: 240,
    render(row) {
      return (
        <div class={'flex items-center'}>
          共{Number(row.successStatus) + Number(row.failureStatus)}条，成功：{row.successStatus}，
          <span class={'flex items-center text-red-500'}>
            失败：
            {row.failureStatus}
            {row.failureStatus != 0 && (
              <div onClick={() => hanleExportFailure(row.code)}>
                <SVGIcon
                  icon={'tdesign:download'}
                  class={'ml-1 cursor-pointer text-20px'}
                  style={'color:var(--n-color)'}
                ></SVGIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];
const failData = ref<Api.government.PointsFailureRecordVO[]>([]);
const [registerTable, { refresh, setFieldsValue: setSearchValues }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'channelNoList',
        label: '所属企业',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetLoginUserList,
          labelFeild: 'channelName',
          valueFeild: 'channelNo',
          multiple: true,
          onUpdateValue: () => {
            nextTick(() => {
              listHandleSearch();
            });
          },
          getOptions: async (options: any) => {
            await setSearchValues({ channelNoList: [options[0].channelNo] });
            listHandleSearch();
          }
        }
      },
      {
        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: 'id',
    title: '充值积分',
    showAddButton: false,
    defaultParamsNotReset: 'channelIdList'
  }
});
const [registerModalTable, { refresh: refreshModal, setFieldsValue, getSeachForm, setTableLoading, getTableData }] =
  useTable({
    searchFormConfig: {
      schemas: searchSchemas,
      inline: false,
      size: 'small',
      labelPlacement: 'left',
      isFull: false
    },
    tableConfig: {
      keyField: 'id',
      title: '积分列表',
      showAddButton: false,
      minHeight: 400,
      defaultParamsNotReset: 'channelIdList',
      fieldMapToTime: [['createTime', ['createTimeStart', 'createTimeEnd']]]
    }
  });

const [registerModal, { openModal }] = useModal({
  title: '充值积分',
  height: 800,
  showFooter: false,
  width: 1200
});
const [registerModalFail, { openModal: openModalFail }] = useModal({
  title: '导入记录',
  height: 400,
  showFooter: false
});
async function handleSubmitImport(file: File) {
  const { error } = await fetchImportPoints(file);
  if (!error) {
    importTemplateRef.value?.closeModal();
    refreshModal();
  } else {
    importTemplateRef.value?.setSubLoading(false);
  }
}
function handleOpenPoints() {
  importTemplateRef.value?.openModal();
}
async function openImportModal() {
  openModalFail();
  const { data } = await fetchGetFailPointsList();
  failData.value = data as Api.government.PointsFailureRecordVO[];
}
async function hanleExportFailure(code: string) {
  if (loading.value) {
    window.$message?.error('正在导出，请勿重复点击');
    return;
  }
  loading.value = true;
  try {
    await commonExport('/smqjh-system/api/v1/pointsFailureRecord/export', { code }, '失败的记录.xlsx');
  } finally {
    loading.value = false;
  }
}

async function exportIntegral() {
  setTableLoading(true);
  try {
    await commonExport('/smqjh-system/api/v1/pointsRecharge/export', getSeachForm(), '积分列表.xlsx');
  } finally {
    setTableLoading(false);
  }
}

function handleSearch() {
  refreshModal();
}

function listHandleSearch() {
  refresh();
}

async function setSearchForm(value: Recordable) {
  await setFieldsValue(value);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="outColumns" :immediate="false" :api="fetchGetPointsOutList" @register="registerTable">
      <template #prefix>
        <NButton size="small" @click="openModal">充值积分</NButton>
      </template>
    </ZTable>
    <BasicModal @register="registerModal" @after-leave="refresh">
      <LayoutTable>
        <ZTable
          :immediate="false"
          :show-table-action="false"
          :columns="ModalColumns"
          :api="fetchGetPointsList"
          @register="registerModalTable"
        >
          <template #prefix="{ loading: tabloading }">
            <NButton
              v-if="useAuth().hasAuth('points:user:export')"
              size="small"
              :loading="tabloading"
              :disabled="getTableData().length == 0"
              @click="exportIntegral"
            >
              导出
            </NButton>
            <NButton v-if="useAuth().hasAuth('points:user:import')" size="small" @click="handleOpenPoints">
              导入积分
            </NButton>
            <NButton v-if="useAuth().hasAuth('points:user:import-record')" size="small" @click="openImportModal">
              导入记录
            </NButton>
          </template>
        </ZTable>
      </LayoutTable>
    </BasicModal>
    <BasicModal @register="registerModalFail">
      <NDataTable :columns="failColumns" :data="failData" size="small" remote class="sm:h-full" />
    </BasicModal>
    <ZImportTemplate
      ref="importTemplateRef"
      url="/smqjh-system/api/v1/pointsRecharge/exportTemplate"
      template-text="导入积分模版.xlsx"
      modal-text="导入积分"
      @submit="handleSubmitImport"
    ></ZImportTemplate>
  </LayoutTable>
</template>

<style scoped></style>
