<template>
  <div class="part-box" :style="{ minHeight: '300px' }">
    <a-form ref="formRef" :model="formData" :rules="rules" auto-label-width>
      <a-form-item field="name" label="预约任务名称">
        <a-input
          v-model.trim="formData.name"
          placeholder="请输入"
          allow-clear
          :max-length="50"
        ></a-input>
      </a-form-item>
      <a-form-item field="allowApplyCancelDays" label="学生自主操作限制">
        <span>考前</span>
        <a-input-number
          v-model="formData.allowApplyCancelDays"
          :style="{ width: '120px', margin: '0 10px' }"
          placeholder="请输入"
          mode="button"
          :min="1"
          :max="999"
          :step="1"
          :formatter="intFormatter"
        />
        <span>天，禁止考生自主取消和预约</span>
      </a-form-item>
      <a-form-item field="selfApplyStartTime" label="第一阶段开启时间">
        <select-range-datetime
          v-model:startTime="formData.selfApplyStartTime"
          v-model:endTime="formData.selfApplyEndTime"
          :render-to-body="false"
          popup-container=".modify-task"
        >
        </select-range-datetime>
        <template #extra>
          <div>本阶段考生只能预约所属教学点下的考点</div>
        </template>
      </a-form-item>
      <a-form-item field="openApplyStartTime" label="第三阶段开启时间">
        <select-range-datetime
          v-model:startTime="formData.openApplyStartTime"
          v-model:endTime="formData.openApplyEndTime"
          :render-to-body="false"
          popup-container=".modify-task"
        >
        </select-range-datetime>
        <template #extra>
          <div>本阶段考生可以预约其他教学点下的考点</div>
        </template>
      </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>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { updateTaskRule } from '@/api/order';
  import useLoading from '@/hooks/loading';
  import type { FormInstance, FieldRule } from '@arco-design/web-vue/es/form';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { TaskItemDetail, TaskRuleUpdateParams } from '@/api/types/order';
  import { intFormatter } from '@/utils/arco';

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

  const defaultFormData = {
    id: null,
    name: '',
    allowApplyCancelDays: 1,
    selfApplyStartTime: undefined,
    selfApplyEndTime: undefined,
    openApplyStartTime: undefined,
    openApplyEndTime: undefined,
    enable: false,
  };
  const formRef = ref<FormInstance>();
  const formData = reactive<TaskRuleUpdateParams>({ ...defaultFormData });
  const rules: Partial<Record<keyof TaskRuleUpdateParams, FieldRule[]>> = {
    name: [
      {
        required: true,
        message: '请输入名称',
      },
      {
        maxLength: 50,
        message: '名称不能超过50字符',
      },
    ],
    allowApplyCancelDays: [
      {
        required: true,
        message: '请输入学生自主操作限制',
      },
    ],
    selfApplyStartTime: [
      {
        required: true,
        message: '请选择自主预约时间',
      },
    ],
    openApplyStartTime: [
      {
        required: true,
        message: '请选择开放预约时间',
      },
      {
        validator: (value, callback) => {
          if (
            formData.openApplyStartTime &&
            formData.selfApplyEndTime &&
            formData.openApplyStartTime < formData.selfApplyEndTime
          ) {
            return callback('第三阶段开启时间不得早于第一阶段开启时间');
          }
          return callback();
        },
      },
    ],
  };

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

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

    setLoading(true);
    const datas = objAssign(formData, {});
    let res = true;
    await updateTaskRule(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified');
  }
  /* init modal */
  function initData() {
    if (props.rowData.id) {
      objModifyAssign(formData, props.rowData);
    } else {
      objModifyAssign(formData, defaultFormData);
    }
  }
  onMounted(() => {
    initData();
  });
</script>
