<template>
  <div id="XAddNativeForm">
    <!-- 骨架屏 -->
    <a-skeleton v-if="!loaded" active :paragraph="{ rows: 3 }" />
    <a-form-model v-else ref="selectForm" :zIndex="1001" :model="form" v-bind="formItemLayoutGen" :layout="layout">
      <template v-for="(item, key) in childTableData">
        <a-row v-if="childTablePriority" :gutter="16" :key="'childTableRow' + key">
          <a-card :title="item.name" :bordered="false" size="small">
            <x-form-table
              :key="'childTable_' + item.model"
              :title="item.name"
              :queryParamsName="item.childTableConfigName"
              :localEditMode="true"
              :fixed-query-form="childTableFixedQueryForm(item)"
              :service-name="serviceName"
              @innerXFormTableEmit="innerXFormTableEmit"
              @afterTableInit="childTableMounted(item)"
              :ref="'childXFormTable_' + item.model"
            ></x-form-table>
          </a-card>
        </a-row>
      </template>
      <template v-if="isSimpleInlineMode">
        <a-row v-for="(row, rowIndex) in simpleInlineRows" :key="'simple-row-' + rowIndex" :gutter="0" type="flex">
          <a-col v-for="(item, itemIndex) in row.items" :key="'simple-item-' + itemIndex" :span="item.span">
            <x-form-item
              class="simple-inline-item"
              :class="{ 'show-label': simpleInline?.showSimpleInlineLabel }"
              v-bind="formItemLayoutGen"
              :attr="item.formItem"
              :disabled="itemDisabled(item.formItem)"
              :read-only="readonly(item.formItem)"
              :files="files"
              :signs="signs"
              :form="form"
              :images="images"
              :service-name="serviceName"
              mode="新增/修改"
              layout="simple-inline"
              :show-label="simpleInline?.showSimpleInlineLabel === true"
              :rules="rules[`${item.formItem.name}${item.formItem.model}`]"
              :get-data-params="getDataParams"
              :env="env"
              :enablePopupToBody="enablePopupToBody"
              @x-form-item-emit-func="emitFunc"
              @rowChoose="rowChoose"
              :setForm="setForm"
              :style="{ margin: 0, padding: '2px' }"
            />
          </a-col>
        </a-row>
      </template>
      <a-row ref="GroupItemRow" v-if="!isSimpleInlineMode">
        <a-col :span="3" v-if="!inXFormGroup && !(groups[0].groupName === DEFAULT_GROUP_NAME)">
          <a-tabs tab-position="left" v-model="activeTab" @change="scrollToGroup">
            <a-tab-pane
              v-for="(groupsItem, groupsIndex) in groups"
              :tab="groupsItem.groupName"
              :key="groupsIndex"
            ></a-tab-pane>
          </a-tabs>
        </a-col>
        <a-col :span="!inXFormGroup && !(groups[0].groupName === DEFAULT_GROUP_NAME) ? 21 : 24">
          <a-row :gutter="16" type="flex" :key="groupsIndex" v-for="(groupsItem, groupsIndex) in groups">
            <a-col
              :span="24"
              :style="{
                marginTop: groupsIndex === 0 && !inXFormGroup ? '' : '8px',
                fontSize: '14px'
              }"
              v-if="groupsItem.groupName !== DEFAULT_GROUP_NAME"
            >
              <span
                class="xFormGroupTitle"
                :style="{
                  paddingLeft: inXFormGroup ? '14px' : '-5px'
                }"
                :ref="`group-title-${groupsIndex}`"
              >
                {{ groupsItem.groupName }}
              </span>
            </a-col>
            <x-form-item
              v-for="(item, index) in groupsItem.realJsonData"
              :key="index"
              :attr="item"
              :disabled="itemDisabled(item)"
              :read-only="readonly(item)"
              :files="files"
              :signs="signs"
              v-bind="formItemLayoutGen"
              :style="layout === 'inline' ? { marginTop: '5px' } : undefined"
              :form="form"
              :images="images"
              :enablePopupToBody="enablePopupToBody"
              :service-name="serviceName"
              mode="新增/修改"
              :layout="layout"
              :rules="rules[`${item.name}${item.model}`]"
              :get-data-params="getDataParams"
              :env="env"
              @x-form-item-emit-func="emitFunc"
              @rowChoose="rowChoose"
              :setForm="setForm"
            />
          </a-row>
        </a-col>
      </a-row>
      <template v-if="!isSimpleInlineMode">
        <a-row :gutter="16" v-for="(groupItem, groupIndex) in groupJsonData" :key="groupIndex">
          <a-card v-if="groupItem.groupItems.length > 0" :title="groupItem.name" :bordered="false" size="small">
            <x-form-item
              v-for="(item, index) in groupItem.groupItems"
              :key="index"
              :attr="item"
              :disabled="itemDisabled(item)"
              :readonly="readonly(item)"
              :files="files"
              :signs="signs"
              v-bind="formItemLayoutGen"
              :style="layout === 'inline' ? { marginTop: '5px' } : undefined"
              :form="form[groupItem.model]"
              :images="images"
              :service-name="serviceName"
              mode="新增/修改"
              :rules="rules[`${item.name}${item.model}`]"
              :get-data-params="getDataParams"
              :env="env"
              :setForm="setForm"
              @rowChoose="rowChoose"
            />
          </a-card>
          <template v-else>
            <slot
              name="groupFormItems"
              :form="form"
              :model="groupItem.model"
              :rules="rules"
              :modifyModelData="modifyModelData"
            ></slot>
          </template>
        </a-row>
      </template>
      <template v-if="!isSimpleInlineMode">
        <a-row :gutter="16" v-for="(item, key) in simpleFormJsonData" :key="'row' + key">
          <a-card v-if="item.value.length > 0" :title="item.name" :bordered="false" size="small">
            <x-form-item
              v-for="(formItem, formItemIndex) in item.value"
              :key="key + formItemIndex"
              :attr="formItem"
              :disabled="itemDisabled(formItem)"
              :readonly="readonly(formItem)"
              :files="files"
              :signs="signs"
              :enablePopupToBody="enablePopupToBody"
              v-bind="formItemLayoutGen"
              :style="layout === 'inline' ? { marginTop: '5px' } : undefined"
              :form="form[groupItem.model]"
              :images="images"
              :service-name="serviceName"
              mode="新增/修改"
              :rules="rules[`${item.name}${item.model}`]"
              :get-data-params="getDataParams"
              :env="env"
              :setForm="setForm"
              @rowChoose="rowChoose"
            />
          </a-card>
        </a-row>
      </template>
      <template v-for="(item, key) in childTableData">
        <a-row v-if="!childTablePriority" :gutter="16" :key="'childTableRow' + key">
          <a-card :title="item.name" :bordered="false" size="small">
            <x-form-table
              :key="'childTable_' + item.model"
              :title="item.name"
              :queryParamsName="item.childTableConfigName"
              :localEditMode="true"
              @innerXFormTableEmit="innerXFormTableEmit"
              :fixed-query-form="childTableFixedQueryForm(item)"
              :service-name="serviceName"
              @afterTableInit="childTableMounted(item)"
              :ref="'childXFormTable_' + item.model"
            ></x-form-table>
          </a-card>
        </a-row>
      </template>
      <a-row type="flex" :justify="btnPlace" v-if="showSubmitBtn" class="form-footer-row" :style="{ paddingLeft: '16px', paddingRight: '16px' }">
        <slot name="footer" :loading="loading">
          <a-button :loading="loading" type="primary" @click="onSubmit()">
            {{ btnName }}
          </a-button>
        </slot>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import XFormItem from '@vue2-client/base-client/components/common/XForm/XFormItem'
