<#include "/common/utils.ftl">
<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="${entityName}Form">
          <a-row>
<#assign need_category = false>
<#assign bpm_flag=false>
<#assign need_pca = false>
<#assign need_search = false>
<#assign need_dept_user = false>
<#assign need_switch = false>
<#assign need_dept = false>
<#assign need_multi = false>
<#assign need_popup = false>
<#assign need_popup_dict = false>
<#assign need_select_tag = false>
<#assign need_select_tree = false>
<#assign need_time = false>
<#assign need_markdown = false>
<#assign need_upload = false>
<#assign need_image_upload = false>
<#assign need_editor = false>
<#assign need_checkbox = false>
<#assign hasOnlyValidate = false> 
<#assign need_range_number = false>
<#assign is_like = false>
<#assign form_span = 24>
<#if tableVo.fieldRowNum==2>
<#assign form_span = 12>
<#elseif tableVo.fieldRowNum==3>
<#assign form_span = 8>
<#elseif tableVo.fieldRowNum==4>
<#assign form_span = 6>
</#if>
<#list columns as po>
<#if po.fieldDbName=='bpm_status'>
  <#assign bpm_flag=true>
</#if>        
<#if po.isShow == 'Y' && po.fieldValidType?default("") == 'only'>
      <#assign hasOnlyValidate = true>
</#if>
  <#assign formEntityName>${entityName}Form</#assign>
  <#include "/common/form/native/vue3NativeForm.ftl">
</#list>
            <#if bpm_flag>
            <a-col v-if="showFlowSubmitButton" :span="24" style="width: 100%;text-align: center;">
              <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
            </a-col>
            </#if>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  <#include "/common/form/native/vue3NativeImport.ftl">
  import { getDateByPicker, getValueType } from '/@/utils';
  import { saveOrUpdate } from '../${entityName}.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  <#if hasOnlyValidate == true>
  import { duplicateValidate } from '/@/utils/helper/validator'
  </#if>
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    <#include "/common/init/native/vue3NativeMainInitValue.ftl">
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  <#include "/common/validatorRulesTemplate/native/vue3MainNative.ftl">
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  //日期个性化选择
  const fieldPickers = reactive({
  <#list columns as po>
    <#if po.extendParams?exists && po.extendParams.picker?exists>
    ${po.fieldName}: '${po.extendParams.picker}',
    </#if>
  </#list>
  });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  <#if bpm_flag>
  onMounted(()=>{
    initFormData();
  });
  //渲染流程表单数据
  const queryByIdUrl = '/${entityPackagePath}/${entityName?uncap_first}/queryById';
  async function initFormData(){
    if(props.formBpm === true){
      let params = {id: props.formData.dataId};
      const data = await defHttp.get({url: queryByIdUrl, params});
      //设置表单的值
      edit({...data});
    }
  }
  // 是否显示提交按钮
  const showFlowSubmitButton = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return true
      }
    }
    return false
  });
  </#if>
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      // 更新个性化日期选择器的值
      model[data] = getDateByPicker(model[data], fieldPickers[data]);
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

	<#if need_popup>
  /**
   *  popup组件值改变事件
   */
  function setFieldsValue(map) {
    Object.keys(map).map((key) => {
      formData[key] = map[key];
    });
  }
	</#if>

	<#if need_category || need_select_tree>
  /**
   * 值改变事件触发
   * @param key
   * @param value
   */
  function handleFormChange(key, value) {
    formData[key] = value;
  }
  </#if>
 <#list columns as po>
  <#if po.isShow == 'Y' && po.fieldValidType?default("") == 'only'>
  async function ${po.fieldName}Duplicatevalidate(_r, value) {
    return duplicateValidate('${tableName}', '${po.fieldDbName}', value, formData.id || '')
  }
  </#if>
  </#list>
  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px 20px;
  }
</style>
