<template>
  <a-modal
    v-model:visible="visible"
    :width="800"
    title-align="start"
    top="10vh"
    :align-center="false"
    :mask-closable="false"
    :esc-to-close="false"
    @before-open="modalBeforeOpen"
  >
    <template #title> 编辑考点指引 </template>
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      auto-label-width
      layout="vertical"
    >
      <a-form-item
        field="notice"
        label="考点指引"
        hide-label
        :content-flex="false"
      >
        <rich-editor
          :key="guideKey"
          v-model="formData.guide"
          placeholder="请输入"
        />
      </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 { nextTick, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { FormInstance } from '@arco-design/web-vue/es/form';
  import { updateAgentGuide, agentGuideDetail } from '@/api/base';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { objAssign, randomCode } from '@/utils/utils';
  import { AgentItem, AgentGuideUpdateParams } from '@/api/types/base';
  import { FormRules } from '@/types/global';

  import RichEditor from '@/components/rich-editor/index.vue';

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

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

  const defaultFormData = {
    id: 0,
    guide: '',
  };

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

  const formRef = ref<FormInstance>();
  const formData = reactive<AgentGuideUpdateParams>({ ...defaultFormData });
  const rules: FormRules<keyof AgentGuideUpdateParams> = {
    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, {});
    let res = true;
    await updateAgentGuide(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified', datas);
    close();
  }

  const guideKey = ref('');

  /* init modal */
  async function modalBeforeOpen() {
    const guide = await agentGuideDetail(props.rowData.id);
    formData.id = props.rowData.id;
    formData.guide = guide || '';
    guideKey.value = randomCode();

    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }
</script>
