<template>
  <template v-if="modelData && modelData.data && showField">
    <a-col
      v-if="field.visible" :xs="24"
      :sm="isSingleRow ? 24 : 12" :md="isSingleRow ? 24 : 8" :lg="isSingleRow ? 24 : 6"
      :class="['fixed-width-col', { 'single-row': isSingleRow }]"
    >
      <a-form-item
        v-if="modelData?.data && field.visible"
        :label-col="{ style: 'width: 120px' }"
        :wrapper-col="{ style: isSingleRow ? 'width: 60vw' : '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>

        <div>
          <a-input
            v-if="fieldUtil.isTextType(field)" v-model:value="displayValue" :name="field.displayName"
            :readonly="readOnly" :disabled="readOnly"
          />

          <a-input-number
            v-if="fieldUtil.isNumberType(field)" v-model:value="displayValue" :name="field.displayName"
            :disabled="readOnly" @mousewheel="mouseWheelEvent" @change="numberFormat"
          />

          <a-switch v-if="fieldUtil.isCheckBoxType(field)" v-model:checked="displayValue" :disabled="readOnly" />

          <RedGreenSelect
            v-if="fieldUtil.isRedGreenEditorType(field)" v-model="displayValue" type="string"
            :disabled="readOnly"
          />

          <a-input-password
            v-if="fieldUtil.isPasswordType(field)" v-model:value="displayValue" :name="field.displayName"
            :disabled="readOnly"
          />

          <a-textarea
            v-if="fieldUtil.isTextAreaType(field)" v-model:value="displayValue" 
            :auto-size="{ minRows: 3, maxRows: 5 }"
            :name="field.displayName" :style="field.cssStyle" :disabled="readOnly"
          />

          <Date
            v-if="fieldUtil.isDateType(field)" :model-value="displayValue" :data-vv-name="field.displayName"
            :name="field.displayName" :data-vv-value-path="displayValue" :readonly="readOnly"
            @update:model-value="textChanged"
          />

          <Time
            v-if="fieldUtil.isTimeType(field)" v-model="displayValue" :data-vv-name="field.displayName"
            :name="field.displayName" :data-vv-value-path="displayValue" :readonly="readOnly"
          />

          <DateTime
            v-if="fieldUtil.isDateTimeType(field)" :model-value="displayValue" :readonly="readOnly"
            @update:model-value="textChanged"
          />

          <YearPicker
            v-if="fieldUtil.isYearType(field)" :value="displayValue" :readonly="readOnly" style="width: 100%;"
            @selected="textChanged"
          />

          <VueMonthlyPicker
            v-if="fieldUtil.isYearMonthType(field)" id="month-picker" v-model="month"
            date-format="YYYY-MM" @selected="refresh"
          />

          <ImageWidget
            v-if="fieldUtil.isImageType(field)" style="width: 100%;" :uuid="uuid1"
            :pattern-json="field.pattern" :field="field" :field-value="fieldValue" :class-name="className"
            :readonly="readOnly" @value-changed="valueChanged"
          />

          <ImageListWidget
            v-if="fieldUtil.isImageListType(field)" :field="field" :field-value="fieldValue"
            :class-name="className" :readonly="readOnly" @value-changed="valueChanged"
          />

          <VideoListWidget
            v-if="fieldUtil.isVideoType(field)" :field="field" :field-value="fieldValue"
            :class-name="className" :readonly="readOnly" @value-changed="valueChanged"
          />

          <FileListWidget
            v-if="fieldUtil.isFileType(field)" :field="field" :field-value="fieldValue"
            :class-name="className" :readonly="readOnly" @value-changed="valueChanged"
          />

          <EnumRadioGroupWidget
            v-if="fieldUtil.isRadioButtonGroupType(field)" :field="field" :field-value="fieldValue"
            :data-vv-name="field.displayName" :name="field.displayName" :data-vv-value-path="displayValue"
            :readonly="readOnly" @value-changed="valueChanged"
          />

          <ManyToManySetSearchWidget
            v-if="fieldUtil.isManyToManySetType(field)" :info-window-no="field.infoWindowNo"
            :field="field" :field-value="fieldValue" :readonly="readOnly" :model-data="modelData" :window-no="windowNo"
            :tab-index="tabIndex" @value-changed="valueChanged"
          />

          <SearchWidget
            v-if="fieldUtil.isSearchType(field)" :info-window-no="field.infoWindowNo" :field="field"
            :field-value="fieldValue" :readonly="readOnly" :model-data="modelData" :window-no="windowNo"
            :tab-index="tabIndex" @value-changed="valueChanged"
          />

          <EnumSelectWidget
            v-if="fieldUtil.isEnumListType(field)" :field="field" :field-value="fieldValue"
            :name="field.displayName" :readonly="readOnly" @value-changed="valueChanged"
          />

          <EnumMultiSelectWidget
            v-if="fieldUtil.isEnumMultiType(field)" :field="field" :field-value="fieldValue"
            :name="field.displayName" :readonly="readOnly" @value-changed="valueChanged"
          />

          <SelectWidget
            v-if="fieldUtil.isSelectType(field)" ref="selectWidget" :field="field" :field-value="fieldValue"
            :window-no="windowNo" :tab-index="tabIndex" :readonly="readOnly" :model-data="modelData"
            @value-changed="valueChanged"
          />

          <ButtonWidget
            v-if="fieldUtil.isButtonType(field)" :field="field" :field-value="fieldValue" :readonly="readOnly"
            @value-changed="valueChanged" @execute-callout="executeCallout"
          />

          <RichTextAreaEditorWidget
            v-if="fieldUtil.isRichTextAreaEditor(field)" :display-value="displayValue"
            :class-name="className" :field-value="fieldValue" :readonly="readOnly" @value-changed="valueChanged"
          />
          <div v-if="fieldUtil.isGridButtonEditor(field)" style="display: inline-block">
            <template v-for="(tabFormButtonItem, index) in field.tabFormButtonDtos" :key="tabFormButtonItem.name">
              <template v-if="visible[index]">
                <a-button v-if="tabFormButtonItem.action === 'EDIT'" type="link" @click="editRecord">
                  {{ tabFormButtonItem.name
                  }}
                </a-button>
                <a-button
                  v-if="tabFormButtonItem.action === 'RUN_PROCESS_REPORT'" type="link"
                  @click="execute(tabFormButtonItem)"
                >
                  {{ tabFormButtonItem.name }}
                </a-button>
                <a-button
                  v-if="tabFormButtonItem.action === 'OPEN_CUSTOMER_WINDOW'" type="link"
                  @click="execute(tabFormButtonItem)"
                >
                  {{ tabFormButtonItem.name }}
                </a-button>
                <a-button
                  v-if="tabFormButtonItem.action === 'OPEN_HTML_WINDOW'" type="link"
                  @click="execute(tabFormButtonItem)"
                >
                  {{ tabFormButtonItem.name }}
                </a-button>
                <a-button
                  v-if="tabFormButtonItem.action === 'OPEN_REMOTE_COMPONENT_MODULE_IN_MODAL'" type="link"
                  @click="openRemoteComponentModule(tabFormButtonItem)"
                >
                  {{ tabFormButtonItem.name }}
                </a-button>
                <a-button
                  v-if="tabFormButtonItem.action === 'OPEN_NEW_VIEW_EDIT'" type="link"
                  @click="openNewViewEdit(tabFormButtonItem)"
                >
                  {{ tabFormButtonItem.name }}
                </a-button>
                <a-button v-if="tabFormButtonItem.action === 'ABANDON'" danger @click="abandon">
                  {{ tabFormButtonItem.name }}
                </a-button>
              </template>
            </template>
          </div>
          <p v-show="!validateMandatory" class="required-mark required-error">
            该字段为必填字段
          </p>
        </div>
      </a-form-item>
    </a-col>
  </template>
  <component
    :is="modal1Component" v-model:open="modal1Open" :class-name="className" :model-data="modelData"
    @refresh-data="refreshDatas"
  />
