<template>
  <a-form :colon="false" class="form-container">
    <a-row :gutter="[6, 0]" justify="start">
      <template v-for="(field, index) in fileGroups" :key="'file-item-' + index">
        <!-- <template v-if="modelData.data && showLogical(field)"> -->
        <template v-if="modelData.data && logicStates.get(field.fieldName + '_showLogical')">
          <a-col
            v-if="field.visible" :span="getColSpan(field)"
            :class="['fixed-width-col', { 'single-row': shouldSingleRow(field) }]"
          >
            <a-form-item
              :label-col="{ style: 'width: 120px' }" :wrapper-col="{ style: 'width: 230px' }"
              class="fixed-form-item"
            >
              <template #label>
                <a-tooltip placement="right" :title="Language.getDisplayNameTrl($i18n.locale, field)">
                  <div class="custom-label" :class="{ 'rowWidth': !multipleColumn }">
                    <span class="label-text">
                      <span v-if="field.mandatory" class="required-mark">*</span>
                      {{ Language.getDisplayNameTrl($i18n.locale, field) }}
                      <span v-if="isChineseEnglish && $i18n.locale == 'zh-CN'" class="english-name">
                        {{ field.displayNameEng }}
                      </span>
                    </span>
                  </div>
                </a-tooltip>
              </template>

              <!-- 通用文本类型 -->
              <a-typography-text v-if="isBasicType(field)" class="field-content">
                <a-tooltip placement="left" :title="getFieldStringValue(field)">
                  {{ getFieldStringValue(field) }}
                </a-tooltip>
              </a-typography-text>

              <!-- 数字类型 -->
              <a-typography-text v-else-if="fieldUtil.isNumberType(field)" class="field-content">
                {{ getFieldNumberValue(field) }}
              </a-typography-text>

              <!-- 富文本类型 :style="field.cssStyle" todo -->
              <a-typography-text v-else-if="fieldUtil.isRichTextAreaEditor(field)" class="rich-text-content">
                <div class="rich-text-wrapper">
                  {{ getFieldStringValue(field) }}
                </div>
              </a-typography-text>

              <!-- 文本域类型 -->
              <a-tooltip
                v-else-if="fieldUtil.isTextAreaType(field)" placement="left"
                :title="getFieldStringValue(field)"
              >
                <a-typography-text class="text-area-content">
                  {{ getFieldStringValue(field) }}
                </a-typography-text>
              </a-tooltip>

              <!-- 多选集合类型 -->
              <a-space v-else-if="fieldUtil.isManyToManySetType(field)" wrap class="multi-select-group">
                <a-tag v-for="item in getManyToManyValues(field)" :key="item" class="multi-tag">
                  {{ item }}
                </a-tag>
              </a-space>

              <!-- 复选框类型 -->
              <a-typography-text v-else-if="fieldUtil.isCheckBoxType(field)" class="field-content">
                {{ getFieldStringValue(field) === "true" ? $t("lang.TabFormFieldView.yes") :
                  $t("lang.TabFormFieldView.no")
                }}
              </a-typography-text>

              <!-- 红绿单类型 -->
              <a-typography-text v-else-if="fieldUtil.isRedGreenEditorType(field)">
                {{ getFieldStringValue(field) == "true" ? "红单" : "蓝单" }}
              </a-typography-text>

              <!-- 枚举单选类型 -->
              <a-typography-text v-else-if="fieldUtil.isEnumListType(field)" class="enum-text-content">
                {{ getEnumDisplayValue(field) }}
              </a-typography-text>

              <!-- 枚举多选类型 -->
              <a-typography-text v-else-if="fieldUtil.isEnumMultiType(field)" class="enum-text-content">
                {{ getMultiEnumValue(field) }}
              </a-typography-text>

              <!-- 图片类型 -->
              <ImageViewWidget
                v-else-if="fieldUtil.isImageType(field)" :field="field"
                :field-value="getFieldValue(field)" :class-name="className"
              />

              <!-- 图片列表类型 -->
              <ImageListViewWidget
                v-else-if="fieldUtil.isImageListType(field)" :field="field"
                :field-value="getFieldValue(field)" :class-name="className"
              />

              <!-- 视频类型 -->
              <VideoListWidget
                v-if="fieldUtil.isVideoType(field)" :field="field" :field-value="getFieldValue(field)"
                :class-name="className" :readonly="readOnly(field)"
              />

              <!-- 文件类型 -->
              <FileListWidget
                v-else-if="fieldUtil.isFileType(field)" :field="field" :field-value="getFieldValue(field)"
                :class-name="className" :readonly="true"
              />

              <!-- 按钮类型 -->
              <div v-if="fieldUtil.isButtonType(field)" style="display: inline-block">
                <ButtonWidget
                  :field="field" :readonly="readOnly(field)" :field-value="getFieldValue(field)"
                  @execute-callout="executeCallout(field)"
                />
              </div>

              <!-- 按钮组 -->
              <a-space v-else-if="fieldUtil.isGridButtonEditor(field)" wrap class="button-group">
                <template v-for="(btn, btnIndex) in field.tabFormButtonDtos" :key="btn.name">
                  <template v-if="visible[btnIndex]">
                    <a-button v-if="btn.action === 'ABANDON'" danger @click="triggerButton(btn)">
                      {{ btn.name }}
                    </a-button>
                    <a-button v-else type="link" @click="triggerButton(btn)">
                      {{ btn.name }}
                    </a-button>
                  </template>
                </template>
              </a-space>
            </a-form-item>
          </a-col>
        </template>
      </template>
    </a-row>
  </a-form>
