<script setup lang="tsx">
import { nextTick, onMounted, ref, useTemplateRef } from 'vue';
import { useRoute } from 'vue-router';
import { NButton } from 'naive-ui';
import { delCoupon, fetchFailList, fetchImport, fetchList } from '@/service/api/operation/coupon-manage';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
const route = useRoute();
const importTemplateRef = useTemplateRef('importTemplateRef');
const [registerModalTable, { refresh, setFieldsValue }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'activityId',
        component: 'NInput',
        label: '券ID'
      },
      {
        field: 'activityName',
        component: 'NInput',
        label: '名称'
      },
      {
        field: 'promotionType',
        component: 'NSelect',
        componentProps: {
          options: [
            { label: '满减券', value: 1 },
            { label: '立减券', value: 2 }
          ]
        },
        label: '类型'
      },
      {
        // 优惠券状态 1-已使用 2-可使用 5-已过期 7-未生效
        field: 'useStatus',
        component: 'NSelect',
        componentProps: {
          options: [
            { label: '已使用', value: 1 },
            { label: '可使用', value: 2 },
            { label: '冻结', value: 3 },
            { label: '已过期', value: 5 },
            { label: '未生效', value: 7 }
          ]
        },
        label: '状态'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '优惠券列表',
    minHeight: 400,
    showAddButton: false
  }
});
const loading = ref(false);
const tableColumns: NaiveUI.TableColumn<Api.goods.ShopCategory>[] = [
  {
    title: '所属企业',
    align: 'center',
    key: 'channelName'
  },
  {
    title: '用户手机号',
    align: 'center',
    key: 'memberMobile'
  },
  {
    title: '券ID',
    align: 'center',
    key: 'couponId'
  },

  {
    title: '券名称',
    align: 'center',
    key: 'couponName'
  },
  {
    title: '券信息',
    align: 'center',
    key: 'couponInfo'
    // render: row => {
    //   let content = '';
    //   if (row.promotionType === 1) {
    //     content = `满${row.amountMoney}元减${row.discountMoney}元`;
    //   } else {
    //     content = `立减${row.discountMoney}元`;
    //   }
    //   return <div>{content}</div>;
    // }
  },
  {
    title: '状态',
    align: 'center',
    key: 'useStatus',
    render: row => {
      let status = '';
      switch (row.useStatus) {
        case 1:
          status = '已使用';
          break;
        case 2:
          status = '可使用';
          break;
        case 3:
          status = '冻结';
          break;
        case 5:
          status = '已过期';
          break;
        case 7:
          status = '未生效';
          break;
        default:
          status = '未知状态';
          break;
      }
      return <div>{status}</div>;
    }
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime'
  },
  {
    title: '券使用有效期',
    align: 'center',
    key: 'expirationTime'
  },
  {
    title: '订单编号',
    align: 'center',
    key: 'lockOrderId'
  },
  {
    title: '操作',
    key: 'op',
    fixed: 'right',
    align: 'center',
    width: 230,
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" size="small" ghost onClick={() => del(row)}>
          删除
        </NButton>
      </div>
    )
  }
];

const [registerModalFail, { openModal: openModalFail }] = useModal({
  title: '导入记录',
  height: 650,
  width: 1200,
  showFooter: false
});

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

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.createTime}</div>
        </div>
      );
    }
  },
  {
    key: 'operator',
    title: '操作人',
    align: 'center',
    width: 120
    // 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.failNum) + Number(row.successNum)}条，成功：{row.successNum}，
          <span class={'flex items-center text-red-500'}>
            失败：
            {row.failNum}
            {row.failNum != 0 && (
              <div onClick={() => hanleExportFailure(row.batchNo)}>
                <SvgIcon
                  icon={'tdesign:download'}
                  class={'ml-1 cursor-pointer text-20px'}
                  style={'color:red'}
                ></SvgIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];

function del(row: Api.goods.ShopCategory) {
  window.$dialog?.info({
    title: '删除活动',
    content: '你确定要删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await delCoupon(row.id);
      if (!error) {
        refresh();
      }
    }
  });
}

// async function handleSubmitImport(file: File) {
//   const res = await fetchImportGoods({ file });
//   console.log(res);

//   if (!res.error) {
//     importTemplateRef.value?.closeModal();
//   }
//   window.$message?.success(res.data);
//   importTemplateRef.value?.setSubLoading(false);
// }
function openImportModal() {
  importTemplateRef.value?.openModal();
}
async function openImportLogModal() {
  openModalFail();
  await nextTick();
  refreshLog();
}
async function handleSubmitImport(file: File) {
  console.log(file);

  // setTableLoading(true);
  try {
    const res = await fetchImport({ file });
    console.log(res);

    // if (!res.error) {
    //   importTemplateRef.value?.closeModal();
    // }
    window.$message?.success(res.data);
    importTemplateRef.value?.setSubLoading(false);
    window.$dialog?.success({
      title: '提示',
      content: () => {
        return (
          <div>
            <p>导入操作进行中......</p>
            <p>是否进入导入记录</p>
          </div>
        );
      },
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        importTemplateRef.value?.closeModal();
        openImportLogModal();
      },
      onNegativeClick: () => {}
    });
  } finally {
    importTemplateRef.value?.setSubLoading(false);
  }
}
async function hanleExportFailure(batchNo: string) {
  if (loading.value) {
    window.$message?.error('正在导出，请勿重复点击');
    return;
  }
  loading.value = true;
  setLogTableLoading(true);
  try {
    await commonExport('/smqjh-system/sys-api/memberCoupon/downloadErrorExcel', { batchNo }, '失败的记录.xlsx');
  } finally {
    loading.value = false;
    setLogTableLoading(false);
  }
}

onMounted(() => {
  setTimeout(async () => {
    await setFieldsValue({ activityId: route.query.activityId });
    refresh();
  }, 1000);
});
</script>

<template>
  <LayoutTable>
    <ZTable :show-table-action="false" :columns="tableColumns" :api="fetchList" @register="registerModalTable">
      <template #prefix>
        <NSpace>
          <NButton size="small" @click="openImportModal">批量发放</NButton>
          <NButton size="small" @click="openImportLogModal">导入记录</NButton>
        </NSpace>
      </template>
    </ZTable>

    <ZImportTemplate
      ref="importTemplateRef"
      url="/smqjh-system/sys-api/memberCoupon/downloadXlsx"
      template-text="批量发放导入模版.xlsx"
      modal-text="批量发放"
      @submit="handleSubmitImport"
    ></ZImportTemplate>

    <BasicModal @register="registerModalFail">
      <ZTable
        :immediate="false"
        :columns="failColumns"
        :show-table-action="false"
        :api="fetchFailList"
        @register="registerLogTable"
      ></ZTable>
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
