<template>
  <div class="part-box" :style="{ minHeight: '300px' }">
    <a-form ref="formRef" :model="formData" :rules="rules" auto-label-width>
      <a-form-item field="notice" label="考试说明">
        <a-textarea
          v-model="formData.notice"
          placeholder="请输入"
          :auto-size="{
            minRows: 4,
            maxRows: 10,
          }"
          :max-length="999"
        />
      </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 { updateTaskNotice } 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 } from '@/api/types/order';

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

  const defaultFormData = {
    id: 0,
    notice: '',
  };
  type FormDataType = typeof defaultFormData;

  const formRef = ref<FormInstance>();
  const formData = reactive<FormDataType>({ ...defaultFormData });
  const rules: Partial<Record<keyof FormDataType, FieldRule[]>> = {
    notice: [
      {
        required: true,
        message: '请输入内容',
      },
    ],
  };

  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 updateTaskNotice(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified');
  }
  /* init modal */
  function initData() {
    objModifyAssign(formData, props.rowData);
  }
  onMounted(() => {
    initData();
  });
</script>