</template>

<script>
import {
  ref,
  defineAsyncComponent,
} from 'vue';
import fieldUtil from '../../resource/dictionary/FieldUtil.js';
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import Language from '../../common/Language.js';
import Context from '../common/Context.js';
import { Spin as ASpin, Empty as AEmpty, message } from 'ant-design-vue';
import EnumSelectWidget from '../tabFormWidget/EnumSelectWidget.vue';
import SelectWidget from '../tabFormWidget/SelectWidget.vue';
import EnumRadioGroupWidget from '../tabFormWidget/EnumRadioGroupWidget.vue';
import VideoListWidget from '../tabFormWidget/VideoListWidget.vue';
import FileListWidget from '../tabFormWidget/FileListWidget.vue';
import ButtonWidget from '../tabFormWidget/ButtonWidget.vue';

import ImageViewWidget from '../tabFormWidget/ImageViewWidget.vue';
import ImageListViewWidget from '../tabFormWidget/ImageListViewWidget.vue';
import JsUtil from '../../common/JsUtil.js';
import { SqlApi } from 'pc-component-v3';
import { Notify, Uuid, CssUtil } from 'pc-component-v3';
import Common from '../../common/Common.js';
import CustomerWindowResource from '../../api/dic/CustomerWindowResource.js';
import HtmlWindowResource from '../../api/dic/HtmlWindowResource.js';
import ProcessReportResource from '../../api/dic/ProcessReportResource.js';
export default {
  components: {
    ImageViewWidget,
    ImageListViewWidget,
    EnumSelectWidget,
    SelectWidget,
    EnumRadioGroupWidget,
    VideoListWidget,
    FileListWidget,
    ButtonWidget,
    Common,
    CustomerWindowResource,
    HtmlWindowResource,
    ProcessReportResource,
  },
  props: {
    className: {
      type: String,
      required: true,
    },
    fileGroups: {
      type: Array,
      required: true,
    },
    modelData: {
      type: Object,
      required: true,
    },
    isChineseEnglish: {
      type: Boolean,
      default: null,
    },
    jsUrl: {
      type: String,
      default: null,
    },
    multipleColumn: {
      type: Boolean,
      default: null,
    },
  },
  emits: ['executeCallout', 'refreshDatas', 'getModelData', 'abandonWorkflow'],

  data() {
    return {
      Language,
      fieldUtil,
      tabButtonModel: null,
      visible: [],
      modal1Open: false,
      modal1Component: null,
      logicStates: new Map(),
    };
  },
  watch: {

    'modelData.data': {
      deep: true,
      immediate: true,
      handler(newData) {
        if (newData) {
          this.fileGroups.forEach(field => {
            this.$nextTick(() => {
              this.showLogical(field); // 主动触发逻辑计算
            });
          });
        }
      },
    },

    // 监听按钮组数据变化
    'fileGroups': {
      deep: true,
      immediate: true,
      handler(newGroups) {
        this.visible = [];
        newGroups.forEach(field => {
          if (field?.tabFormButtonDtos) {
            field.tabFormButtonDtos.forEach(() => {
              this.visible.push(true);
            });
          }
        });
        // this.logicStates.clear();
      },
    },
  },
  // 在组件销毁时清理缓存
  beforeUnmount() {
    this.logicStates.clear();
  },

  methods: {
    /**
     * 获取Context
     */
    getContext: Context,

    // 判断是否单行显示
    shouldSingleRow(field) {
      return field.singleRow || !this.multipleColumn;
    },

    // 动态计算列宽
    getColSpan(field) {
      if (this.shouldSingleRow(field)) {
        return 24; // 单行显示时占满24列
      }
      return this.multipleColumn ? undefined : 24;
    },

    // 判断是否是基础类型
    isBasicType(field) {
      const excludedTypes = [
        fieldUtil.isManyToManySetType(field),
        fieldUtil.isImageType(field),
        fieldUtil.isImageListType(field),
        fieldUtil.isCheckBoxType(field),
        fieldUtil.isRedGreenEditorType(field),
        fieldUtil.isVideoType(field),
        fieldUtil.isEnumMultiType(field),
        fieldUtil.isEnumListType(field),
        fieldUtil.isTextAreaType(field),
        fieldUtil.isFileType(field),
        fieldUtil.isRichTextAreaEditor(field),
        fieldUtil.isNumberType(field),
        fieldUtil.isButtonType(field),
        fieldUtil.isGridButtonEditor(field),
      ];
      return !excludedTypes.some(result => result);
    },

    // 获取枚举单选框的值
    getEnumValue: function (field) {
      const fieldValue = this.getFieldValue(field);
      var result;
      if (fieldValue != undefined && fieldValue.displayValue != undefined) {
        var value0 = fieldValue.displayValue[0];
        if (field != null && field.keyValues != null) {
          field.keyValues.forEach(function (item1) {
            if (value0 == item1.keyStr) {
              result = item1.value;
            }
          });
        }
      }
      return result;
    },

    // 获取枚举显示值
    getEnumDisplayValue: function (field) {
      const value = this.getEnumValue(field);
      const mappings = {
        '编辑中': this.$t('lang.TabFormFieldView.editing'),
        '审批中': this.$t('lang.TabFormFieldView.pendingApproval'),
        '审批通过': this.$t('lang.TabFormFieldView.approved'),
        '审批不通过': this.$t('lang.TabFormFieldView.rejected'),
        '单据已撤回': this.$t('lang.TabFormFieldView.withdraw'),
        '转移': this.$t('lang.TabFormFieldView.transfer'),
        '报废': this.$t('lang.TabFormFieldView.disposal'),
        '全盘': this.$t('lang.TabFormFieldView.overall'),
        '抽盘': this.$t('lang.TabFormFieldView.randomInventory'),
      };
      return mappings[value] || value;
    },

    // 获取枚举多选显示值
    getMultiEnumValue: function (field) {
      const fieldValue = this.getFieldValue(field);
      var result = [];
      if (fieldValue != undefined && fieldValue.displayValue != undefined && fieldValue.displayValue[0] != undefined) {
        var arr = fieldValue.displayValue[0].split(',');
        arr.forEach(function (item) {
          field.keyValues.forEach(function (item1) {
            if (item == item1.keyStr) {
              result.push(item1.value + ' ');
            }
          });
        });
      }
      return result.join(',');
    },

    // 获取字段值
    getFieldValue: function (field) {
      return this.modelData.data == undefined ? [] : this.modelData.data[field.fieldName];
    },

    // 获取String字符串
    getFieldStringValue: function (field) {
      var value = '';
      const fieldValue = this.getFieldValue(field);
      if (
        fieldValue == undefined ||
        fieldValue.displayValue == undefined ||
        fieldValue.displayValue.length < field.entityFieldIndex
      ) {
        return '';
      } else {
        value = fieldUtil.formatNumbers(
          fieldValue.displayValue[field.entityFieldIndex],
          field.pattern,
          field.displayType,
        );
        return value;
      }
    },

    // 获取Number类型字段值
    getFieldNumberValue: function (field) {
      const fieldValue = this.getFieldValue(field);
      if (
        fieldValue == undefined ||
        fieldValue.displayValue == undefined ||
        fieldValue.displayValue.length < field.entityFieldIndex
      ) {
        return '';
      } else {
        return fieldValue.displayValue[field.entityFieldIndex];
      }
    },

    // 获取ManyToManySetType值
    getManyToManyValues: function (field) {
      const fieldValue = this.getFieldValue(field);
      if (
        fieldValue == undefined ||
        fieldValue.displayValue == undefined ||
        fieldValue.displayValue.length < field.index
      ) {
        return [];
      } else {
        return fieldValue.displayValue;
      }
    },

    /**
     * 执行Callout
     */
    executeCallout: function (field) {
      this.$emit('executeCallout', field);
    },
    refreshDatas: function () {
      this.$emit('refreshDatas');
    },
    // 弃审
    abandon: function () {
      this.$emit('abandonWorkflow');
    },
    // 获取modelData
    getEditModelData: function () {
      this.$emit('getModelData', true);
    },
    // 刷新modelData
    refreshEditData: function () {
      window.refreshCurdDatas = this.refreshDatas;
    },
    /**
     * 打开新界面编辑
     * @param tabButton 
     */
    openNewViewEdit: function (tabButton) {
      const _self = this;
      //打开新界面编辑Url
      var openNewViewEditUrl = tabButton.openNewViewEditUrl;
      if (!openNewViewEditUrl) {
        message.warning('未定义打开界面地址，请您先定义。');
        return;
      }
      _self.refreshEditData(); // 将刷新方法放入window中
      _self.getEditModelData(); // 将modelData放入window中
      window.viewEditDatas.isViewEdit = false; // 需要通过modelData来保存的标识
      const url = Common.getRootPath() + openNewViewEditUrl;
      window.open(url, '_blank');
    },

    // 触发按钮
    triggerButton: function (btn) {
      if (btn.action === 'RUN_PROCESS_REPORT' || btn.action === 'OPEN_CUSTOMER_WINDOW' || btn.action === 'OPEN_CUSTOMER_WINDOW' || btn.action === 'OPEN_HTML_WINDOW') {
        this.execute(btn);
      } else if (btn.action === 'OPEN_REMOTE_COMPONENT_MODULE_IN_MODAL') {
        this.openRemoteComponentModule(btn);
      } else if (btn.action === 'OPEN_NEW_VIEW_EDIT') {
        this.openNewViewEdit(btn);
      } else if (btn.action === 'ABANDON') {
        this.abandon();
      } else if (btn.action === 'EDIT') {
        console.log('编辑');
      }
    },

    //跳转或执行流程
    execute: function (tabButton) {
      var _self = this;
      _self.tabButtonModel = tabButton;
      if (tabButton.customerWindowNo != undefined && tabButton.customerWindowNo != '') {
        CustomerWindowResource.uniqueByNo(tabButton.customerWindowNo).then(
          successData => {
            if (successData.errorCode == 0) {
              tabButton.customerWindowRouteUrl = successData.data.routeUrl;
              if (tabButton.customerWindowNo == '20221101_151823') {
                localStorage.setItem('AssetInstance_ComplexFilterParams', JSON.stringify(_self.complexFilterParams));
                localStorage.setItem('AssetInstance_SimpleFilterParams', _self.simpleFilterParams);
              }
              //跳转到tabButton.routeUrl
              _self.switchFormRoute(tabButton);
            } else {
              Notify.error(_self.$t('lang.Notify.error'), successData.errorMessage, true);
            }

          },
          errorData => {
            Common.processException(errorData);
          },
        );
      } else if (
        tabButton.processReportNo != undefined &&
        tabButton.processReportNo != ''
      ) {
        // 判断流程报表是否有参数
        // 如果有参数则直接跳转到流程和报表的界面。
        if (tabButton.routerRedirect == undefined || tabButton.routerRedirect == false) {
          if (tabButton.tipsTitle == undefined || tabButton.tipsTitle.length == 0) {
            _self.executeProcess();
          } else {
            _self.titleModal = true;
          }
        } else {
          this.$router.push({
            path: '/desktop/process-report/' + tabButton.processReportNo,
          });
        }
      } else if (tabButton.htmlWindowNo != undefined) {
        HtmlWindowResource.uniqueByNo(tabButton.htmlWindowNo).then(
          response => {
            if (response.errorCode != 0) {
              Notify.error(_self.$t('lang.Notify.dataDictionaryError'), response.errorMessage, true);
              return;
            }

            const htmlWindowDto = response.data;
            if (htmlWindowDto != undefined) {
              var htmlWindowUrl = htmlWindowDto.htmlFileName;
              var autoCloseInterval = htmlWindowDto.autoCloseInterval;
              var regExp = new RegExp('[{].*?[}]', 'g');
              var result = htmlWindowUrl.match(regExp);
              if (htmlWindowUrl != undefined && htmlWindowUrl != '') {
                for (var index = 0, len = result.length; index < len; index++) {
                  var tempResult = result[index];
                  console.log('{' + tempResult + '}匹配');
                  if (tempResult == '{URL}') {
                    htmlWindowUrl = htmlWindowUrl.replace(
                      '{URL}',
                      Common.getHostPageBaseURL(),
                    );
                  } else if (tempResult == '{RecordIds}') {
                    var recordId = _self.modelData.id;
                    htmlWindowUrl = htmlWindowUrl.replace('{RecordIds}', recordId);
                  } else if (tempResult == '{Token}') {
                    htmlWindowUrl = htmlWindowUrl.replace('{Token}', Common.getToken());
                  } else {
                    if (_self.selectedModelDatas.length == 0) {
                      Notify.error(_self.$t('lang.Notify.error'), _self.$t('lang.tabButton.describe3'), true);
                      return;
                    } else if (_self.selectedModelDatas.length > 1) {
                      Notify.error(_self.$t('lang.Notify.error'), _self.$t('lang.tabButton.describe2'), true);
                      return;
                    }
                    var tempResult1 = tempResult.replace('{', '').replace('}', '');
                    htmlWindowUrl = htmlWindowUrl.replace(
                      tempResult,
                      _self.getFirstSelectModelDataFieldValue(tempResult1),
                    );
                  }
                }

                var openWindow = window.open(htmlWindowUrl);

                // 自动关闭
                if (autoCloseInterval != undefined) {
                  setTimeout(function () {
                    openWindow.close();
                    openWindow = undefined;
                  }, autoCloseInterval * 1000);
                }
              }
            }
          },
          errorData => {
            Common.processException(errorData);
          },
        );
      }
    },
    // 执行流程
    executeProcess: function () {
      var _self = this;
      var ids = [_self.modelData.id];
      ProcessReportResource.runProcessByIds(_self.tabButtonModel.processReportNo, ids).then(
        successData => {
          _self.modal = true;
          _self.processReportResult = successData;

          if (
            _self.processReportResult.reportResults != undefined &&
            _self.processReportResult.reportResults.length > 0
          ) {
            _self.processReportResult.reportResults.forEach(function (item, index) {
              if (item.reportDefinitionType !== 'ExcelReport') {
                item.previewIndex = 1;
              } else {
                item.previewIndex = 2;
              }
              if (index == 0) {
                item.showPreview = true;
              } else {
                item.showPreview = false;
              }
            });
          }
          _self.titleModal = false;
          _self.refreshDatas();
        },
        errorData => {
          _self.titleModal = false;
          Common.processException(errorData);
        },
      );
    },
    // 切换到Form表单的路由
    switchFormRoute: function (tabButton) {
      const _self = this;
      var routeDate = {
        path: tabButton.customerWindowRouteUrl,
        params: {
          modelData: this.modelData,
        },
      };
      // 请勿修改，会影响生单的功能
      var uuid = _self.uuid;
      if (uuid != undefined) {
        routeDate.path = routeDate.path + '/' + uuid;
      }

      const frameUrl = Common.getRedirectUrl(
        '#' + routeDate.path,
      );

      // 供子页面iframe调用，修改modelData，(举例：生单界面修改参数)。
      // window.modelDataChanged = this.modelDataChanged;

      // window.getModelData = this.getModelData;
      let modelData = JSON.stringify(this.modelData);
      console.log(modelData);
      localStorage.setItem(_self.uuid + '#GenerateDocumentTool', modelData);

      var iWidth = 1280;//弹出窗口的宽度;
      var iHeight = 720; //弹出窗口的高度;
      var iTop = (window.screen.availHeight - 30 - iHeight) / 2;//获得窗口的垂直位置;
      var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //获得窗口的水平位置;
      window.open(frameUrl, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
      // window.open(frameUrl);
    },

    /**
     * 获取字符串的哈希值
     * @param input
     */
    getHash: function (input) {
      let hash = 0;
      if (input.length === 0) {
        return hash;
      }
      for (let i = 0; i < input.length; i++) {
        const char = input.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // 确保返回值是一个32位有符号整数
      }
      return Math.abs(hash).toString();
    },
    /**
     * 远程加载ES VUE组件模块，并在模态框中打开。
     * @param jsUrl js路径
     * @param cssUrl css路径
     */
    openRemoteComponentModule: function (tabButton) {
      var _self = this;
      let jsUrl = tabButton.remoteComponentModuleJsUrl;
      let cssUrl = tabButton.remoteComponentModuleCssUrl;

      // 显示模态框
      // 异步的加载js组件
      //let jsUrl = './static/client-eam-module-v3/dist/AssetCheckCreate.js';
      //let cssUrl = './static/client-eam-module-v3/dist/AssetCheckCreate.css';

      if (cssUrl != null && cssUrl.length > 0) {
        let cssUrlHash = _self.getHash(cssUrl);
        CssUtil.dynamicLoadCss(cssUrl, cssUrlHash);
      }
      // webpackIgnore：设置为 true 时，禁用动态导入解析。
      // const testAsyncRemoteComponent  = await import(/* webpackIgnore: true */ jsUrl);

      // console.log(testAsyncRemoteComponent);
      if (jsUrl != null && jsUrl.length > 0) {
        const testAsyncRemoteComponent = defineAsyncComponent({
          // 加载函数
          loader: () => {
            return import(/* webpackIgnore: true */ jsUrl);
          },
          // 加载异步组件时使用的组件
          loadingComponent: ASpin,
          // 展示加载组件前的延迟时间，默认为 200ms
          delay: 200,
          // 加载失败后展示的组件
          errorComponent: AEmpty,
          // 如果提供了一个 timeout 时间限制，并超时了
          // 也会显示这里配置的报错组件，默认值是：Infinity
          timeout: 10000,
        });

        _self.modal1Component = testAsyncRemoteComponent;
        _self.modal1Open = true;
        console.log(_self.modal1Component);
      }
    },

    // 显示逻辑（完整实现）
    showLogical: async function (field) {
      const _self = this;

      const cacheKey = `${field.fieldName}_showLogical`;

      if (!this.modelData?.data) {
        _self.logicStates.delete(cacheKey);
        return false;
      }
      _self.$emit('getModelData', false, 'view');

      // 存在缓存直接返回
      if (_self.logicStates.has(cacheKey)) {
        return _self.logicStates.get(cacheKey);
      }

      const logic = field.showLogical;
      // 无逻辑定义时默认显示
      if (!logic) {
        _self.logicStates.set(cacheKey, true);
        return true;
      }

      // 数据未加载时隐藏
      if (!_self.modelData?.data) {
        _self.logicStates.set(cacheKey, false);
        return false;
      }

      const functionName = field.fieldName.replace(/\./g, '_') + '_showLogical';

      try {
        // 动态加载逻辑
        if (!_self[functionName]) {
          if (!_self.jsUrl) {
            throw new Error('JS文件路径未配置');
          }

          const targetFunction = await JsUtil.dynamicLoadJsFunction(_self.jsUrl, logic);
          if (typeof targetFunction !== 'function') {
            throw new Error('加载的方法不是函数类型');
          }
          _self[functionName] = targetFunction;
        }

        // 执行逻辑函数
        const context = new _self.getContext(_self.modelData);
        const result = Boolean(_self[functionName](context));

        // 缓存结果并触发响应式更新
        _self.logicStates.set(cacheKey, result);
        _self.$forceUpdate(); // 确保视图刷新
        field.isLogicalShow = result;
        return result;
      } catch (error) {
        console.error(`[${field.fieldName}]显示逻辑执行失败:`, error);
        _self.logicStates.set(cacheKey, false);
        Notify.error('逻辑执行异常', `字段【${field.displayName}】显示逻辑处理失败，请联系管理员`, false);
        return false;
      }
    },

    // 是否只读
    readOnly: function (field) {
      if (field == undefined) {
        return true;
      }

      if (field != undefined && field.readOnly == true) {
        return true;
      }

      if (field != undefined && field.entityFieldIndex > 0) {
        return true;
      }

      if (
        this.modelData != undefined &&
        this.modelData.id > 0 &&
        (field.updatable == undefined || field.updatable == false)
      ) {
        return true;
      }

      return field.readOnly;
    },
  },
};
</script>

<style scoped>
/* 基础布局样式 */
.single-row.fixed-width-col {
  flex: 0 0 100% !important;
  max-width: 100% !important;
  min-width: 100% !important;
}

/* 桌面端横向排列 */
@media (min-width: 769px) {
  .single-row.fixed-width-col .ant-form-item {
    display: flex;
    width: 100%;
  }
  .single-row.fixed-width-col .ant-form-item-label {
    flex: none;
  }
  .single-row.fixed-width-col .ant-form-item-control {
    flex: 1;
    max-width: 230px;
  }
}

/* 固定宽度容器 */
.fixed-width-col {
  display: flex;
  justify-content: center;
  min-width: 380px;
  max-width: 380px;
  transition: all 0.3s;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .fixed-width-col {
    min-width: 100%;
    max-width: 100%;
  }
  .fixed-width-col.single-row .ant-form-item {
    flex-direction: column;
  }
  .fixed-width-col.single-row .ant-form-item-label,
  .fixed-width-col.single-row .ant-form-item-control {
    width: 100% !important;
    max-width: none !important;
  }
}

/* 必填标记 */
.required-mark {
  color: #ff4d4f;
  margin-right: 4px;
  flex-shrink: 0;
}

/* 表单项基础样式 */
.fixed-form-item .ant-form-item-label {
  flex: none !important;
  width: 150px !important;
}
.fixed-form-item .ant-form-item-label label {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 表单控件容器 */
.fixed-form-item .ant-form-item-control {
  flex: none !important;
  width: 260px !important;
}

/* 统一输入控件宽度 */
.fixed-form-item .ant-input,
.fixed-form-item .ant-input-number,
.fixed-form-item .ant-select,
.fixed-form-item .ant-picker {
  width: 100% !important;
}

/* 移动端表单布局适配 */
@media (max-width: 768px) {
  .fixed-width-col .ant-form-item {
    flex-direction: column;
  }
  .fixed-width-col .ant-form-item-label {
    width: 100% !important;
    text-align: left;
  }
  .fixed-width-col .ant-form-item-control {
    width: 100% !important;
  }
}

/* 深度样式覆盖 */
:deep(.ant-row) {
  align-items: center !important;
}

:deep(.ant-form-item) {
  margin-bottom: 6px !important;
}

:deep(.ant-form-item-label) {
  overflow: visible;
  white-space: normal;
}

:deep(.ant-form-item-label > label) {
  font-size: small !important;
  font-weight: 700 !important;
  height: auto !important;
  margin-bottom: 0px !important;
}
</style>