<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-list
        class="time-box"
        :virtual-list-props="{
          height: 300,
          fixedSize: true,
          threshold: 20,
          buffer: 5,
        }"
        :data="formData.times"
        :bordered="false"
      >
        <template #item="{ item }">
          <a-form-item
            :field="`times[${item.no - 1}].startTime`"
            :rules="rules"
            :label="item.no + ''"
          >
            <select-range-datetime
              v-model:startTime="item.startTime"
              v-model:endTime="item.endTime"
              popup-container=".modify-task"
            >
            </select-range-datetime>
            <a-button
              class="ml-10"
              status="danger"
              @click="toDelete(item.no - 1)"
            >
              <template #icon>
                <svg-icon name="icon-delete"></svg-icon>
              </template>
            </a-button>
          </a-form-item>
        </template>
      </a-list>
    </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, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { updateTaskTime, deleteTaskTime } from '@/api/order';
  import useLoading from '@/hooks/loading';
  import type { FormInstance, FieldRule } from '@arco-design/web-vue/es/form';
  import { TaskItemDetail } from '@/api/types/order';
  import { modalConfirm } from '@/utils/arco';

  import AddTimes from './addTimes.vue';

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

  interface FormDataType {
    id: number;
    times: Array<{
      id: number | null;
      startTime: number | undefined;
      endTime: number | undefined;
      no: number;
    }>;
  }

  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.map((item) => {
        return { ...item, no: 0 };
      })
    );
    updateTimeIndex();
  }

  async function toDelete(index: number) {
    const confirmRes = await modalConfirm(
      '提示',
      `确定要删除当前时间吗?`
    ).catch(() => false);
    if (confirmRes !== 'confirm') return;

    if (formData.times[index].id) {
      await deleteTaskTime(formData.times[index].id as number);
    }
    formData.times.splice(index, 1);
    updateTimeIndex();
    await formRef.value?.validate();
  }

  function updateTimeIndex() {
    formData.times.forEach((item, index) => {
      item.no = 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 = props.rowData.timeList.map((item, index) => {
      return {
        no: index + 1,
        ...item,
      };
    });
    formData.id = props.rowData.id;
  }

  watch(
    () => props.rowData.timeList,
    () => {
      initData();
    }
  );
  onMounted(() => {
    initData();
  });
</script>

<style lang="less" scoped>
  .time-box {
    padding: 10px 0;
    border-radius: var(--border-radius-small);
    border: 1px solid var(--color-border);
  }
</style>