import { formatDate, setDataByRealKey } from '@vue2-client/utils/util'
import * as util from '@vue2-client/utils/util'
import { mapState } from 'vuex'
import { addOrModify, getConfigByName, getConfigByNameAsync, runLogic } from '@vue2-client/services/api/common'
import { checkIdNumber, REG_EMAIL, REG_LANDLINE, REG_PHONE } from '@vue2-client/utils/reg'
import moment from 'moment/moment'
import { executeStrFunction, executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'
import formValidationMixin from '@vue2-client/mixins/formValidationMixin'
import { debounce } from 'lodash'

const DEFAULT_GROUP_NAME = '__default__'
export default {
  name: 'XAddNativeForm',
  components: {
    XFormItem,
    XFormTable: () => import('@vue2-client/base-client/components/common/XFormTable/XFormTable.vue')
  },
  inject: {
    inXFormGroup: {
      default: false
    },
    formGroupContext: {
      default: null
    },
    formDataChange: {
      default: null
    }
  },
  props: {
    // 是否启用 horizontal 模式的自定义配置
    enableHorizontalCustom: {
      type: Boolean,
      default: false
    },
    // 是否启用时间弹出到最外层
    enablePopupToBody: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      DEFAULT_GROUP_NAME,
      // 预览模式
      viewMode: false,
      // 是否处理表单Key值
      isHandleFormKey: true,
      // 内容加载是否完成
      loaded: false,
      // 业务类型
      businessType: '',
      // 业务标题
      title: '',
      // 新增或修改业务是否执行中
      loading: false,
      // 表单Model
      form: {},
      // 配置名称
      configName: undefined,
      // 配置内容，用于查询配置生成器的预览
      configContent: undefined,
      // 表单项集合
      formItems: [],
      // 服务名称
      serviceName: undefined,
      // 是否显示提交按钮
      showSubmitBtn: true,
      // 修改有文件的表单时使用
      files: [],
      images: [],
      // 签名
      signs: [],
      // 校验
      rules: {},
      // 调用logic获取数据源的追加参数
      getDataParams: {},
      // 外部数据（通过 XFormGroup 或直接传入）
      externalData: {},
      // 动态简易表单集合
      simpleFormJsonData: {},
      // 待修改的数据集
      modifyModelData: {},
      // 当前环境
      env: 'prod',
      // 表单主键
      primaryKey: null,
      // 表单模式 horizontal | vertical | inline
      layout: 'horizontal',
      // 提交按钮名称
      btnName: '提交',
      // 提交按钮位置 start / center / end
      btnPlace: 'end',
      // 子表是否排在前面
      childTablePriority: false,
      // simple-inline布局配置
      simpleInline: null,
      // 表单组名称（用于 XFormGroup 场景）
      groupName: null,
      // 是否正在刷新表单项（用于避免死循环）
      isRefreshing: false
    }
  },
  computed: {
    // 过滤出用于新增/修改场景的表单项
    realJsonData: function () {
      return this.formItems.filter(item => {
        return (
          item.addOrEdit &&
          item.addOrEdit !== 'no' &&
          item.addOrEdit !== 'silenceAdd' &&
          item.addOrEdit !== 'version' &&
          !this.itemDisabled(item)
        )
      })
    },
    // 表单项组 / 不是 数据组
    groups: function () {
      if (!this.realJsonData || this.realJsonData.length === 0) {
        return [
          {
            groupName: DEFAULT_GROUP_NAME,
            realJsonData: this.realJsonData,
            xAddFormLayout: 'horizontal'
          }
        ]
      }
      const uniqueGroups = new Set(this.realJsonData.map(item => item.group).filter(Boolean))
      const allGroup = Array.from(uniqueGroups).map(group => {
        return {
          groupName: group,
          realJsonData: this.realJsonData.filter(item => item.group === group),
          xAddFormLayout: 'horizontal'
        }
      })
      // 判断每一组得formJson 长度相加是否等于 realJsonData 长度 避免错误数据
      if (allGroup.reduce((total, item) => total + item.realJsonData.length, 0) === this.realJsonData.length) {
        return allGroup
      } else {
        return [
          {
            groupName: DEFAULT_GROUP_NAME,
            realJsonData: this.realJsonData,
            xAddFormLayout: 'horizontal'
          }
        ]
      }
    },
    // 拥有自定义校验函数得表单项
    customValidateItems: function () {
      return this.formItems.filter(item => {
        return item?.rule?.type === 'customJs'
      })
    },
    // 过滤出用于新增/修改场景的表单项
    groupJsonData: function () {
      return this.formItems
        .filter(item => {
          return item.type === 'group'
        })
        .map(item => {
          item.groupItems = item.groupItems
            .filter(item => {
              return (
                item.addOrEdit &&
                item.addOrEdit !== 'no' &&
                item.addOrEdit !== 'silenceAdd' &&
                item.addOrEdit !== 'version' &&
                !this.itemDisabled(item)
              )
            })
            .map(groupItem => {
              // 只保留第一个下划线后面的内容
              //  多层校验规则需要将prop设置为 key1.key2.....
              groupItem.prop = `${item.model}.${groupItem.model.substring(groupItem.model.indexOf('_') + 1)}`
              groupItem.model = groupItem.model.substring(groupItem.model.indexOf('_') + 1)
              return groupItem
            })
          return item
        })
    },
    // 过滤出用于子表数据新增/修改场景的表单项
    childTableData: function () {
      return this.formItems.filter(item => {
        return item.type === 'childTable'
      })
    },
    // 过滤出用于form子表数据新增/修改场景的表单项
    childFormData: function () {
      return this.formItems.filter(item => {
        return item.type === 'rowEdit'
      })
    },
    // 过滤出用于静默新增场景的表单项
    silenceAddJsonData: function () {
      return this.formItems.filter(function (item) {
        return item.addOrEdit === 'silenceAdd'
      })
    },
    // 过滤出版本号表单项
    versionJsonData: function () {
      return this.formItems.filter(function (item) {
        return item.addOrEdit === 'version'
      })
    },
    formItemLayoutGen() {
      if (this.layout === 'simple-inline') {
        const showLabel = this.simpleInline?.showSimpleInlineLabel === true
        return {
          labelCol: { span: showLabel ? 4 : 0 },
          wrapperCol: { span: showLabel ? 20 : 24 }
        }
      }
      if (this.layout === 'horizontal') {
        // 如果启用了自定义配置，从 formItemLayout 读取（支持 0 值）
        if (this.enableHorizontalCustom && this.formItemLayout) {
          return {
            labelCol: {
              span: this.formItemLayout.labelCol ?? 4,
              offset: this.formItemLayout.offset ?? 2
            },
            wrapperCol: { span: this.formItemLayout.wrapperCol ?? 14 }
          }
        }
        // 默认配置
        return {
          labelCol: { span: 4, offset: 2 },
          wrapperCol: { span: 14 }
        }
      } else if (this.layout === 'vertical') {
        return {}
      } else {
        if (!this.formItemLayout.labelCol || !this.formItemLayout.wrapperCol) {
          return {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 }
          }
        }
        return {
          labelCol: { span: this.formItemLayout.labelCol },
          wrapperCol: { span: this.formItemLayout.wrapperCol }
        }
      }
    },
    // simple-inline模式判断
    isSimpleInlineMode() {
      return this.layout === 'simple-inline' && this.simpleInline
    },
    // simple-inline布局行数据
    simpleInlineRows() {
      if (!this.isSimpleInlineMode) return []
      return this.simpleInline.rows.map(row => ({
        ...row,
        items: row.items
          .map(item => ({
            ...item,
            formItem: this.realJsonData.find(f => f.model === item.key && f.name === item.title)
          }))
          .filter(item => item.formItem)
      }))
    },
    ...mapState('account', { currUser: 'user' })
  },
  provide() {
    return {
      getComponentByName: this.getComponentByName,
      registerComponent: this.registerComponent,
      XFormContext: this,
      // 移除必填项
      removeRequired: this.removeRequired,
      // 设置必填项
      setRequired: this.setRequired,
      getSelf: () => this,
      // 传递 formGroupContext 给子组件
      formGroupContext: this.formGroupContext,
      // 传递外部数据给子组件
      _getExtData: this.getExtData
    }
  },
  watch: {
    form: {
      handler(val) {
        // 如果是 refreshShowFunc 触发的变化，不调用 formDataChange，避免死循环
        if (this.isRefreshing) {
          return
        }
        if (this.formDataChange && typeof this.formDataChange === 'function') {
          // 如果存在 groupName，则传递 groupName 和 formData（用于 XFormGroup 场景）
          if (this.groupName) {
            // 使用防抖避免频繁触发
            if (!this.debouncedFormDataChange) {
              this.debouncedFormDataChange = debounce(() => {
                if (this.formDataChange && typeof this.formDataChange === 'function') {
                  this.formDataChange(this.groupName, this.form)
                }
              }, 150)
            }
            this.debouncedFormDataChange()
          } else {
            // 兼容非 XFormGroup 场景
            this.formDataChange(val)
          }
        }
        // 自定义校验红星：本组 form 变化时更新 tempRequired
        if (this.customValidateItems.length > 0) {
          if (!this.debouncedRunCustomValidation) {
            this.debouncedRunCustomValidation = debounce(() => this.runCustomValidationForDisplay(), 150)
          }
          this.debouncedRunCustomValidation()
        }
      },
      deep: true
    }
  },
  mixins: [formValidationMixin],
  methods: {
    runLogic,
    getConfigByNameAsync,
    getConfigByName,
    init(params) {
      this._configEndEmitted = false
      this._configEndPromise = new Promise(resolve => { this._configEndResolve = resolve })
      const {
        configName,
        configContent,
        formItems,
        formJson,
        viewMode,
        isHandleFormKey,
        isKeyHandle = true,
        showSubmitBtn = true,
        serviceName,
        primaryKey,
        modifyModelData = {},
        businessType,
        title,
        fixedAddForm = {},
        getDataParams = {},
        extData = {},
        simpleFormJsonData = {},
        env = 'prod',
        layout,
        xAddFormLayout = 'horizontal',
        formItemLayout = {},
        btnName = '提交',
        childTablePriority = false,
        btnPlace = 'end',
        simpleInline = null,
        paramLogicName,
        paramLogicServiceName,
        paramLogicNameParam
      } = params
      this.loaded = false
      // 保存表单组名称（用于 XFormGroup 场景）
      this.groupName = params.groupName || null
      // 兼容需要省略 传递 layout: res.xAddFormLayout 可以使用 ...res 展开运算符 直接转递
      if (xAddFormLayout && layout === undefined) {
        this.layout = xAddFormLayout
      } else {
        this.layout = layout
      }
      this.formItemLayout = formItemLayout
      if ((isHandleFormKey === null || isHandleFormKey === undefined) && !isKeyHandle) {
        this.isHandleFormKey = isKeyHandle
      } else if (isHandleFormKey) {
        this.isHandleFormKey = isHandleFormKey
      } else {
        this.isHandleFormKey = isKeyHandle
      }
      this.childTablePriority = childTablePriority
      this.configName = configName
      this.configContent = configContent
      this.formItems = this.getFromItem(formItems, formJson)
      this.viewMode = viewMode
      this.showSubmitBtn = showSubmitBtn
      this.primaryKey = primaryKey
      this.serviceName = serviceName
      this.businessType = businessType
      this.title = title
      this.getDataParams = getDataParams
      this.extData = extData
      this.simpleFormJsonData = simpleFormJsonData
      this.env = env
      this.btnName = btnName
      this.btnPlace = btnPlace
      this.simpleInline = simpleInline
      // 如果 fixedAddForm 有 selected_id 值，并且设置了处理表单key值，则多给 selected_id 加前缀 避免处理错误
      if (fixedAddForm.selected_id && this.isHandleFormKey) {
        fixedAddForm._selected_id = fixedAddForm.selected_id
        delete fixedAddForm.selected_id
      }
      // 设置普通表单项的相关参数
      const formData = Object.assign({}, fixedAddForm)
      if (paramLogicName) {
        // console.warn('2paramLogicServiceName', paramLogicServiceName)
        runLogic(paramLogicName, paramLogicNameParam, (typeof paramLogicServiceName === 'string' && paramLogicServiceName.trim()) || this.serviceName).then(res => {
          Object.assign(formData, res)
        })
      }
      for (let i = 0; i < this.realJsonData.length; i++) {
        const item = this.realJsonData[i]
        this.setFormProps(formData, item, null)
      }
      // 设置表单分组项目相关参数
      for (let i = 0; i < this.groupJsonData.length; i++) {
        const groupItem = this.groupJsonData[i]
        formData[groupItem.model] = {}
        for (let j = 0; j < groupItem.groupItems.length; j++) {
          const item = groupItem.groupItems[j]
          this.setFormProps(formData[groupItem.model], item, item.prop)
        }
      }
      // 设置动态简易表单项的相关参数
      for (const key in this.simpleFormJsonData) {
        for (const item of this.simpleFormJsonData[key].value) {
          item.model = key + '@' + item.model
          this.setFormProps(formData, item, null)
        }
      }

      // 修改场景下对表单项赋值
      this.form = formData
      if (modifyModelData && modifyModelData.data) {
        this.modifyModelData = modifyModelData
        if (Object.keys(modifyModelData.data).length > 0) {
          this.getModifyModelData(modifyModelData)
        }
      }
      // 处理表单得附件
      if (modifyModelData && modifyModelData.files) {
        this.files = modifyModelData.files
      }
      if (modifyModelData && modifyModelData.images) {
        this.images = modifyModelData.images
      }
      if (modifyModelData && modifyModelData.signs) {
        this.signs = modifyModelData.signs
      }
      this.loaded = true
      this._emitConfigEnd()
    },
    /** 配置加载/应用结束后发出，供 XReport 判断「所有 slot 配置结束」；每次 init 仅发出一次 */
    _emitConfigEnd() {
      if (this._configEndEmitted) return
      this._configEndEmitted = true
      if (this._configEndResolve) {
        this._configEndResolve()
        this._configEndResolve = null
      }
      this.$emit('configEnd')
    },
    /**
     * 等待配置结束的异步方法。配置已结束则立即 resolve，否则在 configEnd 时 resolve。
     * @returns {Promise<void>}
     */
    waitConfigEnd() {
      if (this._configEndEmitted) return Promise.resolve()
      return this._configEndPromise || Promise.resolve()
    },
    getExtData() {
      return this.extData
    },
    scrollToGroup(index) {
      const groupElement = this.$refs[`group-title-${index}`][0]
      if (groupElement) {
        groupElement.scrollIntoView({ behavior: 'smooth' })
      }
    },
    registerComponent(componentName, component) {
      console.log('内部注册', this.$options.name, componentName)
      this.$refs[componentName] = component
      console.log('内部注册完成', this.$refs)
    },
    // 根据名字从注册到组件中获取组件
    getComponentByName(componentName) {
      console.log('内部取组件', this.$options.name, componentName)
      console.log('内部组件内容', this.$refs)
      return this.$refs[componentName]
    },
    // 兼容需要省略 传递 [formItems: res.formJson ] 可以使用 ...res 展开运算符 直接转递
    getFromItem(formItems, formJson) {
      const _formItems = formItems || formJson
      if (typeof formItems === 'string') {
        return JSON.parse(_formItems)
      } else {
        return JSON.parse(JSON.stringify(_formItems))
      }
    },
    innerXFormTableEmit(fun, record, id, actionType, index) {
      this.$emit(fun, record, id, actionType, index)
    },
    // 时间组件赋默认值
    // .type, item.formDefault
    getDateRange({ type, formDefault: defaultValue, formValueFormat }) {
      // const format = type === 'datePicker' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'
      let format = 'YYYY-MM-DD HH:mm:ss'
      if (formValueFormat) {
        format = formValueFormat
      }
      let start
      switch (defaultValue) {
        case 'curYear':
          start = moment().startOf('year').format(format)
          break
        case 'curMonth':
          start = moment().startOf('month').format(format)
          break
        case 'curDay':
          start = moment().startOf('day').format(format)
          break
        case 'curTime':
          start = moment().format(format)
          break
        default:
          return defaultValue
      }
      return start
    },
    setFormProps(formData, item, groupItem) {
      const rulesKey = `${item.name}${item.model}`
      if (formData[item.model] === undefined || formData[item.model] === null) {
        formData[item.model] = undefined
      }
      if (!formData[item.model] && item.formDefault) {
        if (
          ['datePicker', 'rangePicker', 'yearPicker', 'monthPicker', 'yearRangePicker', 'monthRangePicker'].includes(
            item.type
          )
        ) {
          formData[item.model] = this.getDateRange(item)
        } else if (
          ['treeSelect', 'select', 'checkbox'].includes(item.type) &&
          ['curOrgId', 'curDepId', 'curUserId'].includes(item.formDefault)
        ) {
          if (item.formDefault === 'curOrgId') {
            formData[item.model] = item.type === 'select' ? this.currUser.orgid : [this.currUser.orgid]
          }
          if (item.formDefault === 'curDepId') {
            formData[item.model] = item.type === 'select' ? this.currUser.depids : [this.currUser.depids]
          }
          if (item.formDefault === 'curUserId') {
            formData[item.model] = item.type === 'select' ? this.currUser.id : [this.currUser.id]
          }
        } else if (['addressSearch'].includes(item.type)) {
          formData[item.model] = item.formDefault
          formData[`${item.model}_lng_lat`] = item.formDefault_lng_lat
        } else {
          formData[item.model] = item.formDefault
        }
      }
      // 处理表单校验情况
      if (item.rule) {
        const rulesArrayKey = groupItem || rulesKey
        this.rules[rulesArrayKey] = []
        const required = item.rule.required ? item.rule.required === true || item.rule.required === 'true' : false
        let trigger
        let message
        if (required) {
          switch (item.type) {
            case 'select':
            case 'checkbox':
            case 'radio':
            case 'treeSelect':
            case 'rangePicker':
            case 'monthPicker':
            case 'yearPicker':
            case 'datePicker':
            case 'file':
            case 'image':
            case 'citySelect':
            case 'addressSearch':
            case 'personSetting':
              message = '请选择' + item.name
              trigger = 'change'
              break
            default:
              message = '请输入' + item.name
              trigger = 'blur'
          }
          this.rules[rulesArrayKey].push({
            required: true,
            message: message,
            trigger: trigger
          })
        }
        // 文件/图片上传最小数量校验：必填时强制校验；非必填但已上传时也需校验
        if (['file', 'image'].includes(item.type) && item.minAcceptCount) {
          const minCount = Number(item.minAcceptCount)
          this.rules[rulesArrayKey].push({
            validator: (rule, value, callback) => {
              const count = Array.isArray(value) ? value.length : value ? 1 : 0
              if ((required || count > 0) && count < minCount) {
                callback(new Error(`请至少上传${minCount}个${item.name}`))
              } else {
                callback()
              }
            },
            trigger: 'change'
          })
        }

        switch (item.rule.type) {
          case 'number':
          case 'integer':
          case 'float':
            // eslint-disable-next-line no-case-declarations
            let defaultValue
            // eslint-disable-next-line no-case-declarations
            let message
            switch (item.rule.type) {
              case 'number':
                item.numberInput = true
                message = '数字'
                defaultValue = 0
                break
              case 'integer':
                item.numberInput = true
                message = '整数'
                defaultValue = 0
                break
              case 'float':
                item.numberInput = true
                message = '小数'
                defaultValue = 0.0
                break
            }
            this.rules[rulesArrayKey].push({
              type: item.rule.type,
              message: item.name + '必须为' + message,
              transform: value => {
                if (value && value.length !== 0) {
                  return Number(value)
                } else {
                  return defaultValue
                }
              },
              trigger: 'blur'
            })
            break
          case 'email': {
            const validator = (rule, value, callback) => {
              if (value && !REG_EMAIL.test(value)) {
                callback(new Error('请输入正确的邮箱地址'))
              } else {
                callback()
              }
            }
            this.rules[rulesArrayKey].push({
              type: 'email',
              validator: validator,
              message: '请输入正确的邮箱地址',
              trigger: 'blur'
            })
            break
          }
          case 'userPhone': {
            this.rules[rulesArrayKey].push({
              type: 'userPhone',
              validator: (rule, value, callback) => {
                if (value && !REG_PHONE.test(value)) {
                  callback(new Error('请输入正确的手机号码'))
                } else {
                  callback()
                }
              },
              message: '请输入正确的手机号码',
              trigger: 'blur'
            })
            break
          }
          case 'idNumber': {
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                if (value && !checkIdNumber(value)) {
                  callback(new Error('请输入正确的身份证号码'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            })
            break
          }
          case 'landlineNumber': {
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                if (value && !REG_LANDLINE.test(value)) {
                  callback(new Error('请输入正确的座机号码'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            })
            break
          }
          // 大于0
          case 'greaterThanZero': {
            item.numberInput = true
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                if (isNaN(value) || value <= 0) {
                  callback(new Error('请输入一个大于0的数字'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            })
            break
          }
          // 大于等于0
          case 'greaterThanOrEqualZero': {
            item.numberInput = true
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                if (isNaN(value) || value < 0) {
                  callback(new Error('请输入一个大于等于0的数字'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            })
            break
          }
          case 'stringLength': {
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                if (value && value.length < item.rule.minLen) {
                  callback(new Error('长度不能少于' + item.rule.minLen + '个字符'))
                } else if (value && value.length > item.rule.maxLen) {
                  callback(new Error('长度不能超过' + item.rule.maxLen + '个字符'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            })
            break
          }
          case 'customJs': {
            this.rules[rulesArrayKey].push({
              validator: (rule, value, callback) => {
                this.customJsValidate(rule, value, callback, item)
              },
              trigger: 'blur'
            })
            break
          }
        }
      }
    },
    childTableMounted(item) {
      // 子表初始化时，设置表格数据
      if (this.form[item.model] && this.form[item.model].length > 0) {
        this.$refs[`childXFormTable_${item.model}`][0].setTableData(this.form[item.model])
      }
    },
    customJsValidate(rule, value, callback, item) {
      if (item.rule.customValidatorFunc) {
        executeStrFunctionByContext(this, item.rule.customValidatorFunc, [
          rule,
          value,
          callback,
          this.form,
          item,
          this.util,
          runLogic,
          getConfigByNameAsync
        ])
      } else {
        callback()
      }
    },
    /**
     * 根据自定义校验函数更新表单项红星状态（tempRequired）及校验规则
     * 支持两种触发：1) 本组 form 变化时由 watch 调用  2) 他组变化时由 refreshShowFunc 调用
     * XFormGroup 场景下，自定义校验函数可通过 this.formGroupContext.allFormData 获取全部表单数据
     */
    runCustomValidationForDisplay() {
      if (!this.customValidateItems || this.customValidateItems.length === 0) return
      for (const item of this.customValidateItems) {
        const itemIndex = this.formItems.findIndex(formItem => formItem.model === item.model)
        if (itemIndex < 0) continue
        try {
          this.customJsValidate(null, this.form[item.model], res => {
            this.$set(this.formItems[itemIndex], 'tempRequired', res instanceof Error)
          }, item)
        } catch (e) {
          console.error('[XAddNativeForm] runCustomValidationForDisplay:', e)
          this.$set(this.formItems[itemIndex], 'tempRequired', true)
        }
      }
    },
    itemDisabled(value) {
      return (
        (this.businessType === '新增' && value.addOrEdit === 'edit') ||
        (this.businessType === '修改' && value.addOrEdit === 'add')
      )
    },
    readonly(value) {
      return value.addOrEdit === 'readonly'
    },
    async onSubmit() {
      const valid = await this.validateForm()
      if (!valid) return false
      if (this.viewMode) {
        this.$message.info('预览模式禁止新增和修改')
        return false
      }
      this.loading = true
      const requestForm = this.prepareForm()
      await this.appendSilenceAddFields(requestForm)
      const realForm = this.handleFormKeys(requestForm)
      // 增加子表数据
      if (this.childTableData.length > 0) {
        for (const item of this.childTableData) {
          const childModel = item.model
          const childDataRef = this.$refs['childXFormTable_' + item.model][0].getTableData()
          const childData = []
          for (const item of childDataRef) {
            childData.push(JSON.parse(JSON.stringify(item)))
          }
          for (let i = 0; i < childData.length; i++) {
            childData[i] = this.handleFormKeys(childData[i])
            // 外键不需要带表别名，所以此处放到表单处理后赋值
            if (realForm.id) {
              childData[i][item.childTableForeignKeyName] = realForm.id
            }
          }
          realForm[childModel] = childData
        }
      }
      // 增加form子表数据
      if (this.childFormData.length > 0) {
        for (const item of this.childFormData) {
          const childModel = item.model
          const childData = this.$refs[item.model].getTableData()
          for (let i = 0; i < childData.length; i++) {
            childData[i] = this.handleFormKeys(childData[i], true)
            // 外键不需要带表别名，所以此处放到表单处理后赋值
            if (realForm.id) {
              childData[i][item.foreignKey] = realForm.id
            }
          }
          realForm[childModel] = childData
        }
      }
      if (this.$listeners.onSubmit) {
        // 交由父级处理
        this.$emit('onSubmit', {
          businessType: this.businessType,
          serviceName: this.serviceName,
          realForm: realForm,
          currUserName: this.currUser.name,
          currUserId: this.currUser.id,
          orgId: this.currUser.orgid
        })
      } else {
        this.defaultSubmit(realForm)
      }
    },

    async asyncSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs.selectForm.validate(async valid => {
          if (!valid) {
            reject(new Error('Form validation failed'))
            return
          }
          this.loading = true
          const requestForm = this.prepareForm()
          await this.appendSilenceAddFields(requestForm)
          const realForm = this.handleFormKeys(requestForm)
          resolve({
            realForm,
            businessType: this.businessType,
            serviceName: this.serviceName,
            currUserName: this.currUser.name,
            currUserId: this.currUser.id,
            orgId: this.currUser.orgid
          })
        })
      })
    },

    validateForm() {
      return new Promise(resolve => {
        this.$refs.selectForm.validate(valid => resolve(valid))
      })
    },

    childTableFixedQueryForm(item) {
      if (this.modifyModelData?.primaryKeyData) {
        const fixedForm = {}
        fixedForm[item.childTableForeignKeyName] = Object.values(this.modifyModelData.primaryKeyData)[0]
        return fixedForm
      }
      return null
    },

    prepareForm() {
      const form = { ...this.form }
      for (const key of Object.keys(form)) {
        const value = form[key]
        if (value === null || (typeof value === 'object' && Object.keys(value).length === 0)) {
          form[key] = undefined
        }
      }
      return form
    },

    async appendSilenceAddFields(form) {
      if (this.businessType === '新增') {
        for (const item of this.silenceAddJsonData) {
          switch (item.silencePurpose) {
            case 'createTime':
              form[item.model] = formatDate('now')
              break
            case 'operator':
              form[item.model] = this.currUser.name
              break
            case 'operatorId':
              form[item.model] = this.currUser.id
              break
            case 'orgId':
              form[item.model] = this.currUser.orgid
              break
            case 'orgName':
              form[item.model] = this.currUser.orgs
              break
            case 'depId':
              form[item.model] = this.currUser.depids
              break
            case 'depName':
              form[item.model] = this.currUser.deps
              break
          }
        }
        for (const item of this.silenceAddJsonData.filter(item => item.silencePurpose === 'customize')) {
          const result = await runLogic(item.silenceSource, form, this.serviceName)
          if (result) {
            const keys = Object.keys(result)
            if (keys.length === 1 && keys[0] === 'value') {
              form[item.model] = result.value
            } else {
              form[item.model] = result
            }
          } else {
            form[item.model] = result
          }
        }
      }
    },

    handleFormKeys(form, mustHandleKey = false) {
      const realForm = {}
      for (const key of Object.keys(form)) {
        const value = form[key]
        const extraFormKeyTagIndex = key.indexOf('@')
        if (extraFormKeyTagIndex !== -1) {
          const extraFormKey = key.substring(0, extraFormKeyTagIndex)
          const realKey = key.substring(extraFormKeyTagIndex + 1)
          if (!realForm[extraFormKey]) {
            realForm[extraFormKey] = {}
          }
          realForm[extraFormKey][realKey] = value
        } else {
          const realKey = this.isHandleFormKey || mustHandleKey ? this.getRealKey(key, mustHandleKey) : key
          // 如果发生重名，不覆盖，把key的别名带上
          if (realForm[realKey]) {
            realForm[key] = value
          } else {
            realForm[realKey] = value
          }
        }
      }
      return realForm
    },
    // 默认提交事件
    defaultSubmit(realForm, callback) {
      // 新增移除id
      if (this.businessType === '新增') {
        delete realForm.id
      }
      // 组织请求
      const requestParameters = {
        queryParamsName: this.configName,
        queryParams: this.configContent,
        form: realForm,
        businessType: this.businessType,
        operator: this.currUser.name
      }
      addOrModify(requestParameters, this.serviceName, this.env === 'dev')
        .then(data => {
          this.$message.success(this.businessType + '成功！')
          // commit
          this.$emit('afterSubmit', {
            type: this.businessType,
            id: data.id,
            data: data,
            form: requestParameters.form
          })
          this.loading = false
          if (callback) {
            callback()
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.error(this.businessType + '失败：' + e)
        })
    },
    // 获取表单字段实际值
    getRealKey(key, mustHandleKey = false) {
      if (key === 'selected_id') return key
      if (this.isHandleFormKey || mustHandleKey) {
        return key.substring(key.indexOf('_') + 1)
      } else {
        return key
      }
    },
    /**
     * 获取被修改记录数据
     * @param modifyModelData 被修改记录的数据
     */
    getModifyModelData(modifyModelData) {
      if (modifyModelData.primaryKeyData) {
        this.form = Object.assign(this.form, modifyModelData.primaryKeyData)
      }
      // 对动态简易表单项特殊处理
      for (const key in modifyModelData.data) {
        const realKey = this.isHandleFormKey ? this.getRealKey(key) : key
        if (this.simpleFormJsonData[realKey]) {
          const extraForm = JSON.parse(modifyModelData.data[key])
          for (const key in extraForm) {
            const model = realKey + '@' + key
            this.form[model] = extraForm[key]
          }
        }
      }
      // 对普通表单项处理
      for (let i = 0; i < this.realJsonData.length; i++) {
        if (['FilesId', 'Images'].includes(this.realJsonData[i])) {
          // 附件需要跳过 因为会通过 modifyModelData中的files,images属性给upload赋值
          // 新增修改表单每次提交时只会提交最新添加的文件
          continue
        }
        const item = this.realJsonData[i]
        // 地址选择器 需要传递 经纬度字段, 配置中添加 `${item.model}_lng_lat` CRUD 只需勾选 SQL生成查询项
        if (['addressSearch'].includes(item.type)) {
          this.form[item.model] = modifyModelData.data[item.model] + ''
          this.form[`${item.model}_lng_lat`] = modifyModelData.data[`${item.model}_lng_lat`] + ''
          continue
        }
        if (modifyModelData.data[item.model] || modifyModelData.data[item.model] === 0) {
          if (modifyModelData.data[item.model] instanceof Array) {
            this.form[item.model] = modifyModelData.data[item.model]
          } else {
            this.form[item.model] = modifyModelData.data[item.model] + ''
          }
        }
      }
      // 对分组表单进行处理
      for (let i = 0; i < this.groupJsonData.length; i++) {
        const item = this.groupJsonData[i]
        try {
          if (modifyModelData.data[item.model]) {
            this.form[item.model] = JSON.parse(modifyModelData.data[item.model])
          }
        } catch (e) {
          if (modifyModelData.data[item.model]) {
            this.form[item.model] = modifyModelData.data[item.model]
          }
        }
      }
      // 追加版本号信息
      for (const item of this.versionJsonData) {
        if (!modifyModelData.data[item.model]) {
          this.form[item.model] = 0
        } else {
          this.form[item.model] = modifyModelData.data[item.model] + ''
        }
      }
    },
    setForm(obj) {
      this.form = Object.assign(this.form, obj)
      // 给子表赋外键条件
      if (this.childFormData.length > 0) {
        for (const item of this.childFormData) {
          const child = this.$refs[item.model]
          // 获取子表别名，以便在条件上添加别名
          const alias = child.realQueryConfig.tableAliasName
          // 有主键，且主键有值，添加主键条件
          if (this.primaryKey && this.form[this.primaryKey]) {
            const foreignKey = item.foreignKey
            const fixedQueryForm = {
              [alias + '_' + foreignKey]: this.form[this.primaryKey]
            }
            if (!child.fixedQueryForm) {
              child.fixedQueryForm = fixedQueryForm
            } else {
              Object.assign(child.fixedQueryForm, fixedQueryForm)
            }
            child.refreshTable()
          }
        }
      }
    },
    setFormWithKey(obj) {
      setDataByRealKey(this.form, obj)
    },
    setFormWithNoKey(obj) {
      setDataByRealKey(this.form, obj)
    },
    emitFunc(func, data, value) {
      this.$emit(func, data, value)
      this.$emit('x-form-item-emit-func', func, data, value)
    },
    // 直接转发事件的函数
    emitEvent(event, ...args) {
      this.$emit(event, ...args)
    },
    close() {
      this.loaded = false
    },
    /**
     * 行选择事件
     * @param row 选中行集合
     * @param attr 表单项属性
     */
    async rowChoose(row, attr, callback) {
      // 如果配置了自定义函数
      if (attr.dataChangeFunc) {
        await executeStrFunction(attr.dataChangeFunc, [
          this.form,
          this.setForm,
          {
            ...attr,
            selectRows: row
          },
          util,
          this.mode,
          runLogic,
          getConfigByNameAsync
        ])
      } else {
        // 默认填充选中行数据到当前表单
        setDataByRealKey(this.form, row[0])
      }
      if (callback) {
        callback()
      }
    },
    /**
     * 刷新表单项展示函数
     * 通过修改 form 并添加时间戳来触发 watch form，从而自动触发 showFormItemFunc 重新计算
     * 他组数据变化时由 XFormGroup.handleFormDataChange 调用，此时 allFormData 已更新
     */
    refreshShowFunc() {
      // 自定义校验红星：他组变化时更新 tempRequired（可访问 formGroupContext.allFormData）
      if (this.customValidateItems && this.customValidateItems.length > 0) {
        this.runCustomValidationForDisplay()
      }
      // 设置标志位，避免触发 formDataChange 导致死循环
      this.isRefreshing = true
      // 修改 form 中的时间戳字段，触发 watch form，从而自动触发 showFormItemFunc
      this.$set(this.form, '__refreshTimestamp__', Date.now())
      // 在下一个 tick 重置标志位
      this.$nextTick(() => {
        this.isRefreshing = false
      })
    }
  }
}
</script>

<style scoped lang="less">
:deep(.ant-form-inline .ant-form-item) {
  display: block !important;
}

:deep(.ant-form-item-with-help) {
  margin-bottom: 0;
}

.xFormGroupTitle {
  font-weight: bold;
  color: @primary-color;
}

.simple-inline-item {
  max-width: 100% !important;
}

/* simple-inline模式样式 - 需要穿透 x-form-col 组件 */
/* DOM结构: x-form-item.simple-inline-item > slot > x-form-col > a-col > .x-form-col-wrapper > .ant-form-item */
:deep(.simple-inline-item > .x-form-col-wrapper .ant-form-item),
:deep(.simple-inline-item .x-form-col-wrapper .ant-form-item) {
  margin: 0 !important;
  padding: 2px !important;

  > .ant-form-item-label {
    width: 0 !important;
    min-width: 0 !important;
    max-width: 0 !important;
    padding: 0 !important;
    overflow: hidden;
    display: none !important;
  }

  > .ant-form-item-control-wrapper,
  > .ant-form-item-control {
    width: 100% !important;
  }
}

/* simple-inline模式下显示label - 左右结构布局 */
/* simple-inline模式下显示label - 左右结构布局 */
:deep(.simple-inline-item.show-label .x-form-col-wrapper .ant-form-item) {
  display: flex !important;  // 添加这一行
  flex-direction: row !important;  // 确保是行布局
  align-items: flex-start !important;  // 顶部对齐

  > .ant-form-item-label {
    width: auto !important;
    min-width: 80px !important;
    max-width: 120px !important;
    padding: 0 8px 0 0 !important;
    overflow: visible;
    display: flex !important;
    align-items: center;
    flex-shrink: 0;

    label {
      height: 39px;
      line-height: 39px;
      font-size: 16px;
      color: #313131;
      white-space: nowrap;
      margin: 0;
    }

    label::after {
      content: '';
    }
  }

  > .ant-form-item-control-wrapper {
    flex: 1;
    min-width: 0;
    width: auto !important;  // 覆盖原有的固定宽度
  }

  > .ant-form-item-control {
    display: flex;
    align-items: center;
    width: 100%;

    // 各种输入框样式保持不变
    .ant-input,
    .ant-input-affix-wrapper,
    .ant-select .ant-select-selector,
    .ant-input-number .ant-input-number-input,
    .ant-picker {
      border-radius: 6px;
      border: 1px solid #E5E9F0;
      line-height: 39px;
      height: 39px;
      box-sizing: border-box;
      width: 100%;
    }

    .ant-select .ant-select-selector {
      height: 39px !important;
      .ant-select-selection-item {
        line-height: 39px !important;
      }
    }
  }
}
/* 表单底部按钮区域样式 */
.form-footer-row {
  margin-top: 16px;

  :deep(.ant-btn) {
    margin-left: 8px;

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
