<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
      />
      <SelectAgent
        v-model="searchModel.agentId"
        placeholder="请选择"
        allow-clear
        prefix
        :teaching-id="searchModel.teachingId"
      />
      <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-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 type="text" :loading="assginLoading" @click="toAssgin">
        <template #icon><icon-translate /></template>
        一键自动分配
      </a-button>
      <a-button type="text" :loading="printLoading" @click="toPrint">
        <template #icon><icon-file /></template>
        打印签到表
      </a-button>
    </a-space>
    <a-table
      class="page-table"
      :columns="columns"
      :data="dataList"
      :pagination="pagination"
      :scroll="{ x: 1200 }"
      :bordered="false"
    >
      <template #status="{ record }">
        {{ 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/apply/import"
      :upload-data="uploadData"
      :format="['xls', 'xlsx']"
      :download-handle="downloadTemplate"
      download-filename="预考导入模板.xlsx"
      :auto-upload="false"
      @upload-success="getList"
    />
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    orderRecordCancel,
    orderRecordAutoAssign,
    orderRecordListPage,
    orderRecordPrint,
    orderRecordTemplate,
  } 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 { downloadByApi } from '@/utils/download';
  import { parseTimeRangeDateAndTimeContent } from '@/utils/utils';

  import ImportDialog from '@/components/import-dialog/index.vue';
  import { useAppStore } from '@/store';

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

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

  // const { getLabel: getAbleLabel } = useDictOption('ABLE_TYPE');

  const searchModel = reactive<OrderRecordListFilter>({
    taskId: null,
    teachingId: null,
    agentId: null,
    name: '',
    identityNumber: '',
    studentCode: '',
  });

  const columns: TableColumnData[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '证件号',
      dataIndex: 'identityNumber',
      width: 200,
    },
    {
      title: '学号',
      dataIndex: 'studentCode',
      width: 160,
    },
    {
      title: '教学点',
      dataIndex: 'teachingName',
      width: 160,
    },
    {
      title: '考点',
      dataIndex: 'agentName',
      width: 160,
    },
    {
      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 uploadData = computed(() => {
    return searchModel.teachingId ? { teachingId: searchModel.teachingId } : {};
  });
  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();
  }

  // 一键分配
  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 { loading: printLoading, setLoading: setPrintLoading } = useLoading();
  async function toPrint() {
    if (printLoading.value) return;
    setPrintLoading(true);

    const res = await downloadByApi(() =>
      orderRecordPrint({
        teachingId: searchModel.teachingId || undefined,
      })
    ).catch((e) => {
      Message.error(e || '下载失败，请重新尝试！');
    });
    setPrintLoading(false);
    if (!res) return;
    Message.success('下载成功！');
  }

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

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