<script setup lang="tsx">
import { computed, nextTick, ref } from 'vue';
import { NButton, NTag } from 'naive-ui';
import {
  fetchExport,
  fetchExportRecord,
  fetchMemberList,
  fetchOpenRecord
} from '@/service/api/member-center/member-list';
import { commonExport } from '@/utils/common';
import SvgIcon from '@/components/custom/svg-icon.vue';
// import dayjs from 'dayjs';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
const mobile = ref('');
const columns: NaiveUI.TableColumn<Api.goods.ShopSku>[] = [
  {
    key: 'mobile',
    title: '手机号',
    align: 'center',
    width: 100
  },
  {
    key: 'status',
    title: '当前状态',
    align: 'center',
    width: 100,
    render: row => {
      return <NTag class={'mt7'}>{row.status == 1 ? '生效中' : '已失效'}</NTag>;
    }
  },
  {
    key: 'expireTime',
    title: '有效期至',
    align: 'center',
    width: 100
  },
  {
    key: 'openTimes',
    title: '开通次数',
    align: 'center',
    width: 100
  },
  {
    key: 'effectiveTime',
    title: '最近开通时间',
    align: 'center',
    width: 100
  },
  {
    key: 'openSource',
    title: '来源',
    align: 'center',
    width: 100,
    render: row => {
      return <dictTag value={row.openSource} dictCode="open_channel" immediate={true}></dictTag>;
    }
  }
];

const [registerTable, { getTableData }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '手机号',
        component: 'NInput',
        field: 'mobile'
      },
      {
        label: '会员状态',
        field: 'status',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '生效中',
              value: 1
            },
            {
              label: '已失效',
              value: 2
            }
          ]
        }
      },
      {
        label: '开放渠道',
        component: 'dictSelect',
        field: 'openSource',
        componentProps: {
          dictCode: 'open_channel',
          immediate: true
        }
      },
      {
        label: '最近开通时间',
        component: 'NDatePicker',
        field: 'createTime',
        componentProps: {
          type: 'datetimerange',
          defaultTime: ['00:00:00', '23:59:59']
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    opWdith: 160,
    keyField: 'skuId',
    title: '用户列表',
    showAddButton: false,
    scrollX: 1800,
    fieldMapToTime: [['createTime', ['effectiveTimeStart', 'effectiveTimeEnd']]]
  }
});

const failColumns: NaiveUI.TableColumn<Api.government.PointsFailureRecordVO>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    width: 80,
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'taskName',
    title: '任务名称',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center',
    width: 300,
    render(row) {
      return (
        <div>
          <div>创建时间：{row.createTime}</div>
          <div>完成时间：{row.updateTime}</div>
        </div>
      );
    }
  },
  {
    key: 'operatorName',
    title: '操作人',
    align: 'center',
    width: 120
  },
  {
    key: 'successStatus',
    title: '状态',
    align: 'center',
    width: 240,
    render(row) {
      const statusList = ['已创建', '进行中', '导出完成', '导出失败'];
      return (
        <div class={'flex items-center'}>
          <span class={'mr-2'}>{statusList[row.status]}</span>共{Number(row.totalCount)}条，
          <span class={'flex items-center'}>
            {row.status == 2 && (
              <div onClick={() => hanleExport(row.id)}>
                <SvgIcon icon={'tdesign:download'} class={'ml-1 cursor-pointer text-20px'}></SvgIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];
const openColumns: NaiveUI.TableColumn<Api.government.PointsFailureRecordVO>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    width: 80,
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'effectiveTime',
    title: '激活时间',
    align: 'center'
  },
  {
    key: 'expireTime',
    title: '到期时间',
    align: 'center'
  },
  {
    key: 'statusAfterAction',
    title: '状态',
    align: 'center',
    render: row => {
      // 操作后状态：1 生效中，2 已取消/已失效。
      return row.statusAfterAction === 1 ? '生效中' : '已取消/已失效';
    }
  },
  {
    key: 'source',
    title: '来源',
    align: 'center',
    render: row => {
      return <dictTag value={row.source} dictCode="open_channel" immediate={true}></dictTag>;
    }
  }
];

const [registerLogTable, { refresh: refreshLog, setTableLoading: setLogTableLoading }] = useTable({
  tableConfig: {
    keyField: 'skuId',
    title: '',
    minHeight: 200,
    showAddButton: false,
    showSearch: false
  }
});

const [registerOpenTable, { refresh: refreshOpen }] = useTable({
  tableConfig: {
    keyField: 'skuId',
    title: '',
    minHeight: 200,
    showAddButton: false,
    showSearch: false
  }
});

const [registerModalFail, { openModal: openModalFail }] = useModal({
  title: '导出记录',
  height: 400,
  width: 1200,
  showFooter: false
});
const [registerOpenModal, { openModal }] = useModal({
  title: `用户开通记录`,
  height: 400,
  width: 1200,
  showFooter: false
});

const loading = ref(false);

const tableData = computed(() => {
  return getTableData();
});

async function handleExport() {
  try {
    const res = await fetchExport({});
    console.log(res);

    // if (!res.error) {
    //   importTemplateRef.value?.closeModal();
    // }
    // window.$message?.success(res.data);
    window.$dialog?.success({
      title: '提示',
      content: () => {
        return (
          <div>
            <p>导入操作进行中......</p>
            <p>是否进入导入记录</p>
          </div>
        );
      },
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        openExportLogModal();
      },
      onNegativeClick: () => {}
    });
  } finally {
    console.log('导出失败');
  }
}

async function hanleExport(code: string) {
  if (loading.value) {
    window.$message?.error('正在导出，请勿重复点击');
    return;
  }
  loading.value = true;
  setLogTableLoading(true);
  try {
    await commonExport(`/smqjh-system/api/v1/member/export/task/download/${code}`, {}, '导出记录.xlsx');
  } finally {
    loading.value = false;
    setLogTableLoading(false);
  }
}

async function openExportLogModal() {
  openModalFail();
  await nextTick();

  refreshLog();
}

async function openRecordModal(id: string) {
  openModal();
  mobile.value = id;
  await nextTick();
  refreshOpen();
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchMemberList" @register="registerTable">
      <template #prefix="{ loading }">
        <NSpace>
          <NButton size="small" :disabled="tableData.length == 0" :loading="loading" @click="handleExport">
            导出
          </NButton>
          <NButton size="small" @click="openExportLogModal">导出记录</NButton>
        </NSpace>
      </template>
      <template #op="{ row }">
        <NButton size="small" @click="openRecordModal(row.mobile)">开通记录</NButton>
      </template>
    </ZTable>

    <!-- 导出记录 -->
    <BasicModal @register="registerModalFail">
      <ZTable
        :columns="failColumns"
        :immediate="false"
        :show-table-action="false"
        :api="fetchExportRecord"
        @register="registerLogTable"
      ></ZTable>
    </BasicModal>

    <!-- 记录 -->
    <BasicModal @register="registerOpenModal">
      <ZTable
        :columns="openColumns"
        :immediate="false"
        :show-table-action="false"
        :api="fetchOpenRecord"
        :default-params="{ mobile }"
        @register="registerOpenTable"
      ></ZTable>
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
