<template>
  <BasicTable @register="registerTable">
    <!--插槽:table标题-->
    <template #tableTitle>
      <div class="flex items-center p3">
        <a-button type="primary" @click="handleExport">导出赛事报名表</a-button>
      </div>
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
    </template>
    <template #goods="{ record }">
      <div class="flex items-center h-20px text-16px">
        <div class="font-semibold">订单编号：{{ record.orderCode }}</div>
        <div class="ml3">下单时间：{{ record.createTime }}</div>
        <div class="ml3 truncate w300px"
          >店铺名称：

          <a-tooltip>
            <template #title>{{ record.orderType == 3 || record.orderType == 4 ? record.departName : record.siteName }} </template>
            {{ record.orderType == 3 || record.orderType == 4 ? record.departName : record.siteName }}
          </a-tooltip>
        </div>
      </div>
      <div class="mt3 flex items-center border-b border-solid pb-3 h-90px" v-for="item in record.orderProInfoList" :key="item.id">
        <Image :width="80" :height="80" class="rounded-16px" :src="item.productImage.split(',')[0]" v-if="item.productImage" />
        <div class="ml3">{{ item.productName }}</div>
      </div>
    </template>
    <template #price="{ record }">
      <div class="h-20px"></div>
      <div class="mt3 h-90px flex flex-col justify-center border-b border-solid" v-for="item in record.orderProInfoList" :key="item.id">
        <div class="flex items-center" v-if="item.price>0">
          <div>￥{{ item.price || 0 }}</div>
          <div class="line-through ml-3 text-gray">￥{{ item.originalPrice || 0 }}</div>
        </div>
        <div class="flex items-center" v-else>
          <div>￥{{ item.originalPrice || 0 }}</div>
<!--          <div class="line-through ml-3 text-gray">￥{{ item.originalPrice || 0 }}</div>-->
        </div>
        <div class="text-gray">x{{ item.quantity }}</div>
      </div>
    </template>
    <template #user="{ record }">
      <div class="h-20px"></div>
      <div class="mt3 h-90px flex flex-col justify-center border-b border-solid" v-for="item in record.orderProInfoList" :key="item.id">
        <div>{{ item.userName || item.ticketNo || '无' }}</div>
        <div class="text-gray">{{ item.userPhone }}</div>
      </div>
    </template>
    <template #status="{ record }">
      <div class="h-20px"></div>
      <div class="mt3 h-90px flex flex-col justify-center border-b border-solid" v-for="item in record.orderProInfoList" :key="item.id">
        <div v-if="item.type != 6">{{ orderStatus[item.orderStatus] }}</div>
        <div v-else>无</div>
      </div>
    </template>
    <template #After="{ record }">
      <div class="h-20px"></div>
      <div class="mt3 h-90px flex flex-col justify-center border-b border-solid" v-for="item in record.orderProInfoList" :key="item.id">
        <div v-if="item.type != 6">{{ afterSaleStatus[item.afterSaleStatus] }}</div>
        <div v-else>无</div>
      </div>
    </template>
  </BasicTable>
  <orderModelView @register="registerModal"></orderModelView>
  <a-modal v-model:open="openExportData" title="导出赛事名单" @ok="handleExportData" :confirmLoading="exportLoading">
    <BasicForm :showActionButtonGroup="false" @register="registerForm" style="margin: 50px 50px 0 50px" />
  </a-modal>
</template>

<script setup lang="ts">
  import orderModelView from './components/orderModelView.vue';
  import { Image, message, Modal, QRCode } from 'ant-design-vue';
  import { ref, reactive, computed, unref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, searchFormSchema, afterSaleStatus, orderStatus } from './order.data';
  import { list, exportData, queryEvents, queryProject } from './order.api';
  import { useUserStore } from '/@/store/modules/user';

  const queryParam = reactive<any>({});
  const userStore = useUserStore();
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext } = useListPage({
    tableProps: {
      api: list,
      columns,
      formConfig: {
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [['time', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']],
      },
      inset: true,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, { ...queryParam, orgCode: userStore.userInfo?.orgCode });
      },
    },
  });

  const [registerTable, { reload }, { selectedRowKeys }] = tableContext;
  //自定义表单字段
  const formSchemas: FormSchema[] = [
    {
      label: '赛事名称',
      field: 'name',
      component: 'ApiSelect',
      required: true,
      labelWidth: 100,
      componentProps: {
        api: queryEvents,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        onChange: (value) => {
          exportQueryParam.gameId = value;
        },
      },
    },
    {
      label: '比赛项目',
      field: 'project',
      component: 'ApiSelect',
      required: true,
      labelWidth: 100,
      componentProps: {
        api: queryProject,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        params: computed(() => {
          return exportQueryParam.gameId ? { gameId: exportQueryParam.gameId } : {};
        }),
        onChange: (value) => {
          exportQueryParam.projectId = value;
        },
      },
    },
    {
      label: '报名结束时间',
      field: 'entryTime',
      component: 'RangePicker',
      labelWidth: 100,
      required: true,
      componentProps: {
        onChange: (value) => {
          exportQueryParam.startTime = value[0];
          exportQueryParam.endTime = value[1];
          console.log(value);
        },
      },
    },
  ];

  /**
   * BasicForm绑定注册;
   */
  const [registerForm] = useForm({
    //注册表单列
    schemas: formSchemas,
    showResetButton: false,
    submitButtonOptions: { text: '提交', preIcon: '' },
    actionColOptions: { span: 17 },
  });

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
    });
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '查看',
        onClick: handleEdit.bind(null, record),
        // auth: 'feedback:nm_feedback:edit',
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [];
  }

  const openExportData = ref(false);

  function handleExport() {
    openExportData.value = true;
    // message.error('记得提醒搞导出，现在暂时没有这个功能！');
  }

  // 提交导出
  const exportQueryParam = reactive<any>({
    gameId: null,
    projectId: null,
    startTime: null,
    endTime: null,
  });
  const exportLoading = ref(false);
  const handleExportData = async () => {
    exportLoading.value = true;
    try {
      const response = await exportData(exportQueryParam);
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = '赛事名单.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
      message.success('导出成功！');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请稍后重试');
    } finally {
      exportLoading.value = false;
      openExportData.value = false;
    }
  };
</script>

<style scoped></style>
