<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import { useTable, BasicTable, TableAction } from '/@/components/Table';
  import { searchFormSchema, tableColumns } from './data.config';
  import { reactive, computed } from 'vue';
  import { Recordable } from 'vite-plugin-mock';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getStudentReportRecordPlanPage,
    postStudentReportRecordAllSign,
    postStudentReportRecordExportQuery,
    postStudentReportRecordUpdateStduyStatus,
    postStudentReportRecordSign,
  } from '/@/services/apis/StudentReportRecordController';
  import { downloadByData } from '/@/utils/file/download';
  import { formatToDate } from '/@/utils/dateUtil';
  import PlanTree from './planTree.vue';
  import { Switch } from 'ant-design-vue';
  import { useLoading } from '/@/components/Loading';
  import { usePermission } from '/@/hooks/web/usePermission';

  const searchInfo = reactive<Recordable>({});

  const { createConfirm, createMessage } = useMessage();
  const { hasPermission } = usePermission();

  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '处理中...',
  });

  const [registerTable, { reload, getSelectRowKeys, getForm, clearSelectedRowKeys }] = useTable({
    api: getStudentReportRecordPlanPage,
    title: '报到计划表',
    rowKey: 'id',
    columns: tableColumns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    immediate: false,
    canResize: true,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
    rowSelection: {
      type: 'checkbox',
      getCheckboxProps: (record: Recordable) => ({
        disabled: record.isReport === 1,
      }),
    },
  });

  const hasSelected = computed(() => getSelectRowKeys().length > 0);

  const handleChangeReport = async () => {
    try {
      openFullLoading();
      const keys: Recordable[] = [];
      getSelectRowKeys().forEach((item) => {
        keys.push({ id: item });
      });
      if (keys.length > 0) {
        await postStudentReportRecordAllSign(keys);
        clearSelectedRowKeys();
        await reload();
      }
    } finally {
      closeFullLoading();
    }
  };
  const handleChangeStduyStatus = (record: any) => {
    createConfirm({
      iconType: 'warning',
      title: '温馨提醒',
      content: '确认切换当前学生就读方式？',
      onOk: async () => {
        try {
          await postStudentReportRecordUpdateStduyStatus({ id: record.id });
          createMessage.success('切换成功');
          await reload();
        } catch (e) {
          createMessage.error('切换失败');
        }
      },
      okText: '确认',
      cancelText: '取消',
    });
  };

  const handleExport = async () => {
    if (!searchInfo.studentReportPlanId) {
      createMessage.warning('请先选择计划再导出');
      return;
    }
    const postData = getForm().getFieldsValue();
    downloadByData(
      (await postStudentReportRecordExportQuery({ ...postData, ...searchInfo })).data,
      `学生报到信息${formatToDate(new Date())}.xlsx`,
    );
  };

  function handleSelect(id) {
    searchInfo.studentReportPlanId = id;
    reload();
  }

  const handleReport = async (record) => {
    await postStudentReportRecordSign({ id: record.id });
    createMessage.success('已成功修改状态');
    clearSelectedRowKeys();
    reload();
  };
</script>

<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <PlanTree class="w-1/3 xl:w-1/4" @select="handleSelect" />
    <BasicTable @register="registerTable" class="w-2/3 xl:w-3/4" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button
          type="primary"
          @click="handleChangeReport"
          :disabled="!hasSelected"
          v-auth="'schoolOpens:report'"
        >
          变更为已报到
        </a-button>
        <a-button type="primary" @click="handleExport">导出</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '切换就读方式',
              onClick: handleChangeStduyStatus.bind(null, record),
            },
          ]"
        />
      </template>
      <template #isReport="{ record }">
        <Switch :checked="record.isReport === 1" @change="handleReport(record)" />
      </template>
    </BasicTable>
  </PageWrapper>
</template>

<style scoped lang="less"></style>
