<template>
  <a-modal
    v-model:visible="visible"
    :width="500"
    title-align="start"
    top="10vh"
    :align-center="false"
    :mask-closable="false"
    :esc-to-close="false"
    @before-open="modalBeforeOpen"
  >
    <template #title> {{ title }} </template>
    <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
        ></a-input>
      </a-form-item>
      <a-form-item field="code" label="考点代码">
        <a-input
          v-model.trim="formData.code"
          placeholder="请输入"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item field="address" label="考点地址">
        <a-input
          v-model.trim="formData.address"
          placeholder="请输入"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item field="teachingId" label="教学点">
        <SelectTeaching
          v-model="formData.teachingId"
          placeholder="请选择"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="guide" label="考点指引">
        <a-textarea
          v-model="formData.guide"
          placeholder="请输入"
          :auto-size="{
            minRows: 4,
            maxRows: 10,
          }"
          :max-length="999"
        />
      </a-form-item>
    </a-form>

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

<script setup lang="ts">
  import { computed, nextTick, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { FormInstance } from '@arco-design/web-vue/es/form';
  import { updateAgent } from '@/api/base';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { AgentItem, AgentUpdateParams } from '@/api/types/base';
  import { FormRules } from '@/types/global';

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

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

  const defaultFormData = {
    id: undefined,
    name: '',
    code: '',
    address: '',
    teachingId: null,
    guide: '',
  };

  const props = defineProps<{
    rowData: AgentItem;
  }>();
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}考点`);

  const formRef = ref<FormInstance>();
  const formData = reactive<AgentUpdateParams>({ ...defaultFormData });
  const rules: FormRules<keyof AgentUpdateParams> = {
    name: [
      {
        required: true,
        message: '请输入名称',
      },
      {
        max: 50,
        message: '名称不能超过50字符',
      },
    ],
    code: [
      {
        required: true,
        message: '请输入代码',
      },
      {
        max: 50,
        message: '代码不能超过50字符',
      },
    ],
    address: [
      {
        required: true,
        message: '请输入地址',
      },
      {
        max: 100,
        message: '地址不能超过100字符',
      },
    ],
    teachingId: [
      {
        required: true,
        message: '请选择教学点',
      },
    ],
    guide: [
      {
        required: true,
        message: '请输入考点指引',
      },
    ],
  };

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

    setLoading(true);
    const datas = objAssign(formData, {});
    const res = await updateAgent(datas).catch(() => false);
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified', datas);
    close();
  }
  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData.id) {
      objModifyAssign(formData, props.rowData);
    } else {
      objModifyAssign(formData, defaultFormData);
    }
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }
</script>
