<template>
  <div class="p-8px bg-white">
    <div class="px-4">
      <BasicForm @register="registerForm">
        <template #title1>
          <div class="flex">
            <TypographyTitle :level="4">开放时间</TypographyTitle>
            <a-button type="link" @click="handleClick" v-if="getIsMerchant"> 查看教学日与非教学日日历 </a-button>
          </div>
          <Divider></Divider>
        </template>
        <template #title2>
          <TypographyTitle :level="4">封面、配套保险、使用须知</TypographyTitle>
          <Divider></Divider>
        </template>
        <template #title3 v-if="siteId">
          <TypographyTitle :level="4">场地二维码</TypographyTitle>
          <Divider></Divider>
          <div class="p-20px flex">
            <div>
              <QRCode :value="`https://api.qlapp.cn/schoolOrder/?placeId=${siteId}`" ref="qrcodeCanvasRef" />
              <a-button type="link" block class="mt20px" @click="downloadImage">下载图片</a-button>
            </div>
          </div>
        </template>
        <template #tenant="{ model, field }">
          <ApiSelect
            :api="Business"
            labelField="name"
            valueField="tenantId"
            :params="{
              orgCode: userInfo?.orgCode,
              type: 0,
            }"
            v-model:value="model[field]"
            @change="handleOption"
          ></ApiSelect>
        </template>
        <template #ZtCustomTable1="{ model, field }">
          <ZtCustomTable :tableColumn="ScheduleArrangementColums" :showAction="getIsMerchant" v-model:value="model[field]" :count="3"></ZtCustomTable>
        </template>
        <template #ZtCustomTable2="{ model, field }">
          <ZtCustomTable :tableColumn="ScheduleArrangementColums" :showAction="getIsMerchant" v-model:value="model[field]" :count="1"></ZtCustomTable>
        </template>
        <template #formFooter>
          <div style="margin: 0 auto" v-if="getIsMerchant">
            <a-button type="primary" @click="save" class="mr-2" :loading="isSubmit"> 保存</a-button>
            <a-button type="error" @click="back" class="mr-2"> 关闭</a-button>
          </div>
        </template>
      </BasicForm>
      <div class="h-20px"></div>
    </div>
  </div>
</template>
<script lang="ts" setup name="business-management-schoolOpen">
  import { TypographyTitle, Divider, QRCode, message } from 'ant-design-vue';
  import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
  import ZtCustomTable from '/@/components/ZtCustomTable/index.vue';
  import { Business } from '../gymnasiumBag/gymnasiumBag.api';
  import { useUserStore } from '/@/store/modules/user';
  import { formSchema, ScheduleArrangementColums } from './schoolOpen.data';
  import { getDetails, saveOrUpdate } from './schoolOpen.api';
  import { ref, unref } from 'vue';
  import { useRouter } from 'vue-router';
  import { storeToRefs } from 'pinia';
  import { areAllItemsAllFieldsFilled } from '@/utils';

  const { userInfo, getIsMerchant } = storeToRefs(useUserStore());
  const router = useRouter();
  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const isSubmit = ref(false);

  function back() {
    router.back();
  }

  async function save() {
    await validate();
    isSubmit.value = true;
    const form = await getFieldsValue();
    console.log(form.noTeachingDay, 'form', form.teachingDay);
    const newNoTeachingDay = form.noTeachingDay.map((it) => {
      return {
        ticketNum: it.editValueRefs.ticketNum ? unref(it.editValueRefs.ticketNum) : null,
        startTime: it.editValueRefs.time ? unref(it.editValueRefs.time)[0] : null,
        endTime: it.editValueRefs.time ? unref(it.editValueRefs.time)[1] : null,
      };
    });
    const newTeachingDay = form.teachingDay.map((it) => {
      return {
        ticketNum: it.editValueRefs.ticketNum ? unref(it.editValueRefs.ticketNum) : null,
        startTime: it.editValueRefs.time ? unref(it.editValueRefs.time)[0] : null,
        endTime: it.editValueRefs.time ? unref(it.editValueRefs.time)[1] : null,
      };
    });
    if (!areAllItemsAllFieldsFilled(newTeachingDay)) {
      isSubmit.value = false;
      return message.error('请填写完整的教学日信息');
    }
    if (!areAllItemsAllFieldsFilled(newNoTeachingDay)) {
      isSubmit.value = false;

      return message.error('请填写完整的非教学日信息');
    }

    const newObj = {
      ...form,
      noTeachingDay: JSON.stringify({
        data: newNoTeachingDay,
      }),
      teachingDay: JSON.stringify({
        data: newTeachingDay,
      }),
    };
    console.log(newObj, 'newObj');
    try {
      await saveOrUpdate(newObj);
      isSubmit.value = false;
      getData();
    } catch (error) {
      console.log(error);
      isSubmit.value = false;
    }
    console.log(newObj);
  }

  const qrcodeCanvasRef = ref();

  async function downloadImage() {
    const url = await qrcodeCanvasRef.value.toDataURL();
    const a = document.createElement('a');
    a.download = 'competition.png';
    a.href = url;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  async function getData() {
    const res = await getDetails({ orgCode: useUserStore().userInfo?.orgCode });
    if (!res.teachingDay) return;
    handleCommonSet(res);
    console.log(JSON.parse(res.noTeachingDay));
  }

  getData();

  function handleClick() {
    router.push({ path: '/informationManagement/teachorNoteach' });
  }

  async function handleOption(options) {
    const res = await Business({ orgCode: useUserStore().userInfo?.orgCode, type: 0 });
    const orgCode = res.find((it) => it.tenantId == options).orgCode;
    if (orgCode) {
      const res = await getDetails({ orgCode: orgCode });
      if (!res.noTeachingDay) return;

      handleCommonSet(res);
    }
  }

  const siteId = ref();

  function handleCommonSet(res) {
    // console.log( res,'获取数据')
    siteId.value = res.siteId;
    console.log(`https://api.qlapp.cn/school/?placeId=${siteId.value}`, '获取到的siteid');
    setFieldsValue({
      ...res,
      insureIds: res.insureIds ? res.insureIds.split(',') : '',
      noTeachingDay: res.noTeachingDay
        ? JSON.parse(res.noTeachingDay).data.map((it) => {
            return { ...it, time: [it.startTime, it.endTime] };
          })
        : [],
      teachingDay: JSON.parse(res.teachingDay).data.map((it) => {
        return { ...it, time: [it.startTime, it.endTime] };
      }),
    });
  }
</script>
