<template>
  <div class="part-box" :style="{ minHeight: '300px' }">
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item label="可选考试时段">
        <a-button type="primary" @click="toAdd">添加</a-button>
      </a-form-item>
      <a-form-item
        v-for="(time, index) in formData.times"
        :key="index"
        :field="`times[${index}].startTime`"
        :rules="rules"
      >
        <select-range-datetime
          v-model:startTime="formData.times[index].startTime"
          v-model:endTime="formData.times[index].endTime"
        >
        </select-range-datetime>
        <a-button class="ml-10" status="danger" @click="toDelete(index)">
          <template #icon>
            <svg-icon name="icon-delete"></svg-icon>
          </template>
        </a-button>
      </a-form-item>
    </a-form>
  </div>

  <div class="align-right">
    <a-button @click="close">取消</a-button>
    <a-button type="primary" :disabled="loading" @click="confirm"
      >确认</a-button
    >
  </div>

  <!-- AddTimes -->
  <AddTimes ref="addTimesRef" @confirm="timeSelected" />
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { updateTaskTime } from '@/api/order';
  import useLoading from '@/hooks/loading';
  import type { FormInstance, FieldRule } from '@arco-design/web-vue/es/form';
  import { deepCopy } from '@/utils/utils';
  import { TaskItemDetail } from '@/api/types/order';
  import AddTimes from './addTimes.vue';

  defineOptions({
    name: 'TimeForm',
  });
  const props = defineProps<{
    rowData: TaskItemDetail;
  }>();
  const emit = defineEmits(['cancel', 'modified']);

  interface FormDataType {
    id: number;
    times: TaskItemDetail['timeList'];
  }

  const defaultFormData = {
    id: 0,
    times: [],
  };

  const formRef = ref<FormInstance>();
  const formData: FormDataType = reactive(defaultFormData);

  const rules: FieldRule[] = [
    {
      required: true,
      message: '请选择时间',
    },
  ];

  function close() {
    emit('cancel');
  }

  const addTimesRef = ref();
  function toAdd() {
    addTimesRef.value?.open();
  }

  function timeSelected(times: TaskItemDetail['timeList']) {
    formData.times.push(...times);
  }

  function toDelete(index: number) {
    formData.times.splice(index, 1);
  }

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

    setLoading(true);
    const datas = {
      id: formData.id,
      timeJson: JSON.stringify(formData.times),
    };
    let res = true;
    await updateTaskTime(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified');
  }
  /* init */
  function initData() {
    formData.times = deepCopy(props.rowData.timeList);
    formData.id = props.rowData.id;
  }
  onMounted(() => {
    initData();
  });
</script>
