<template>
  <div class="part-box is-filter">
    <a-space class="filter-line" :size="12" wrap>
      <SelectTask
        v-model="searchModel.taskId"
        placeholder="请选择"
        allow-clear
        prefix
      />
      <SelectTeaching
        v-model="searchModel.teachingId"
        placeholder="请选择"
        allow-clear
        prefix-str="所约教学点"
      />
      <SelectAgent
        v-model="searchModel.agentId"
        placeholder="请选择"
        allow-clear
        prefix
        cascade
        :teaching-id="searchModel.teachingId"
      />
      <select-range-datetime
        v-model:startTime="searchModel.startDate"
        v-model:endTime="searchModel.endDate"
      >
      </select-range-datetime>
      <a-input v-model.trim="searchModel.name" placeholder="请输入" allow-clear>
        <template #prefix>姓名</template>
      </a-input>
      <a-input
        v-model.trim="searchModel.identityNumber"
        placeholder="请输入"
        allow-clear
      >
        <template #prefix>证件号</template>
      </a-input>
      <a-input
        v-model.trim="searchModel.studentCode"
        placeholder="请输入"
        allow-clear
      >
        <template #prefix>学号</template>
      </a-input>

      <a-button type="primary" @click="toPage(1)">查询</a-button>
      <a-button type="primary" status="success" @click="exportTable"
        >导出</a-button
      >
    </a-space>
  </div>
  <div class="part-box">
    <a-space class="part-action" :size="6">
      <a-button type="text" @click="toImport">
        <template #icon>
          <svg-icon name="icon-import" />
        </template>
        导入预考
      </a-button>
      <a-button
        v-if="userStore.isAdmin"
        type="text"
        :loading="assginLoading"
        @click="toAssgin"
      >
        <template #icon> <svg-icon name="icon-assign" /> </template>
        一键自动分配
      </a-button>
      <a-button type="text" @click="toPrint">
        <template #icon> <svg-icon name="icon-print" /> </template>
        导出签到表
      </a-button>
      <a-button type="text" @click="toExportOrderDetail">
        <template #icon> <svg-icon name="icon-print" /> </template>
        导出预约情况表
      </a-button>
    </a-space>
    <a-table
      class="page-table"
      :columns="columns"
      :data="dataList"
      :pagination="pagination"
      :scroll="{ x: 1200 }"
      :bordered="false"
    >
      <template #status="{ record }">
        <status-tag type="recordCancel" :value="record.cancel" />
      </template>
      <template #period="{ record }">
        {{ parseTimeRangeDateAndTimeContent(record.startTime, record.endTime) }}
      </template>
      <template #updateTime="{ record }">
        {{ timestampFilter(record.updateTime) }}
      </template>
      <template #action="{ record }">
        <a-button
          v-if="!record.cancel"
          type="text"
          class="btn-danger"
          @click="toCancel(record)"
          >取消</a-button
        >
      </template>
    </a-table>

    <!-- ImportDialog -->
    <ImportDialog
      ref="importStudentDialogRef"
      title="导入预考"
      upload-url="/api/admin/apply/import"
      :format="['xls', 'xlsx']"
      :download-handle="downloadTemplate"
      download-filename="预考导入模板.xlsx"
      :auto-upload="false"
      @upload-success="importSuccess"
    />
    <!-- PrintDialog -->
    <PrintDialog ref="printDialogRef" />
    <!-- orderDetailDialog -->
    <OrderDetailDialog ref="orderDetailDialogRef" />
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    orderRecordCancel,
    orderRecordAutoAssign,
    orderRecordListPage,
    orderRecordTemplate,
    orderDetailExport,
  } from '@/api/order';
  import { OrderRecordItem, OrderRecordListFilter } from '@/api/types/order';
  import useTable from '@/hooks/table';
  // import useDictOption from '@/hooks/dict-option';
  import useLoading from '@/hooks/loading';
  import { timestampFilter } from '@/utils/filter';
  import { modalConfirm } from '@/utils/arco';
  import { parseTimeRangeDateAndTimeContent } from '@/utils/utils';
  import { useAppStore, useUserStore } from '@/store';
  import { downloadByApi } from '@/utils/download';
  // import { getBeforeWeek } from '@/utils/day';

  import ImportDialog from '@/components/import-dialog/index.vue';
  import PrintDialog from './printDialog.vue';
  import OrderDetailDialog from './orderDetailDialog.vue';

  defineOptions({
    name: 'OrderRecordManage',
  });

  const appStore = useAppStore();
  appStore.setInfo({ breadcrumbs: ['考试预约管理', '预约明细'] });
  const userStore = useUserStore();

  // const preDate = getBeforeWeek();
  const searchModel = reactive<OrderRecordListFilter>({
    taskId: null,
    teachingId: null,
    agentId: null,
    name: '',
    identityNumber: '',
    studentCode: '',
    startDate: undefined,
    endDate: undefined,
  });

  const columns: TableColumnData[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '证件号',
      dataIndex: 'identityNumber',
      width: 200,
    },
    {
      title: '学号',
      dataIndex: 'studentCode',
      width: 160,
    },
    {
      title: '所属教学点',
      dataIndex: 'teachingName',
      width: 200,
    },
    {
      title: '所约教学点',
      dataIndex: 'applyTeachingName',
      width: 200,
    },
    {
      title: '考点',
      dataIndex: 'agentName',
      width: 200,
    },
    {
      title: '预约时段',
      dataIndex: 'startTime',
      slotName: 'period',
      width: 200,
    },
    {
      title: '考场',
      dataIndex: 'roomName',
      width: 120,
    },
    {
      title: '座位号',
      dataIndex: 'seatNumber',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'cancel',
      slotName: 'status',
      width: 100,
    },
    {
      title: '操作时间',
      dataIndex: 'updateTime',
      slotName: 'updateTime',
      width: 170,
    },
    {
      title: '操作人',
      dataIndex: 'userName',
      width: 120,
    },
    {
      title: '操作',
      slotName: 'action',
      width: 80,
      fixed: 'right',
      cellClass: 'action-column',
    },
  ];
  const { dataList, pagination, toPage, getList } = useTable<OrderRecordItem>(
    orderRecordListPage,
    searchModel,
    true
  );

  async function downloadTemplate() {
    const res = await downloadByApi(() => orderRecordTemplate()).catch((e) => {
      Message.error(e || '下载失败，请重新尝试！');
    });
    if (!res) return;
    Message.success('下载成功！');
  }

  // table action
  // 导入
  const importStudentDialogRef = ref();
  function toImport() {
    importStudentDialogRef.value?.open();
  }
  function importSuccess() {
    importStudentDialogRef.value?.close();
    toPage(1);
  }

  // 一键分配
  const { loading: assginLoading, setLoading: setAssignLoading } = useLoading();
  async function toAssgin() {
    if (!searchModel.taskId) {
      Message.error('请先选择任务！');
      return;
    }

    if (assginLoading.value) return;
    setAssignLoading(true);

    const res = await orderRecordAutoAssign({
      taskId: searchModel.taskId,
    }).catch(() => false);
    setAssignLoading(false);
    if (!res) return;
    Message.success('操作成功！');
    getList();
  }

  // 打印签到表
  const printDialogRef = ref();
  function toPrint() {
    printDialogRef.value?.open();
  }

  // 导出考场预约情况表
  const orderDetailDialogRef = ref();
  function toExportOrderDetail() {
    orderDetailDialogRef.value?.open();
  }

  // 取消
  async function toCancel(row: OrderRecordItem) {
    const confirmRes = await modalConfirm(
      '提示',
      `确定要取消【${row.name}】的预约吗?`
    ).catch(() => false);
    if (confirmRes !== 'confirm') return;

    await orderRecordCancel(row.id);
    Message.success('操作成功！');
    getList();
  }

  const exportTable = async () => {
    const res = await downloadByApi(() =>
      orderDetailExport({ teachingId: searchModel.teachingId })
    ).catch((e) => {
      Message.error(e || '导出失败，请重新尝试！');
    });
    if (!res) return;
    Message.success('导出成功！');
  };
</script>