</template>

<script>
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 SearchWidget from '../tabFormWidget/SearchWidget.vue';
import ImageListWidget from '../tabFormWidget/ImageListWidget.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 EnumMultiSelectWidget from '../tabFormWidget/EnumMultiSelectWidget.vue';
import ManyToManySetSearchWidget from '../tabFormWidget/ManyToManySetSearchWidget.vue';
import RedGreenSelect from '../../widget/RedGreenSelect.vue';
import ImageWidget from '../tabFormWidget/ImageWidget.vue';
import RichTextAreaEditorWidget from '../tabFormWidget/RichTextAreaEditorWidget.vue';
import JsUtil from '../../common/JsUtil.js';
import { Notify, Uuid, CssUtil } from 'pc-component-v3';
import Common from '../../common/Common.js';
import { Spin as ASpin, Empty as AEmpty, message } from 'ant-design-vue';
import CustomerWindowResource from '../../api/dic/CustomerWindowResource.js';
import HtmlWindowResource from '../../api/dic/HtmlWindowResource.js';
import ProcessReportResource from '../../api/dic/ProcessReportResource.js';
import { defineAsyncComponent } from 'vue';





export default {

  components: {
    SearchWidget,
    ImageListWidget,
    EnumSelectWidget,
    SelectWidget,
    EnumRadioGroupWidget,
    VideoListWidget,
    FileListWidget,
    EnumMultiSelectWidget,
    ManyToManySetSearchWidget,
    ImageWidget,
    RedGreenSelect,
    ButtonWidget,
    RichTextAreaEditorWidget,
  },

  props: {

    windowNo: {
      type: String,
      default: null,
    },
    tabIndex: {
      type: Number,
      default: null,
    },
    className: {
      type: String,
      default: null,
    },
    multipleColumn: {
      type: Boolean,
      default: null,
    },
    jsUrl: {
      type: String,
      default: null,
    },
    field: {
      type: Object,
      default: function () {
        return null;
      },
    },
    modelData: {
      type: Object,
      default: function () {
        return null;
      },
    },
    isChineseEnglish: {
      type: Boolean,
      default: null,
    },
    uuid: {
      type: String,
      default : null,
    },
  },


  emits: ['executeCallout', 'valueChanged', 'refreshDatas', 'getModelData', 'abandonWorkflow', 'modelDataChanged'],

  data: function () {
    this.Language = Language;
    // eslint-disable-next-line
    var value =
      this.modelData == undefined ||
        this.modelData.data == undefined ||
        this.modelData.data[this.field.fieldName] == undefined
        ? ''
        : this.modelData.data[this.field.fieldName].displayValue[
          this.field.entityFieldIndex
        ];

    var fieldValue =
      this.modelData == undefined || this.modelData.data == undefined
        ? []
        : this.modelData.data[this.field.fieldName];

    return {
      displayValue: value,
      fieldValue: fieldValue,
      fieldUtil: fieldUtil,
      validateMandatory: true, // 验证强制字段是否通过
      month: undefined,
      uuid1: Uuid.createUUID(),
      showField: true, // 显示字段
      visible: [],
      modal1Open: false,
      modal1Component: null,
    };
  },

  computed: {
    isSingleRow() {
      if (!this.multipleColumn) {
        return true;
      }
      return this.field.singleRow;
    },
    readOnly: function () {
      if (this.field == undefined) {
        return true;
      }

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

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

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

      return this.field.readOnly;
    },

  },

  watch: {
    displayValue: function (currentValue, oldValue) {
      if (
        fieldUtil.isSearchType(this.field) == false &&
        this.field.entityFieldIndex == 0 &&
        fieldUtil.isSelectType(this.field) == false &&
        fieldUtil.isRadioButtonGroupType(this.field) == false &&
        fieldUtil.isEnumListType(this.field) == false &&
        fieldUtil.isManyToManySetType(this.field) == false
      ) {
        // add by jack 20240220
        // 修复bug：当modelData.data的值从外部修改以后，修改执行 watch->'modelData.data'  中的 this.displayValue = ? 方法
        // 执行完成以后，watch->displayValue 又会执行，会触发valueChanged事件，这会导致 callout/calloutjs 会被多次执行。
        // 所以在触发 valueChanged 的之前，先判断currentValue与modelData中的值是否相等，
        // 如果相等，说明是外部修改了modelData，然后执行了 watch->'modelData.data' 方法修改了 displayValue，此时不触发valueChanged事件。
        // 如果不相等，说明是DOM修改了，触发修改了displayValue，此时触发valueChanged事件。

        const modelDataFieldDisplayValue = this.getModelDataFieldDisplayValue();

        if (currentValue !== oldValue && currentValue !== modelDataFieldDisplayValue) {
          var newFieldValue = {
            displayValue: [currentValue],
            fieldType: 'String',
          };
          this.$emit('valueChanged', newFieldValue);
        }
      }
    },

    'modelData.data': {
      deep: true,
      handler(curVal, oldVal) {
        if (curVal == undefined ||
          curVal[this.field.fieldName] == undefined ||
          curVal[this.field.fieldName].displayValue == undefined ||
          curVal[this.field.fieldName].displayValue.length < this.field.entityFieldIndex + 1) {
          this.displayValue = '';
        } else {
          let tempValue = curVal[this.field.fieldName].displayValue[this.field.entityFieldIndex];
          if (fieldUtil.isCheckBoxType(this.field)) {
            if (typeof (tempValue) == 'string') {
              this.displayValue = (tempValue === 'true') ? true : false;
            }
            if (typeof (tempValue) == 'boolean') {
              this.displayValue = (tempValue === true) ? true : false;
            }
          } else {
            this.displayValue = tempValue;
          }
        }
        this.fieldValue = curVal == undefined ? [] : curVal[this.field.fieldName];
        this.showLogical();
      },
    },
    'field.tabFormButtonDtos': {

      immediate: true,
      handler(curVal, oldVal) {
        const _self = this;
        this.visible.splice(0, this.visible.length);
        if (curVal != null) {
          curVal.forEach(item => {
            _self.visible.push(true);
          });
        }
      },
    },
    month: function () {
      this.textChanged(this.month);
    },
  },

  mounted: function () { },

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


    /**
     * 获取modelData中字段的显示值
     */
    getModelDataFieldDisplayValue: function () {
      if (this.modelData == null
        || this.field == null
        || this.modelData.data[this.field.fieldName] == undefined
        || this.modelData.data[this.field.fieldName].displayValue == undefined
        || this.modelData.data[this.field.fieldName].displayValue.length < this.field.entityFieldIndex + 1) {
        return null;
      }
      return this.modelData.data[this.field.fieldName].displayValue[this.field.entityFieldIndex];
    },
    refreshDatas: function () {
      this.$emit('refreshDatas');
    },

    // 获取modelData
    getEditModelData: function () {
      this.$emit('getModelData', true);
    },
    // 更新modelData
    editModelDataChanged: function (modelData) {
      this.$emit('modelDataChanged', modelData);
    },
    // 刷新modelData
    refreshEditData: function () {
      window.refreshCurdDatas = this.refreshDatas;
    },
    // 弃审
    abandon: function () {
      this.$emit('abandonWorkflow');
    },
    /**
     * 打开新界面编辑
     * @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 = true; // 需要通过modelData来保存的标识
      window.editModelDataChanged = _self.editModelDataChanged; // 修改modelData
      const url = Common.getRootPath() + openNewViewEditUrl;
      window.open(url, '_blank');
    },
    // 值改变事件
    valueChanged: function (newFieldValue) {
      // this.fieldValue = newFieldValue;
      this.$emit('valueChanged', newFieldValue);
    },

    /**
     * 执行Callout
     */
    executeCallout: function (field) {
      this.$emit('executeCallout', field);
    },

    //年份选择器值改变
    textChanged: function (value) {
      var newFieldValue = {
        displayValue: [value],
        fieldType: 'String',
      };
      this.$emit('valueChanged', newFieldValue);
    },

    validateRule: function (field) {
      return field.mandatory ? 'required' : '';
    },

    performValide: function () {
      var _self = this;
      _self.validateMandatory = true;

      if (this.field.mandatory == true) {
        if (
          fieldUtil.isRadioButtonGroupType(this.field) ||
          fieldUtil.isSelectType(this.field) ||
          fieldUtil.isSearchType(this.field)
        ) {
          var idValue =
            this.modelData == undefined ||
              this.modelData.data == undefined ||
              this.modelData.data[this.field.fieldName] == undefined
              ? undefined
              : this.modelData.data[this.field.fieldName].id;
          if (idValue == null || idValue == '' || idValue < 1) {
            _self.validateMandatory = false;
          }
        } else if (fieldUtil.isCheckBoxType(this.field)) {
          return true;
        } else if (fieldUtil.isRedGreenEditorType(this.field)) {
          return true;
        } else {
          var stringValue =
            this.modelData == undefined ||
              this.modelData.data == undefined ||
              this.modelData.data[this.field.fieldName] == undefined
              ? ''
              : this.modelData.data[this.field.fieldName].displayValue[0];
          if (stringValue == undefined || stringValue === '') {
            _self.validateMandatory = false;
          }
        }
      }
      return _self.validateMandatory;
    },

    /**
     * 年份变化
     */
    yearChange: function () { },

    /**
     * 年月选择完成
     */
    refresh: function () { },

    numberFormat: function () {
      if (
        this.fieldItem &&
        this.fieldItem.pattern &&
        this.fieldItem.pattern != ''
      ) {
        var _self = this;
        fieldUtil.formatNumber(
          this.displayValue,
          this.fieldItem.pattern,
          function (formatValue) {
            _self.displayValue = formatValue;
          },
        );
      }
    },

    /**
     * 获取字符串的哈希值
     * @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);
      }
    },
    //跳转或执行流程
    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);
    },
    /**
     * 禁止滚轮滚动影响数字
     */
    mouseWheelEvent: function (event) {
      if (event || Window.event) {
        event.preventDefault();
      }
    },

    /**
     * 响应显示逻辑
     */
    showLogical: function () {
      let _self = this;
      var logic = this.field.showLogical;
      if (logic == null || logic == '') {
        this.showField = true;
        return;
      }
      _self.modelData.type = 'edit';
      const functionName =
        this.field.fieldName.replace('.', '_') + '_showLogical';


      let executeFunction = function () {
        try {
          let context = new _self.getContext(_self.modelData);
          _self.showField = _self[functionName](context);
          _self.field.isLogicalShow = _self.showField;
        } catch (error) {
          console.error(error);
          Notify.error('数据字典定义异常', '【' + logic + '】前端列显示逻辑定义异常,请联系管理员检查数据字典的定义。', false);
        }
      };

      if (_self[functionName] == null) {
        const jsUrl = _self.jsUrl;
        if (jsUrl == null || jsUrl == undefined) {
          Notify.error('数据字典定义异常', '【' + logic + '】前端列显示逻辑的JS文件不存在,请联系管理员检查数据字典是否JS文件。', false);
          return;
        }

        let promise = JsUtil.dynamicLoadJsFunction(jsUrl, logic);

        promise.then(targetFunction => {
          _self[functionName] = targetFunction;
          if (_self[functionName] == null) {
            Notify.error('数据字典定义异常', '【' + logic + '】前端列显示逻辑方法不存在,请联系管理员检查数据字典。', false);
            return;
          }
          executeFunction();
        }, errorData => {
          console.error(errorData);
        });
      } else {
        executeFunction();
      }
    },
  },
};
</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: 120px !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>