<#include "/common/utils.ftl">
<#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 need_range_number = 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>
<#assign hasOne2manyTable = false>
<#assign subTabActiveKey = ''>
<#assign subMainFieldMap={}>
<#assign subTableColumnsKey=[]>
<#assign hasOnlyValidate = false>
<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="${entityName}Form" ref="formRef">
          <a-row>
            <#list columns as po>
              <#if po.isShow == 'Y' && po.fieldValidType?default("") == 'only'>
                <#assign hasOnlyValidate = true>
              </#if>
              <#if po.fieldDbName=='bpm_status'>
                  <#assign bpm_flag=true>
              </#if>
      <#assign formEntityName>${entityName}Form</#assign>
      <#include "/common/form/native/vue3NativeForm.ftl">
            </#list>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
<#list subTables as sub><#rt/>
      <a-tab-pane tab="${sub.ftlDescription}" key="${sub.entityName?uncap_first}" :forceRender="true">
			  <#if sub.foreignRelationType =='1'>
        <${Format.humpToShortbar(sub.entityName)}-form ref="${sub.entityName?uncap_first}FormRef" :disabled="disabled"></${Format.humpToShortbar(sub.entityName)}-form>
			  <#else>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="${sub.entityName?uncap_first}TableRef"
          :loading="${sub.entityName?uncap_first}Table.loading"
          :columns="${sub.entityName?uncap_first}Table.columns"
          :dataSource="${sub.entityName?uncap_first}Table.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
			  </#if>
      </a-tab-pane>
</#list>
    </a-tabs>
    <#if bpm_flag>
    <div v-if="showFlowSubmitButton" :span="24" style="width: 100%;text-align: center;margin-top: 10px">
      <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
    </div>
    </#if>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { <#list subTables as sub><#if sub.foreignRelationType =='0'>query${sub.entityName}ListByMainId, </#if></#list>queryDataById, saveOrUpdate } from '../${entityName}.api';
  <#list subTables as sub>
  <#if sub.foreignRelationType =='1'>
  import ${sub.entityName}Form from './${sub.entityName}Form.vue'
	<#else>
  <#assign hasOne2manyTable = true>
  <#assign subTableColumnsKey += ['${sub.entityName?uncap_first}Columns']>
  </#if>
	<#if sub?? && (sub.foreignMainKeys)??>
    <#list sub.foreignMainKeys as key>
      <#assign subMainFieldMap += {"${sub.entityName}": "${dashedToCamel(key)}"}>
    </#list>
  </#if>
  </#list>
  <#if hasOne2manyTable == true>
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {<#list subTableColumnsKey as columnsKey><#if columnsKey_index gt 0>, </#if>${columnsKey}</#list>} from '../${entityName}.data';
  </#if>
  <#include "/common/form/native/vue3NativeImport.ftl">
  <#if hasOnlyValidate == true>
  import { duplicateValidate } from '/@/utils/helper/validator'
  </#if>
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "${entityName}Form",
    components:{
			<#include "/common/form/native/vue3NativeComponents.ftl">
			<#if hasOne2manyTable == true>
      JVxeTable,
			</#if>
			JFormContainer,
<#list subTables as sub>
	<#if sub.foreignRelationType =='1'>
      ${sub.entityName}Form,
	</#if>
</#list>
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const formRef = ref();
      <#list subTables as sub>
      <#if sub_index == 0>
      <#assign subTabActiveKey = '${sub.entityName?uncap_first}'>
      </#if>
      <#if sub.foreignRelationType =='1'>
      const ${sub.entityName?uncap_first}FormRef = ref();
      <#else>
      const ${sub.entityName?uncap_first}TableRef = ref();
      const ${sub.entityName?uncap_first}Table = reactive<Record<string, any>>({
        loading: false,
        columns: ${sub.entityName?uncap_first}Columns,
        dataSource: []
      });
      </#if>
      </#list>
      const activeKey = ref('${subTabActiveKey}');
      const formData = reactive<Record<string, any>>({
        id: '',
        <#include "/common/init/native/vue3NativeMainInitValue.ftl">
      });

      //表单验证
      const validatorRules = reactive({
      <#list columns as po>
      <#if po.isShow == 'Y' && poHasCheck(po)>
        ${po.fieldName}: [<#include "/common/validatorRulesTemplate/native/vue3CoreNative.ftl">],
      </#if>
      </#list>
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      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 = '/${entityPackage}/${entityName?uncap_first}/queryById';
      async function initFormData(){
        if(props.formBpm === true){
          let params = {id: props.formData.dataId};
          const row = await defHttp.get({url: queryByIdUrl, params});
          //设置表单的值
          Object.keys(row).map(k => {
            formData[k] = row[k];
          });
          //子表数据
          <#list subTables as sub>
          <#if sub.foreignRelationType =='1'>
          await ${sub.entityName?uncap_first}FormRef.value.initFormData(row['${subMainFieldMap[sub.entityName]}']);
          <#else>
          const ${sub.entityName?uncap_first}DataList = await query${sub.entityName}ListByMainId(row['${subMainFieldMap[sub.entityName]}']);
          ${sub.entityName?uncap_first}Table.dataSource = [...${sub.entityName?uncap_first}DataList];
          </#if>
          </#list>
        }
      }
      // 是否显示提交按钮
      const showFlowSubmitButton = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return true
          }
        }
        return false
      });
      </#if>
      

      function add() {
        resetFields();
        <#list subTables as sub>
        <#if sub.foreignRelationType =='1'>
        ${sub.entityName?uncap_first}FormRef.value.initFormData();
        <#else>
        ${sub.entityName?uncap_first}Table.dataSource = [];
        </#if>
        </#list>
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        <#list subTables as sub>
        <#if sub.foreignRelationType =='1'>
        await ${sub.entityName?uncap_first}FormRef.value.initFormData(row['${subMainFieldMap[sub.entityName]}']);
        <#else>
        const ${sub.entityName?uncap_first}DataList = await query${sub.entityName}ListByMainId(row['${subMainFieldMap[sub.entityName]}']);
        ${sub.entityName?uncap_first}Table.dataSource = [...${sub.entityName?uncap_first}DataList];
        </#if>
        </#list>
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        <#list subTables as sub>
        <#if sub.foreignRelationType =='1'>
        '${sub.entityName?uncap_first}': ${sub.entityName?uncap_first}FormRef,
        <#else>
        '${sub.entityName?uncap_first}': ${sub.entityName?uncap_first}TableRef,
        </#if>
        </#list>
      });

      async function getFormData() {
        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);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      <#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>

      return {
        <#list subTables as sub>
        <#if sub.foreignRelationType =='1'>
        ${sub.entityName?uncap_first}FormRef,
        <#else>
        ${sub.entityName?uncap_first}TableRef,
        ${sub.entityName?uncap_first}Table,
        </#if>
        </#list>
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        <#if bpm_flag>
        showFlowSubmitButton,
        </#if>
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      }
    }
  });
</script>
<style lang="less" scoped></style>
