<template>
  <a-modal
    v-model:visible="visible"
    title-align="start"
    title="添加时间"
    :width="800"
    top="10vh"
    :align-center="false"
    @before-open="modalBeforeOpen"
  >
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item label="添加方式" required>
        <a-radio-group v-model="formData.type" @change="typeChange">
          <a-radio value="simple">简单创建</a-radio>
          <a-radio value="loop">循环创建</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        v-if="IS_LOOP"
        label="日期范围"
        field="date.startTime"
        :rules="[
          {
            required: true,
            message: '请选择时间',
          },
        ]"
      >
        <select-range-datetime
          v-model="formData.date"
          :show-time="false"
          format="YYYY-MM-DD"
        >
        </select-range-datetime>
      </a-form-item>

      <a-form-item
        v-for="(time, index) in formData.times"
        :key="index"
        :field="`times[${index}].startTime`"
        :rules="[
          {
            required: true,
            message: '请选择时间',
          },
        ]"
        :label="index + 1 + ''"
      >
        <select-range-time
          v-if="IS_LOOP"
          v-model="formData.times[index]"
          disable-confirm
          :style="{ width: '256px' }"
        >
        </select-range-time>
        <select-range-datetime v-else v-model="formData.times[index]">
        </select-range-datetime>
        <a-button class="ml-10" @click="toAdd(index)">
          <template #icon>
            <icon-plus />
          </template>
        </a-button>
        <a-button
          status="danger"
          :disabled="formData.times.length === 1"
          @click="toDelete(index)"
        >
          <template #icon>
            <svg-icon name="icon-delete"></svg-icon>
          </template>
        </a-button>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="close">取消</a-button>
      <a-button type="primary" @click="confirm">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, nextTick, reactive, ref } from 'vue';
  import type { FormInstance } from '@arco-design/web-vue/es/form';
  import useModal from '@/hooks/modal';
  import { formatDate, objModifyAssign } from '@/utils/utils';
  import { Message } from '@arco-design/web-vue';

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

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  const emit = defineEmits(['confirm']);

  function getItemItem() {
    return {
      id: null,
      startTime: null,
      endTime: null,
    };
  }
  function getDefaultFormData() {
    return {
      type: 'simple',
      date: {
        startTime: null,
        endTime: null,
      },
      times: [getItemItem()],
    };
  }
  const formRef = ref<FormInstance>();
  const formData = reactive(getDefaultFormData());
  const IS_LOOP = computed(() => {
    return formData.type === 'loop';
  });

  function typeChange() {
    formData.times = [getItemItem()];
  }

  function toAdd(index: number) {
    formData.times.splice(index + 1, 0, getItemItem());
  }

  function toDelete(index: number) {
    if (formData.times.length <= 1) {
      Message.error('不可再删除！');
      return;
    }
    formData.times.splice(index, 1);
  }

  /* confirm */
  async function confirm() {
    const err = await formRef.value?.validate();
    if (err) return;

    if (!IS_LOOP.value) {
      emit('confirm', formData.times);
      close();
      return;
    }

    const times = [];
    const oneDay = 24 * 60 * 60 * 1000;
    for (
      let i = formData.date.startTime;
      i <= formData.date.endTime;
      i += oneDay
    ) {
      const curDate = formatDate('YYYY/MM/DD', new Date(i));
      formData.times.forEach((item) => {
        times.push({
          id: null,
          startTime: new Date(`${curDate} ${item.startTime}`).getTime(),
          endTime: new Date(`${curDate} ${item.endTime}`).getTime(),
        });
      });
    }

    emit('confirm', times);
    close();
  }

  /* init modal */
  function modalBeforeOpen() {
    objModifyAssign(formData, getDefaultFormData());
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }
</script>
