<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="所约教学点"
        :task-id="searchModel.taskId"
        @get-options="getTeachOptions"
      />
      <SelectAgent
        v-model="searchModel.examSiteId"
        placeholder="请选择"
        allow-clear
        prefix
        cascade
        :teaching-id="searchModel.teachingId"
      />
      <a-button type="primary" @click="search">查询</a-button>
    </a-space>
  </div>
  <div class="part-box">
    <a-space
      v-if="searchModel.examSiteId && searchModel.taskId && tableData.length"
      class="part-action"
      :size="12"
    >
      <a-button type="primary" @click="save">保存</a-button>
      <span style="color: #ff9a2e">时段关联最小单位是考点</span>
    </a-space>
    <div
      v-if="searchModel.examSiteId && searchModel.taskId && !userStore.isAdmin"
      class="part-action"
      :size="12"
      style="display: flex; align-items: center"
    >
      <span>开放考生自主预约：</span>
      <a-radio-group v-model="selfYYDefaultValue" @change="selfYY">
        <a-radio :value="true">是</a-radio>
        <a-radio :value="false">否</a-radio>
      </a-radio-group>

      <span style="color: #ff9a2e"
        >说明：选择否，则考生在手机端无法自主预约</span
      >
    </div>
    <a-table
      :key="tableKey"
      class="page-table"
      :columns="columns"
      :data="tableData"
      :pagination="false"
      :scroll="{ x: 1200 }"
      :bordered="false"
      :loading="saveLoading || tableLoading"
    >
      <template #dateStr="{ record }"> {{ record.dateStr }} </template>
      <template #batch="{ record, rowIndex }">
        <a-switch
          :default-checked="record.batchStatus"
          @change="(bool:string | number | boolean)=>{
            switchBatchChange(rowIndex,bool as boolean)
          }"
        >
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch></template
      >
      <template
        v-for="head in sliceTimeArr"
        #[head]="{ record, rowIndex }"
        :key="head"
      >
        <a-switch
          v-if="
            record.timePeriodList?.find((item:any) => item.timePeriodStr == head)
          "
          :default-checked="record.timePeriodList?.find((item:any) => item.timePeriodStr == head).enable"
          @change="(bool:string | number | boolean)=>{
            switchChange(rowIndex,head,bool as boolean)
          }"
        >
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch></template
      >
    </a-table>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, onMounted, watch } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    ableTask,
    taskListPage,
    getTimeSliceList,
    getDateAndTimeList,
    saveReservation,
    toggleSelfYYStatus,
  } from '@/api/order';
  import { TaskItem } from '@/api/types/order';
  import useTable from '@/hooks/table';
  import { timestampFilter } from '@/utils/filter';
  import { modalConfirm } from '@/utils/arco';
  import { useAppStore, useUserStore } from '@/store';

  defineOptions({
    name: 'ReservationSet',
  });
  const userStore = useUserStore();
  const tableLoading = ref(false);

  const tableKey = ref(`${Date.now()}`);
  const appStore = useAppStore();
  appStore.setInfo({ breadcrumbs: ['考试预约管理', '考点预约设置'] });

  const searchModel = reactive({
    taskId: '',
    examSiteId: '',
    teachingId: '',
  });
  const sliceTimeArr = ref([]);

  const columns = computed(() => {
    return [
      // {
      //   title: '任务ID',
      //   dataIndex: 'id',
      //   width: 80,
      // },
      {
        title: '日期/时段',
        dateIndex: 'dateStr',
        slotName: 'dateStr',
      },
      {
        title: '批量操作',
        slotName: 'batch',
        minWidth: 100,
      },
      ...sliceTimeArr.value.map((head: string) => {
        return {
          title: head,
          minWidth: 100,
          slotName: head,
          // render: (record: any, column: any, rowIndex: any) => {
          //   return <span>2</span>;
          // },
        };
      }),
    ];
  });

  const tableData = ref<any>([]);
  const getTimeSilce = () => {
    getTimeSliceList({ taskId: searchModel.taskId }).then((res: any) => {
      console.log('times', res);
      sliceTimeArr.value = res || [];
    });
  };
  onMounted(() => {});
  const search = () => {
    if (
      !searchModel.taskId ||
      !searchModel.teachingId ||
      !searchModel.examSiteId
    ) {
      Message.error(
        `请选择${
          !searchModel.taskId
            ? '任务'
            : !searchModel.teachingId
            ? '教学点'
            : '考点'
        }`
      );
      tableData.value = [];
      tableKey.value = `${Date.now()}`;
      return;
    }
    getTimeSilce();
    tableLoading.value = true;
    getDateAndTimeList({ examSiteId: searchModel.examSiteId || null })
      .then((res: any) => {
        tableData.value = (res || []).map((item: any) => {
          item.batchStatus = false;
          return item;
        });
        tableKey.value = `${Date.now()}`;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  };
  // watch(
  //   () => searchModel.examSiteId,
  //   (val) => {
  //     search();
  //   }
  // );

  const switchChange = (rowIndex: number, head: string, bool: boolean) => {
    console.log(rowIndex, head, bool);
    tableData.value[rowIndex].timePeriodList.find(
      (item: any) => item.timePeriodStr === head
    ).enable = bool;
  };

  const switchBatchChange = (rowIndex: number, bool: boolean) => {
    tableData.value[rowIndex].batchStatus = bool;
    tableData.value[rowIndex].timePeriodList.forEach((item: any) => {
      item.enable = bool;
    });
    tableKey.value = `${Date.now()}`;
  };

  const saveLoading = ref(false);
  const save = () => {
    saveLoading.value = true;
    const arr = [];
    for (let i = 0; i < tableData.value.length; i++) {
      arr.push(...tableData.value[i].timePeriodList);
    }
    saveReservation(arr, { examSiteId: searchModel.examSiteId })
      .then(() => {
        Message.success('保存成功！');
        search();
      })
      .finally(() => {
        saveLoading.value = false;
      });
  };

  let teachOptions: any = [];
  const getTeachOptions = (data: any) => {
    teachOptions = data || [];
  };

  const selfYYDefaultValue = ref<any>(null);
  watch(
    () => searchModel.teachingId,
    (val) => {
      if (val) {
        selfYYDefaultValue.value = teachOptions.find(
          (item: any) => item.id === searchModel.teachingId
        ).selfApplyEnable;
      }
    }
  );
  const selfYY = (bool: string | number | boolean) => {
    toggleSelfYYStatus({
      id: searchModel.teachingId,
      enable: bool as boolean,
    }).then(() => {
      Message.success('设置成功');
    });
  };
</script>
