<script setup lang="tsx">
import { ref, useTemplateRef } from 'vue';
import {
  fetchGetFailPointsList,
  fetchGetPointsList,
  fetchGetPointsOutList,
  fetchImportPoints
} from '@/service/api/government/points';
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 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: 'channelName',
    label: '企业名称',
    component: 'NInput'
  },
  {
    field: 'userPhone',
    label: '员工手机号',
    component: 'NInput'
  }
];
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 }] = useTable({
  searchFormConfig: {
    schemas: searchSchemas.slice(0, 1),
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '充值积分',
    showAddButton: false
  }
});
const [registerModalTable, { refresh: refreshModal }] = useTable({
  searchFormConfig: {
    schemas: searchSchemas,
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '积分列表',
    showAddButton: false,
    minHeight: 400
  }
});

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[];
}
function hanleExportFailure(code: string) {
  window.open(`${import.meta.env.VITE_SERVICE_BASE_URL}/platform/pointsFailureRecord/export?code=${code}`, '_blank');
}
</script>

<template>
  <LayoutTable>
    <ZTable :show-table-action="false" :columns="outColumns" :api="fetchGetPointsOutList" @register="registerTable">
      <template #prefix>
        <NButton size="small" @click="openModal">充值积分</NButton>
      </template>
    </ZTable>
    <BasicModal @register="registerModal" @after-leave="refresh">
      <LayoutTable>
        <ZTable
          :show-table-action="false"
          :columns="ModalColumns"
          :api="fetchGetPointsList"
          @register="registerModalTable"
        >
          <template #prefix>
            <NButton size="small" @click="handleOpenPoints">导入积分</NButton>
            <NButton 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="/platform/pointsRecharge/exportTemplate"
      template-text="导入积分模版.xlsx"
      modal-text="导入积分"
      @submit="handleSubmitImport"
    ></ZImportTemplate>
  </LayoutTable>
</template>

<style scoped></style>
