<template>
  <div class="p-8px bg-white">
    <div class="px-4">
      <BasicForm @register="registerForm">
        <template #title1>
          <TypographyTitle :level="4">基础信息</TypographyTitle>
          <Divider></Divider>
        </template>
        <template #RangePicker>
          <TypographyTitle :level="4">比赛时间及赛程安排</TypographyTitle>
          <Divider></Divider>
        </template>
        <template #ZtCustomTable1="{ model, field }">
          <ZtCustomTable
            :tableColumn="ScheduleArrangementColums"
            v-model:value="model[field]"
            v-model:deleteId="model['scheduleDTOSList']"
          ></ZtCustomTable>
        </template>
        <template #title3>
          <TypographyTitle :level="4">比赛项目、价格、地点、说明</TypographyTitle>
          <Divider></Divider>
        </template>
        <template #ZtCustomTable2="{ model, field }">
          <ZtCustomTable
            :tableColumn="SchedulePricesColums"
            v-model:value="model[field]"
            v-model:deleteId="model['gamePriceRulesList']"
          ></ZtCustomTable>
        </template>
        <template #title4>
          <TypographyTitle :level="4">配套保险</TypographyTitle>
          <Divider></Divider>
        </template>
        <template #address="{ model, field }">
          <JAreaSelect v-model:province="model['provinceCode']" v-model:city="model['cityCode']" v-model:area="model['areaCode']"></JAreaSelect>
        </template>
        <template #aptitudes="{ model, field }">
          <div class="flex flex-wrap">
            <a-button type="primary" @click="model[field].push({ name: '' })">添加资质</a-button>
            <div class="ml20px flex mb-20px" v-for="(item, idx) in model[field]" :key="idx">
              <FormItem>
                <a-input v-model:value="item.name" placeholder="请输入资质">
                  <template #suffix>
                    <a-button type="primary" danger @click="model[field].splice(idx, 1)">删除</a-button>
                  </template>
                </a-input>
              </FormItem>
            </div>
          </div>
        </template>
        <template #formFooter>
          <div style="margin: 0 auto">
            <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-competitionCommon">
  import { TypographyTitle, Divider, FormItem, Input, Button } from 'ant-design-vue';
  import { BasicForm, useForm, JAreaSelect } from '/@/components/Form/index';
  import ZtCustomTable from '/@/components/ZtCustomTable/index.vue';
  import { formSchema, SchedulePricesColums } from './competition.data';
  import { BasicColumn } from '/@/components/Table';
  import { getSprotProject } from '@/api/common/api';
  import { getDetaile, saveOrUpdate } from './competition.api';
  import dayjs from 'dayjs';
  import { nextTick, onUnmounted, ref, toRefs, unref, watch, watchEffect } from 'vue';
  import { areAllItemsAllFieldsFilled, extractRefs } from '/@/utils';
  import { message } from 'ant-design-vue/lib';
  import { useRoute } from 'vue-router';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { getDataByCode } from '@/components/Form/src/utils/areaDataUtil';
  import { matchCityByFirstFourDigits, matchProvinceByFirstThreeDigits } from '/@/utils/map';
  const { close: closeTab } = useTabs();
  const route = useRoute();

  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const isSubmit = ref(false);
  async function back() {
    await closeTab();
  }
  async function save() {
    await validate();
    const form = getFieldsValue();
    const gamePriceRules = form.gamePriceRules.map((it) => {
      return {
        ...extractRefs(it.editValueRefs),
        id: it.id,
      };
    });
    const scheduleRules = form.scheduleDTOS.map((it) => {
      return {
        ...extractRefs(it.editValueRefs),
        id: it.id,
      };
    });
    console.log(form, '表单数据');

    if (!valiDataCustom(gamePriceRules) || !valiDataCustom(scheduleRules)) {
      return message.error('请填写完整');
    }
    const newObj = {
      game: {
        ...form,
        aptitudes: form.aptitudes ? form.aptitudes.map((it) => it.name).join(',') : null,
        endTime: form.competitionTime.split(',')[1],
        startTime: form.competitionTime.split(',')[0],
        id: route.query.id,
        gamePriceRules: null,
        scheduleDTOS: null,
      },
      gamePriceRules: gamePriceRules,
      scheduleDTOSList: form.scheduleDTOSList,
      gamePriceRulesList: form.gamePriceRulesList,
      scheduleDTOS: scheduleRules.map((it) => {
        return {
          ...it,
          startTime: it.time[0],
          endTime: it.time[1],
        };
      }),
    };
    isSubmit.value = true;
    try {
      await saveOrUpdate(newObj, Number(route.query.type) == 1);
      isSubmit.value = false;
      back();
    } catch (error) {
      console.log(error);
      isSubmit.value = false;
    }
  }
  const ScheduleArrangementColums: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 220,
      editComponent: 'Input',
      editRule: true,
      editRow: true,
      editable: true,
      editComponentProps: {
        placeholder: '请输入名称',
        size: 'middle',
      },
    },
    {
      title: '时间段',
      dataIndex: 'time',
      width: 450,
      editComponent: 'RangePicker',
      editRule: true,
      editComponentProps: {
        showTime: true,
        size: 'middle',
        placeholder: ['开始时间', '结束时间'],
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        disabledDate: (current) => {
          const fields = getFieldsValue();
          if (fields.competitionTime && fields.competitionTime.length >= 2) {
            const [startDate, endDate] = fields.competitionTime.split(',');
            return current && (current < dayjs(startDate).startOf('day') || current > dayjs(endDate).endOf('day'));
          }
          return current && current < dayjs().endOf('day');
        },
      },
      editRow: true,
      editable: true,
    },
    {
      title: '安排',
      dataIndex: 'arrange',
      width: 220,
      editComponent: 'Input',
      editRule: true,
      editRow: true,
      editable: true,
      editComponentProps: {
        size: 'middle',
      },
    },
    {
      key: 'op',
      dataIndex: 'operation',
      title: 'operation',
      fixed: 'right',
      width: 80,
    },
  ];

  function valiDataCustom(data) {
    if (!areAllItemsAllFieldsFilled(data)) {
      return false;
    }
    return true;
  }

  async function getDetaileData() {
    const res = await getDetaile({ id: route.query.id });
    setFieldsValue({
      ...res.game,
      competitionTime: [res.game.startTime, res.game.endTime],
      gamePriceRules: res.gamePriceRules.map((it) => {
        return {
          ...it,
          type: String(it.type),
        };
      }),
      scheduleDTOS: res.scheduleDTOS.map((it) => {
        return {
          ...it,
          time: [it.startTime, it.endTime],
        };
      }),
      aptitudes: res.game.aptitudes.split(',').map((it) => {
        return {
          name: it,
        };
      }),
    });
  }

  watch(
    () => route.query.type,
    () => {
      if (Number(route.query.type) != 0) {
        getDetaileData();
      }
    },
    { immediate: true }
  );
</script>
<style>
  /* #panel {
    position: absolute;
    background-color: white;
    max-height: 300px;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
  } */
</style>
