<template>
  <a-modal v-model:visible="visible"
           modal-class="modal-form-large"
           title-align="start"
           :title="title"
           :top="80"
           :align-center="false"
           :draggable="true"
           :mask-closable="false"
           :unmount-on-close="true"
           :ok-button-props="{ disabled: loading }"
           :cancel-button-props="{ disabled: loading }"
           :on-before-ok="handlerOk"
           @close="handleClose">
    <a-spin class="full" :loading="loading">
      <a-form :model="formModel"
              ref="formRef"
              label-align="right"
              :auto-label-width="true"
              :rules="formRules">
        #foreach($field in ${table.fields})
        #if("$field.propertyName" != "id")
        <!-- $field.comment -->
        <a-form-item field="${field.propertyName}" label="${field.comment}">
        #if(${dictMap.containsKey(${field.propertyName})})
          <a-select v-model="formModel.${field.propertyName}"
                    :options="toOptions($dictMap.get(${field.propertyName}).keyField)"
                    placeholder="请选择${field.comment}" />
          #else
          #if("$field.propertyType" == "Integer" || "$field.propertyType" == "Long")
          <a-input-number v-model="formModel.${field.propertyName}"
                          placeholder="请输入${field.comment}"
                          hide-button />
          #elseif("$field.propertyType" == "Date")
          <a-date-picker v-model="formModel.${field.propertyName}"
                         style="width: 100%"
                         placeholder="请选择${field.comment}"
                         show-time />
          #else
          <a-input v-model="formModel.${field.propertyName}"
                   placeholder="请输入${field.comment}"
                   allow-clear />
          #end
          #end
        </a-form-item>
        #end
        #end
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts">
  export default {
    name: '${vue.featureEntityFirstLower}FormModal'
  };
</script>

<script lang="ts" setup>
  import type { ${vue.featureEntity}UpdateRequest } from '@/api/${vue.module}/${vue.feature}';
  import { ref } from 'vue';
  import useLoading from '@/hooks/loading';
  import useVisible from '@/hooks/visible';
  import formRules from '../types/form.rules';
  #if($dictMap.entrySet().size() > 0)
  import { #foreach($entry in ${dictMap.entrySet()})${entry.value.keyField}#if($foreach.hasNext), #end#end } from '../types/const';
  #else
  import {} from '../types/const';
  #end
  import { create${vue.featureEntity}, update${vue.featureEntity} } from '@/api/${vue.module}/${vue.feature}';
  import { Message } from '@arco-design/web-vue';
  #if($dictMap.entrySet().size() > 0)
  import { useDictStore } from '@/store';
  #end

  const emits = defineEmits(['added', 'updated']);

  const { visible, setVisible } = useVisible();
  const { loading, setLoading } = useLoading();
  #if($dictMap.entrySet().size() > 0)
  const { toOptions } = useDictStore();
  #end

  const title = ref<string>();
  const isAddHandle = ref<boolean>(true);
  const formRef = ref<any>();
  const formModel = ref<${vue.featureEntity}UpdateRequest>({});

  const defaultForm = (): ${vue.featureEntity}UpdateRequest => {
    return {
    #foreach($field in ${table.fields})
      ${field.propertyName}: undefined,
    #end
    };
  };

  // 打开新增
  const openAdd = () => {
    title.value = '添加${table.comment}';
    isAddHandle.value = true;
    renderForm({ ...defaultForm() });
    setVisible(true);
  };

  // 打开修改
  const openUpdate = (record: any) => {
    title.value = '修改${table.comment}';
    isAddHandle.value = false;
    renderForm({ ...defaultForm(), ...record });
    setVisible(true);
  };

  // 渲染表单
  const renderForm = (record: any) => {
    formModel.value = Object.assign({}, record);
  };

  defineExpose({ openAdd, openUpdate });

  // 确定
  const handlerOk = async () => {
    setLoading(true);
    try {
      // 验证参数
      const error = await formRef.value.validate();
      if (error) {
        return false;
      }
      if (isAddHandle.value) {
        // 新增
        await create${vue.featureEntity}(formModel.value);
        Message.success('创建成功');
        emits('added');
      } else {
        // 修改
        await update${vue.featureEntity}(formModel.value);
        Message.success('修改成功');
        emits('updated');
      }
      // 清空
      handlerClear();
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 关闭
  const handleClose = () => {
    handlerClear();
  };

  // 清空
  const handlerClear = () => {
    setLoading(false);
  };

</script>

<style lang="less" scoped>

</style>
