<template>
  <!-- 输入框 -->
  <x-form-col v-if="attr.type === 'input' && show" :occupyCol="attr.occupyCol" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <!--  如果配置了后置按钮插槽    -->
      <a-input-group
        v-if="
          ((attr.inputOnAfterName && attr.inputOnAfterFunc) || (attr.inputOnAfterIcon && attr.inputOnAfterIconFunc)) &&
          mode !== '查询'
        "
        style="display: flex; width: 100%; padding: 4px 0"
        compact
      >
        <a-input
          v-model="form[attr.model]"
          autocomplete="off"
          :read-only="readOnly"
          :disabled="disabled && !readOnly"
          :whitespace="true"
          @input="attr.dataChangeFunc && debouncedDataChangeFunc()"
          :suffix="attr.inputSuffix && mode !== '新增' ? attr.inputSuffix : ''"
          @blur="mode !== '查询' && attr.inputOnBlurFunc && emitFunc(attr.inputOnBlurFunc, attr)"
          @keyup.enter="mode !== '查询' && attr.inputOnEnterFunc && emitFunc(attr.inputOnEnterFunc, attr)"
          :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
          :ref="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
          :id="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
        />
        <a-button
          v-if="attr.inputOnAfterName && attr.inputOnAfterFunc && !attr.inputOnAfterName.includes('|')"
          style="width: auto; min-width: 4rem; max-width: 6rem"
          type="primary"
          @click="emitFunc(attr.inputOnAfterFunc, attr)"
        >
          {{ attr.inputOnAfterName }}
        </a-button>
        <!--    仅可以配置 一个按钮 以及 一个图标插槽    -->
        <a-button
          style="width: 2rem; flex-shrink: 0"
          v-else-if="attr.inputOnAfterIcon"
          :type="attr.inputOnAfterIcon && attr.inputOnAfterName ? 'primary' : ''"
          :icon="attr.inputOnAfterIcon || 'question'"
          @click="emitFunc(attr.inputOnAfterIconFunc, attr)"
        ></a-button>
        <!-- 状态按钮 -->
        <x-status-button
          v-else
          :states="parseStates(attr.inputOnAfterName, attr.inputOnAfterFunc)"
          v-on="generateDynamicEvents(attr.inputOnAfterFunc, attr)"
          style="width: auto; min-width: 4rem; max-width: 6rem"
        />
      </a-input-group>
      <a-input-number
        v-else-if="attr.numberInput && !readOnly"
        v-model="form[attr.model]"
        autocomplete="off"
        :whitespace="true"
        @change="attr.dataChangeFunc && debouncedDataChangeFunc()"
        :disabled="disabled && !readOnly"
        style="width: 100%"
        @blur="mode !== '查询' && attr.inputOnBlurFunc && emitFunc(attr.inputOnBlurFunc, attr)"
        @keyup.enter="mode !== '查询' && attr.inputOnEnterFunc && emitFunc(attr.inputOnEnterFunc, attr)"
        :suffix="attr.inputSuffix && mode !== '新增' ? attr.inputSuffix : ''"
        :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
        :ref="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
        :id="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
      />
      <a-input
        v-else
        v-model="form[attr.model]"
        autocomplete="off"
        :whitespace="true"
        :read-only="readOnly"
        :disabled="disabled && !readOnly"
        @input="attr.dataChangeFunc && debouncedDataChangeFunc()"
        :suffix="attr.inputSuffix && mode !== '新增' ? attr.inputSuffix : ''"
        style="width: 100%"
        @blur="mode !== '查询' && attr.inputOnBlurFunc && emitFunc(attr.inputOnBlurFunc, attr)"
        @keyup.enter="mode !== '查询' && attr.inputOnEnterFunc && emitFunc(attr.inputOnEnterFunc, attr)"
        :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
        :ref="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
        :id="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
      />
    </a-form-model-item>
  </x-form-col>
  <!-- 下拉框 -->
  <x-form-col v-else-if="attr.type === 'select' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-if="!attr.showMode || mode === '查询' || attr.showMode === 'select'"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <!--      <span slot="label" class="label-box">{{ showLabel?attr.name:undefined }}</span>-->
      <a-select
        v-if="!attr.lazyLoad || attr.lazyLoad === 'false'"
        v-model="form[attr.model]"
        :disabled="disabled || readOnly"
        @change="handleSelectChange"
        :filter-option="filterOption"
        :getPopupContainer="getPopupContainer"
        dropdownClassName="custom-dropdown"
        :dropdownMatchSelectWidth="false"
        :dropdownStyle="{ position: 'absolute' }"
        :placeholder="attr.placeholder ? attr.placeholder : '请选择'"
        show-search
        :allowClear="true"
        :getCalendarContainer="triggerNode => triggerNode.parentNode"
      >
        <a-select-option v-if="mode === '查询'" key="999999" value="">全部</a-select-option>
        <template v-if="attr.keys">
          <a-select-option v-for="(item, index) in attr.keys" :key="index.value" :value="item.value + ''">
            {{ item.label }}
          </a-select-option>
        </template>
        <template v-else-if="attr.keyName">
          <template v-if="attr.keyName.indexOf('async ') !== -1 || attr.keyName.indexOf('function ') !== -1">
            <a-select-option v-for="(item, index) in optionForFunc" :key="index.value" :value="item.value + ''">
              <template>
                {{ item.label }}
              </template>
            </a-select-option>
          </template>
          <template v-else>
            <a-select-option v-for="(item, index) in option" :key="index.value" :value="item.value + ''">
              <template
                v-if="
                  attr.keyName.indexOf('logic@') !== -1 ||
                  attr.keyName.indexOf('config@') !== -1 ||
                  attr.keyName.indexOf('search@') !== -1
                "
              >
                {{ item.label }}
              </template>
              <template v-else-if="item.status">
                <!-- 徽标(badge) -->
                <a-badge v-if="item.status !== 'gary'" :color="item.status" :text="item.label" />
                <a-badge v-else color="#D9D9D9" :text="item.label" />
              </template>
            </a-select-option>
          </template>
        </template>
      </a-select>
      <a-select
        v-else
        v-model="form[attr.model]"
        :disabled="disabled || readOnly"
        @change="handleSelectChange"
        :filter-option="filterOption"
        :getPopupContainer="getPopupContainer"
        dropdownClassName="custom-dropdown"
        :dropdownMatchSelectWidth="false"
        :dropdownStyle="{ position: 'absolute' }"
        :placeholder="attr.placeholder ? attr.placeholder : '搜索' + attr.name"
        show-search
        @search="fetchFunction"
      >
        <template #notFoundContent>
          <a-spin v-if="searching" size="small" />
        </template>
        <a-select-option v-if="mode === '查询'" key="999999" value="">全部</a-select-option>
        <a-select-option v-for="(item, index) in option" :key="index" :value="item.value + ''">
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-model-item>
    <a-form-model-item
      :disabled="disabled || readOnly"
      v-bind="bindOther"
      :rules="effectiveRules"
      v-else-if="attr.showMode === 'radioGroup'"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-radio-group v-model="form[attr.model]">
        <a-radio-button v-for="modeItem in option" :key="modeItem.value" :value="modeItem.value">
          {{ modeItem.label }}
        </a-radio-button>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item
      v-bind="bindOther"
      v-else-if="attr.showMode === 'clickChange' && option.length > 0"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <XClickChangeBtn></XClickChangeBtn>
    </a-form-model-item>
  </x-form-col>
  <!-- 多选框 -->
  <x-form-col v-else-if="attr.type === 'checkbox' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-if="!attr.showMode || mode === '查询' || attr.showMode === 'select'"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-select
        class="multiple_select"
        style="width: 100%"
        v-if="!attr.lazyLoad || attr.lazyLoad === 'false'"
        v-model="form[attr.model]"
        :disabled="disabled"
        :filter-option="filterOption"
        :getPopupContainer="getPopupContainer"
        :placeholder="attr.placeholder ? attr.placeholder : '请选择'"
        @change="handleCheckboxChange"
        :mode="mode === '新增/修改' && attr.chooseForm === 'singleChoice' ? 'default' : 'multiple'"
        show-search
        allowClear
      >
        <template v-if="attr.keys">
          <a-select-option v-for="(item, index) in attr.keys" :key="index" :value="item.value + ''">
            {{ item.label }}
          </a-select-option>
        </template>
        <template v-else-if="attr.keyName">
          <template v-if="attr.keyName.indexOf('async ') !== -1 || attr.keyName.indexOf('function ') !== -1">
            <a-select-option v-for="(item, index) in optionForFunc" :key="index.value" :value="item.value + ''">
              <template>
                {{ item.label }}
              </template>
            </a-select-option>
          </template>
          <template v-else>
            <a-select-option v-for="(item, index) in option" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </template>
        </template>
      </a-select>
      <a-select
        v-else
        class="multiple_select"
        v-model="form[attr.model]"
        :disabled="disabled"
        :filter-option="filterOption"
        :getPopupContainer="getPopupContainer"
        :placeholder="attr.placeholder ? attr.placeholder : '搜索' + attr.name"
        :mode="mode === '新增/修改' && attr.chooseForm === 'singleChoice' ? 'default' : 'multiple'"
        style="width: 100%"
        @change="handleCheckboxChange"
        show-search
        allowClear
        @search="fetchFunction"
      >
        <template #notFoundContent>
          <a-spin v-if="searching" size="small" />
        </template>
        <a-select-option v-for="(item, index) in option" :key="index" :value="item.value + ''">
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-model-item>
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-else
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-checkbox-group v-model="form[attr.model]" :options="option" @change="handleCheckboxChange" />
    </a-form-model-item>
  </x-form-col>
  <!-- 单选框 -->
  <x-form-col v-else-if="attr.type === 'radio' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-if="!attr.showMode || attr.type === 'radio'"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-radio-group v-model="form[attr.model]" @change="handleRadioChange">
        <template v-if="attr.keys">
          <a-radio v-for="(item, index) in attr.keys" :key="index" :value="item.value">
            {{ item.label }}
          </a-radio>
        </template>
        <template v-else-if="attr.keyName">
          <a-radio v-for="(item, index) in option" :key="index" :value="item.value">
            {{ item.label }}
          </a-radio>
        </template>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-else-if="attr.showMode === 'radioGroup'"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-radio-group v-model="form[attr.model]">
        <a-radio-button v-for="modeItem in option" :key="modeItem.value" :value="modeItem.value">
          {{ modeItem.label }}
        </a-radio-button>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      v-else-if="attr.showMode === 'clickChange' && option.length > 0"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <XClickChangeBtn></XClickChangeBtn>
    </a-form-model-item>
  </x-form-col>
  <!-- 时间 日期 框整合 -->
  <x-form-col
    v-else-if="
      [
        'datePicker',
        'rangePicker',
        'yearPicker',
        'monthPicker',
        'yearRangePicker',
        'monthRangePicker',
        'timePicker',
        'timeRangePicker'
      ].includes(attr.type) && show
    "
    :labelCol="labelCol"
    :mode="mode"
    :layout="layout"
    :attrType="attr.type"
  >
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <XFormDatePicker
        :attr="attr"
        :mode="mode"
        :enablePopupToBody="enablePopupToBody"
        :getCalendarContainer="getPopupContainer"
        :disabled="disabled"
        :readOnly="readOnly"
        :showLabel="showLabel"
        @change="attr.dataChangeFunc && debouncedDataChangeFunc()"
        v-model="form[attr.model]"
      />
    </a-form-model-item>
  </x-form-col>
  <!-- 文本域 -->
  <x-form-col v-else-if="attr.type === 'textarea' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <!--    :style="layout === 'inline'?{width:'calc(100% - 60px)'}:{}"-->
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-textarea
        v-model="form[attr.model]"
        autocomplete="off"
        style="width: 100%"
        :readOnly="readOnly"
        :disabled="disabled"
        :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
        :rows="4"
      />
    </a-form-model-item>
  </x-form-col>
  <!-- 文件上传 -->
  <x-form-col
    v-else-if="(attr.type === 'file' || attr.type === 'image' || attr.type === 'signature') && show"
    :labelCol="labelCol"

    :mode="mode"
    :layout="layout"
    :attrType="attr.type"
  >
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <upload
        :files="files"
        :signs="signs"
        :read-only="readOnly"
        :images="images"
        :compatible-images="form[attr.model]"
        :model="attr"
        v-bind="attr"
        :service-name="serviceName"
        @setFiles="setFiles"
      ></upload>
    </a-form-model-item>
  </x-form-col>
  <!-- 省市区选择框 -->
  <x-form-col v-else-if="attr.type === 'citySelect' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <citySelect
        @change="attr.dataChangeFunc && debouncedDataChangeFunc()"
        ref="citySelect"
        v-model="form[attr.model]"
        :contexts="attr.contexts"
        :value-type="attr.valueType"
        :default-value="form[attr.model]"
      ></citySelect>
    </a-form-model-item>
  </x-form-col>
  <!-- 地点搜索框 -->
  <x-form-col
    v-else-if="(attr.type === 'addressSearch' || attr.type === 'coordinateSearch') && show"
    :labelCol="labelCol"
    :occupyCol="attr.occupyCol"

    :mode="mode"
    :layout="layout"
    :attrType="attr.type"
  >
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <address-search-combobox
        :emitFunc="emitFunc"
        :attr="attr"
        :read-only="readOnly"
        :searchResult="form[attr.model]"
        :address="{ address: form[attr.model], coords: form[`${attr.model}_lng_lat`] }"
        :resultKeys="{ address: attr.model, coords: `${attr.model}_lng_lat` }"
        ref="addressSearchCombobox"
        searchResultType="Object"
        @onSelect="addressSearchComboboxSelect"
        @onDivisionsChange="onDivisionsChange"
      ></address-search-combobox>
    </a-form-model-item>
  </x-form-col>
  <!-- 颜色选择器 -->
  <x-form-col v-else-if="attr.type === 'colorPicker' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <color-picker-combobox :value="form[attr.model]" :read-only="readOnly" @onSelect="colorPickerComboboxSelect" />
    </a-form-model-item>
  </x-form-col>
  <!-- 人员选择框 -->
  <x-form-col v-else-if="attr.type === 'personSetting' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <PersonSetting v-model="form[attr.model]"></PersonSetting>
    </a-form-model-item>
  </x-form-col>
  <!-- 树形选择框 -->
  <x-form-col v-else-if="attr.type === 'treeSelect' && show" :labelCol="labelCol"  :mode="mode" :layout="layout" :attrType="attr.type">
    <x-tree-select
      :rules="effectiveRules"
      @onChange="handleTreeSelectChange"
      v-model="form[attr.model]"
      :attr="attr"
      :disabled="disabled"
      :readOnly="readOnly"
      @mounted="itemMounted"
      ref="xTreeSelect"
    ></x-tree-select>
  </x-form-col>
  <!-- 列表选择框 -->
  <x-form-col v-else-if="attr.type === 'listSelect' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :style="
        layout === 'inline' && attr.occupyCol && attr.occupyCol > 1
          ? { width: `calc(100% - ${attr.occupyCol * 1.533}rem)` }
          : {}
      "
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <a-popover
        ref="rowChoosePopover"
        :visible="rowChoosePopoverVisible"
        title="选择数据"
        placement="bottom"
        trigger="focus"
        :arrowPointAtCenter="true"
        :overlayStyle="{ width: '1000px', height: '30vh' }"
      >
        <template #content>
          <x-report
            v-if="isCover"
            :use-oss-for-img="false"
            :config-name="queryParamsName"
            :service-name="serviceName"
            :show-img-in-cell="true"
            :display-only="true"
            :edit-mode="false"
            :show-save-button="true"
            :no-padding="true"
            :dont-format="true"
            @rowChoose="rowChoose"
            @cancel="closeRowChooseInput"
          ></x-report>
          <x-form-table
            v-else
            title="请选择数据"
            :queryParamsName="queryParamsName"
            :rowSelectMode="true"
            :allowSelectRowNum="1"
            :service-name="serviceName"
            :fixed-query-form="rowChooseFixedQueryValue"
            @rowChoose="rowChoose"
            @afterQuery="rowChooseSearchAfterQuery"
            ref="rowChooseTable"
          >
            <template #button>
              <a-button @click="closeRowChooseInput">关闭</a-button>
            </template>
          </x-form-table>
        </template>
        <a-input
          v-model="form[attr.model]"
          autocomplete="off"
          :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
          @change="searchRowChooseData"
          @focus="showCloseRowChooseInput"
        />
      </a-popover>
    </a-form-model-item>
  </x-form-col>
  <!-- 评分框 -->
  <x-form-col v-else-if="attr.type === 'rate' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <x-rate
        v-model="form[attr.model]"
        :mode="mode"
        :disabled="disabled"
        :query-type="attr.queryType"
        :display-count="attr.displayCount"
        :max-count="attr.maxCount"
        :allow-half="attr.allowHalf"
        :icon="attr.rateIcon"
        :placeholder="attr.placeholder ? attr.placeholder : '请选择' + attr.name.replace(/\s*/g, '')"
        @change="attr.dataChangeFunc && debouncedDataChangeFunc()"
      />
    </a-form-model-item>
  </x-form-col>
  <!--  区间选择器  -->
  <x-form-col v-else-if="attr.type === 'intervalPicker' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <x-interval-picker
        v-model="form[attr.model]"
        :mode="mode"
        :read-only="readOnly"
        :disabled="disabled && !readOnly"
        :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
        :start-placeholder="attr.startPlaceholder || '起始值'"
        :end-placeholder="attr.endPlaceholder || '结束值'"
        @blur="attr.inputOnBlurFunc && emitFunc(attr.inputOnBlurFunc, attr)"
      />
    </a-form-model-item>
  </x-form-col>
  <!--  车牌号选择  -->
  <x-form-col v-else-if="attr.type === 'licensePlate' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :style="
        layout === 'inline' && attr.occupyCol && attr.occupyCol > 1
          ? { width: `calc(100% - ${attr.occupyCol * 1.533}rem)` }
          : {}
      "
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <!--  如果配置了后置按钮插槽    -->
      <a-input
        v-if="mode === '查询'"
        v-model="form[attr.model]"
        autocomplete="off"
        :whitespace="true"
        :read-only="readOnly"
        :disabled="disabled && !readOnly"
        style="width: 100%"
        @blur="attr.inputOnBlurFunc && emitFunc(attr.inputOnBlurFunc, attr)"
        :placeholder="attr.placeholder ? attr.placeholder : '请输入' + attr.name.replace(/\s*/g, '')"
        :ref="rowIndex !== undefined ? `${rowIndex}-${attr.model}input` : `${attr.model}input`"
      />
      <x-license-plate
        v-else
        v-model="form[attr.model]"
        @change="attr.dataChangeFunc && debouncedDataChangeFunc()"
      ></x-license-plate>
    </a-form-model-item>
  </x-form-col>
  <!-- 录音 -->
  <x-form-col v-else-if="attr.type === 'recording' && show" :labelCol="labelCol"  >
    <recording ref="recording" @recordingData="recordingData"></recording>
  </x-form-col>
  <!-- 表格录入 -->
  <x-form-col v-else-if="attr.type === 'rowEdit' && show" :labelCol="labelCol"   :mode="mode" :layout="layout" :attrType="attr.type">
    <a-form-model-item
      v-bind="bindOther"
      :rules="effectiveRules"
      :ref="attr.model"
      :label="showLabel ? attr.name : undefined"
      :prop="attr.prop ? attr.prop : attr.model"
    >
      <x-form-table
        :key="'childTable_' + attr.model"
        :title="attr.name"
        :queryParamsName="attr.crud"
        :localEditMode="true"
        :fixed-query-form="childTableFixedQueryForm(attr)"
        :service-name="serviceName"
        @hook:mounted="h => onComponentMounted(h, attr)"
        :ref="'childXFormTable_' + attr.model"
      ></x-form-table>
    </a-form-model-item>
  </x-form-col>
</template>
<script>
import { debounce } from 'ant-design-vue/lib/vc-table/src/utils'
import XFormCol from '@vue2-client/base-client/components/common/XFormCol'
import XBadge from '@vue2-client/base-client/components/common/XBadge'
import CitySelect from '@vue2-client/base-client/components/common/CitySelect'
import PersonSetting from '@vue2-client/base-client/components/common/PersonSetting'
import AddressSearchCombobox from '@vue2-client/base-client/components/common/AddressSearchCombobox'
import Upload from '@vue2-client/base-client/components/common/Upload'
import moment from 'moment'
import { runLogic, getConfigByNameAsync } from '@vue2-client/services/api/common'
import * as util from '@vue2-client/utils/util'
import XTreeSelect from '@vue2-client/base-client/components/common/XForm/XTreeSelect'
import { searchToListOption, searchToOption } from '@vue2-client/services/v3Api'
import { mapState } from 'vuex'
import { executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'
import XLicensePlate from '@vue2-client/base-client/components/common/XLicensePlate/XLicensePlate.vue'
import XStatusButton from './XStatusButton.vue'
import XClickChangeBtn from './itemComponent/XClickChangeBtn'
import 'moment/locale/zh-cn'
import XFormDatePicker from '@vue2-client/base-client/components/common/XDatePicker/index.vue'
import XIntervalPicker from '@vue2-client/base-client/components/common/XIntervalPicker/XIntervalPicker.vue'
import XRate from '@vue2-client/base-client/components/common/XRate/index.vue'
import { post } from '@vue2-client/services/api/restTools'
import ColorPickerCombobox from '@vue2-client/base-client/components/common/ColorPickerCombobox/ColorPickerCombobox.vue'
import { createSelectValueTypeHandler } from '@vue2-client/base-client/plugins/selectValueTypeHelper'

export default {
  name: 'XFormItem',
  components: {
    XFormDatePicker,
    XFormTable: () => import('@vue2-client/base-client/components/common/XFormTable/XFormTable.vue'),
    Recording: () => import('@vue2-client/base-client/components/common/Recording/Recording.vue'),
    XReport: () => import('@vue2-client/base-client/components/common/XReportGrid/XReport.vue'),
    XLicensePlate,
    XTreeSelect,
    XFormCol,
    XBadge,
    CitySelect,
    PersonSetting,
    AddressSearchCombobox,
    Upload,
    XStatusButton,
    XClickChangeBtn,
    XIntervalPicker,
    XRate,
    ColorPickerCombobox
  },
  data() {
    // 检索去抖
    this.fetchFunction = debounce(this.fetchFunction, 800)
    // 初始化selectValueType处理器
    this.selectValueTypeHandler = createSelectValueTypeHandler(this)
    return {
      option: [],
      // 最后检索版本
      lastFetchId: 0,
      // 检索中
      searching: false,
      searchResult: '',
      optionForFunc: [],
      // 控制当前表单项是否展示
      show: true,
      // moment
      moment,
      // 行选择器浮层是否显示
      rowChoosePopoverVisible: false,
      // 行选择器CRUD固定查询值
      rowChooseFixedQueryValue: undefined,
      bindOther: {}
    }
  },
  props: {
    attr: {
      type: Object,
      default: () => {
        return {}
      }
    },
    form: {
      type: Object,
      required: true
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    readOnly: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    mode: {
      type: String,
      default: () => {
        return '查询'
      }
    },
    files: {
      type: Array,
      default: () => {
        return []
      }
    },
    signs: {
      type: Array,
      default: () => {
        return []
      }
    },
    images: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 是否启用时间弹出到最外层
    enablePopupToBody: {
      type: Boolean,
      default: false
    },
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
    // 调用logic获取数据源的追加参数
    getDataParams: {
      type: Object,
      default: undefined
    },
    // 布局
    layout: {
      type: String,
      default: 'horizontal'
    },
    // 环境
    env: {
      type: String,
      default: () => {
        return 'prod'
      }
    },
    // 设置表单值
    setForm: {
      type: Function,
      default: val => {
        console.log(val)
      }
    },
    showLabel: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    labelCol: {
      type: Object,
      default: () => {
        return { span: 8 }
      }
    },
    rules: {
      type: Array,
      default: () => {
        return undefined
      }
    },
    // 行索引（行编辑模式下使用）
    rowIndex: {
      type: Number,
      default: undefined
    }
  },
  provide() {
    return {
      FormItemContext: this
    }
  },
  async created() {
    this.init()
    if (
      this.attr.keyName &&
      (this.attr?.keyName?.toString().indexOf('async ') !== -1 ||
        this.attr?.keyName?.toString()?.indexOf('function') !== -1)
    ) {
      this.debouncedUpdateOptions = debounce(this.updateOptions, 200)
    }
    if (this.attr.dataChangeFunc) {
      this.debouncedDataChangeFunc = debounce(this.dataChangeFunc, 200)
      // 执行一次
      this.dataChangeFunc(true)
    }
    if (this.attr.showFormItemFunc) {
      this.debouncedShowFormItemFunc = debounce(this.showFormItemFunc, 100)
      // 执行一次
      this.showFormItemFunc()
    }
    if (this.attr.showQueryFormItemFunc) {
      this.debouncedShowQueryFormItemFunc = debounce(this.showQueryFormItemFunc, 100)
      // 执行一次
      this.showQueryFormItemFunc()
    }
    // 人员联动框增加监听
    if (
      this?.attr?.keyName?.toString()?.startsWith('search@根据表单项[') &&
      this?.attr?.keyName?.toString().endsWith(']联动人员')
    ) {
      this.debouncedUserLinkFunc = debounce(() => this.updateResOptions('人员'), 200)
    }
    if (
      this?.attr?.keyName?.toString()?.startsWith('search@根据表单项[') &&
      this?.attr?.keyName?.toString().endsWith(']联动部门')
    ) {
      this.debouncedDepLinkFunc = debounce(() => this.updateResOptions('部门'), 200)
    }
    // xTreeSelect 自己调用 mounted
    if (this.attr.type !== 'treeSelect') {
      this.$emit('mounted', this.attr)
    }
  },
  computed: {
    ...mapState('account', { currUser: 'user', curRoles: 'roles', curPermissions: 'permissions' }),
    /**
     * 合并 attr.tempRequired 的必填规则，用于自定义校验（customJs）动态显示红星
     * tempRequired 由 XAddNativeForm.runCustomValidationForDisplay 根据校验结果设置
     * 未开 tempRequired 时直接返回 this.rules（含 undefined），以便 a-form-model-item 合并表单级 rules；勿用 || [] 挡住 FormContext.rules
     */
    effectiveRules() {
      if (this.attr.tempRequired) {
        const selectTypes = ['select', 'checkbox', 'radio', 'treeSelect', 'file', 'image', 'citySelect', 'addressSearch', 'personSetting']
        const msg = selectTypes.includes(this.attr.type) ? '请选择' + this.attr.name : '请输入' + this.attr.name
        return [...(this.rules || []), { required: true, message: msg }]
      }
      return this.rules
    },
    queryParamsName() {
      if (this.attr.keyName.startsWith('function')) {
        // 调用异步函数获取内容
        const obj = executeStrFunctionByContext(this, this.attr.keyName, [
          this.form,
          runLogic,
          this.mode,
          getConfigByNameAsync
        ])
        // 处理同步返回值
        return this.handleQueryParamsResult(obj)
      } else if (this.attr.keyName.startsWith('async ')) {
        console.warn('此处不支持异步操作')
        return ''
      } else {
        // 按现有方式处理
        return this.attr.keyName.split('@')[this.attr.keyName.split('@').length - 1]
      }
    },
    // 判断弹出时是否Cover，弹出只支持Cover以及CRUD
    isCover() {
      // 如果 queryParamsName 为空，返回空
      if (!this.queryParamsName) {
        return false
      }
      const result = this.queryParamsName.endsWith('Cover')
      return result
    },
    copyForm() {
      return JSON.parse(JSON.stringify(this.form))
    }
  },
  watch: {
    attr: {
      handler() {
        this.init()
      },
      deep: true
    },
    copyForm: {
      handler(newVal, oldVal) {
        if (
          this.attr.keyName &&
          (this.attr.keyName.toString().indexOf('async ') !== -1 ||
            this.attr.keyName.toString().indexOf('function') !== -1)
        ) {
          this.debouncedUpdateOptions()
        }
        // 如果有自定义是否展示表单项函数
        if (this.attr.showFormItemFunc) {
          this.debouncedShowFormItemFunc()
        }
        // 如果有自定义是否展示查询表单项函数
        if (this.attr.showQueryFormItemFunc) {
          this.debouncedShowQueryFormItemFunc()
        }
        // 地址搜索框赋值
        if (this.attr.type === 'addressSearch' || this.attr.type === 'coordinateSearch') {
          this.$refs.addressSearchCombobox.addressInput = this.form[this.attr.model]
        }
        // 数据源来自人员联动时更新数据
        if (
          this?.attr?.keyName?.toString()?.startsWith('search@根据表单项[') &&
          this?.attr?.keyName?.toString().endsWith(']联动人员')
        ) {
          const startIndex = this.attr.keyName.indexOf('[') + 1
          const endIndex = this.attr.keyName.indexOf(']', startIndex)
          const fromModel = this.attr.keyName.substring(startIndex, endIndex).replace('.', '_')
          if (JSON.stringify(newVal[fromModel]) !== JSON.stringify(oldVal[fromModel])) {
            this.debouncedUserLinkFunc()
          }
        }
        // 数据源来自部门联动时更新数据
        if (
          this?.attr?.keyName?.toString()?.startsWith('search@根据表单项[') &&
          this?.attr?.keyName?.toString().endsWith(']联动部门')
        ) {
          const startIndex = this.attr.keyName.indexOf('[') + 1
          const endIndex = this.attr.keyName.indexOf(']', startIndex)
          const fromModel = this.attr.keyName.substring(startIndex, endIndex).replace('.', '_')
          if (JSON.stringify(newVal[fromModel]) !== JSON.stringify(oldVal[fromModel])) {
            this.debouncedDepLinkFunc()
          }
        }
      },
      deep: true
    }
  },
  inject: {
    getComponentByName: {
      default: () => () => {
        console.warn('getComponentByName is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    registerComponent: {
      default: () => () => {
        console.warn('registerComponent is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    getSelf: {
      default: () => () => {
        console.warn('getSelf is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    XFormContext: {
      default: () => () => {
        console.warn('XFormContext is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    setRequired: {
      default: () => () => {
        console.warn('setRequired is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    removeRequired: {
      default: () => () => {
        console.warn('removeRequired is not provided')
        return null // 或者返回一个默认的函数
      }
    },
    // 表单组上下文（通过注入传递）
    formGroupContext: {
      default: null
    },
    // 外部数据（通过 XAddNativeForm 的 provide 传递）
    _getExtData: {
      default: () => ({})
    }
  },
  methods: {
    /**
     * 获取外部数据
     * @returns {Object} 外部扩展数据对象 比如收费表单中俄的 用户信息要参与表单判断
     */
    getExtData() {
      return (this._getExtData && typeof this._getExtData === 'function') ? this._getExtData() : {}
    },
    // 处理 queryParams 结果并更新 rowChooseFixedQueryValue
    handleQueryParamsResult(obj) {
      let configName = ''
      if (obj && typeof obj === 'object') {
        // obj 是一个对象，并且不是数组
        if (Object.prototype.hasOwnProperty.call(obj, 'configName')) {
          configName = obj?.configName
        }
        if (Object.prototype.hasOwnProperty.call(obj, 'fixedQueryForm')) {
          if (obj?.fixedQueryForm && typeof obj?.fixedQueryForm === 'object') {
            this.rowChooseFixedQueryValue = Object.assign({}, this.rowChooseFixedQueryValue, obj.fixedQueryForm)
          }
        }
      } else if (obj && typeof obj === 'string') {
        configName = obj
      }
      return configName
    },
    // 根据selectValueType预处理options数据
    processOptionsForValueType(options) {
      return this.selectValueTypeHandler.processOptions(options, this.attr.selectValueType)
    },

    // 处理both模式的数据，为表单添加label字段
    processBothModeData() {
      this.selectValueTypeHandler.processBothMode()
    },
    // 获取所有表单组数据（通过 formGroupContext）
    getAllFormData() {
      if (this.formGroupContext && this.formGroupContext.allFormData) {
        return this.formGroupContext.allFormData
      }
      return {}
    },

    // 根据value查找对应的label（支持单选和多选）
    findLabelByValue(value) {
      return this.selectValueTypeHandler.findLabel(value, this.option)
    },

    // 统一的表单项change处理逻辑
    handleFormItemChange() {
      // 处理both模式
      if (this.attr.selectValueType === 'both') {
        this.$nextTick(() => {
          this.selectValueTypeHandler.processBothMode()
        })
      }
      // 处理label模式
      if (this.attr.selectValueType === 'label') {
        this.$nextTick(() => {
          this.selectValueTypeHandler.processLabelMode()
        })
      }
      // 处理扩展字段
      this.selectValueTypeHandler.processExtField()
      // 处理原有的dataChangeFunc
      if (this.attr.dataChangeFunc) {
        this.debouncedDataChangeFunc()
      }
    },

    // Select组件change处理
    handleSelectChange(a,b,c) {
      console.warn(a,b,c)
      this.handleFormItemChange()
    },

    // Checkbox组件change处理
    handleCheckboxChange() {
      this.handleFormItemChange()
    },

    // Radio组件change处理
    handleRadioChange() {
      this.handleFormItemChange()
    },

    // TreeSelect组件change处理（通过XTreeSelect组件回调）
    handleTreeSelectChange() {
      this.handleFormItemChange()
    },

    // 把内部的crud表单录入放到表单中，以便外部可以调用
    onComponentMounted(h, attr) {
      console.log('crud表单', h)
      if (attr.crud) {
        this.registerComponent(attr.model, this.$refs['childXFormTable_' + attr.model])
      }
    },
    childTableFixedQueryForm(item) {
      console.log('传递的form', this.form)
      if (this.modifyModelData?.primaryKeyData) {
        const fixedForm = {}
        fixedForm[item.childTableForeignKeyName] = Object.values(this.modifyModelData.primaryKeyData)[0]
        return fixedForm
      }
      return null
    },
    // 动态生成事件绑定对象
    generateDynamicEvents(inputOnAfterFunc, attr) {
      const events = {}
      const states = this.parseStates(attr.inputOnAfterName, inputOnAfterFunc)

      states.forEach(state => {
        // 动态绑定事件名到 emitFunc
        events[state.event] = () => {
          console.info('事件名', state.event)
          this.emitFunc(state.event, attr)
        }
      })

      return events // 返回 { state1Event: handler, state2Event: handler, ... }
    },
    parseStates(input, events) {
      const eventNames = events.split('|')
      return input.split('|').map((label, index) => ({
        label,
        event: eventNames[index] // 如果没有提供事件名称，则使用默认值
      }))
    },
    focusInput() {
      if (this.attr.defaultFocus) {
        this.$nextTick(h => {
          const el = this.$refs[`${this.attr.model}input`]?.$el
          let inputEl
          if (el) {
            if (el.tagName.toLowerCase() === 'input') {
              inputEl = el
            } else {
              inputEl = el.querySelector('input')
            }
          }
          if (inputEl) {
            inputEl.focus()
            if (inputEl.type === 'number') {
              if (inputEl.valueAsNumber) {
                inputEl.setSelectionRange(0, inputEl.valueAsNumber.toString().length)
              }
            } else {
              if (inputEl.value) {
                inputEl.setSelectionRange(0, inputEl.value.length)
              }
            }
          }
        })
      }
    },
    // 更新人员下拉框数据
    async updateResOptions(type) {
      if (
        this?.attr?.keyName?.toString()?.startsWith('search@根据表单项[') &&
        this?.attr?.keyName?.toString()?.endsWith(`]联动${type}`)
      ) {
        const startIndex = this.attr.keyName.indexOf('[') + 1
        const endIndex = this.attr.keyName.indexOf(']', startIndex)
        const fromModel = this.attr.keyName.substring(startIndex, endIndex).replace('.', '_')
        // 获取表单字段的实际值（优先使用originData中的原始值）
        const rawFieldValue =
          this.form.originData && this.form.originData[fromModel]
            ? this.form.originData[fromModel]
            : this.form[fromModel]

        // 确保数据为数组格式（用于filter参数）
        const filterValues = Array.isArray(rawFieldValue) ? rawFieldValue : [rawFieldValue]
        if (fromModel?.length && filterValues?.length) {
          const searchData = {
            source: `获取${type}`,
            userid: this.currUser.id,
            filter: filterValues,
            filterType: fromModel.indexOf('org') > -1 ? 'org' : 'dep'
          }
          const tempArray = []
          await searchToListOption(searchData, res => {
            this.getDataCallback(
              res.filter(h => {
                if (fromModel.indexOf('org') > -1) {
                  if (type === '部门') {
                    if (
                      filterValues?.includes(h.orgid || h.f_organization_id) ||
                      filterValues?.includes(h.parentid) ||
                      tempArray.includes(h.parentid)
                    ) {
                      tempArray.push(h.value)
                      return true
                    }
                    return false
                  } else {
                    return filterValues?.includes(h.orgid || h.f_organization_id || h.parentid)
                  }
                } else {
                  return filterValues?.includes(h?.parentid)
                }
              })
            )
          })
        }
      }
    },
    // js 函数作为数据源
    async updateOptions() {
      if (
        this.attr.keyName &&
        (this.attr.keyName.indexOf('async ') !== -1 || this.attr.keyName.indexOf('function ') !== -1)
      ) {
        const rawOptions = await executeStrFunctionByContext(this, this.attr.keyName, [
          this.form,
          runLogic,
          this.mode,
          getConfigByNameAsync,
          post
        ])
        // 根据selectValueType预处理options数据
        this.optionForFunc = this.processOptionsForValueType(rawOptions)
        const option = this.optionForFunc
        this.getDataCallback(option)
      }
    },
    // f 是否是初始化执行的
    async dataChangeFunc(f = false) {
      if (this.attr.dataChangeFunc) {
        await executeStrFunctionByContext(this, this.attr.dataChangeFunc, [
          this.form,
          this.setForm,
          this.attr,
          util,
          this.mode,
          runLogic,
          getConfigByNameAsync,
          f
        ])
      }
    },
    async showFormItemFunc() {
      if (this.attr.showFormItemFunc) {
        const obj = executeStrFunctionByContext(this, this.attr.showFormItemFunc, [
          this.form,
          this.setForm,
          this.attr,
          util,
          this.mode,
          this.curPermissions,
          this.curRoles
        ])
        // 判断是 bool 还是  obj  兼容
        if (typeof obj === 'boolean') {
          this.show = obj
        } else if (obj && typeof obj === 'object') {
          console.warn('showFormItemFunc obj', obj)
          // obj 是一个对象，并且不是数组
          if (Object.prototype.hasOwnProperty.call(obj, 'show')) {
            this.show = obj?.show
          }
          if (Object.prototype.hasOwnProperty.call(obj, 'readOnly')) {
            this.readOnly = obj?.readOnly
          }
          if (Object.prototype.hasOwnProperty.call(obj, 'disabled')) {
            this.disabled = obj?.disabled
          }
        }
      } else {
        this.show = true
      }
    },
    async showQueryFormItemFunc() {
      if (this.attr.showQueryFormItemFunc) {
        const obj = executeStrFunctionByContext(this, this.attr.showQueryFormItemFunc, [
          this.form,
          this.setForm,
          this.attr,
          util,
          this.mode,
          this.curPermissions,
          this.curRoles
        ])
        // 判断是 bool 还是  obj  兼容
        if (typeof obj === 'boolean') {
          this.show = obj
        } else if (obj && typeof obj === 'object') {
          // obj 是一个对象，并且不是数组
          if (Object.prototype.hasOwnProperty.call(obj, 'show')) {
            this.show = obj?.show
          }
          if (Object.prototype.hasOwnProperty.call(obj, 'readOnly')) {
            this.readOnly = obj?.readOnly
          }
          if (Object.prototype.hasOwnProperty.call(obj, 'disabled')) {
            this.disabled = obj?.disabled
          }
        }
      } else {
        this.show = true
      }
    },
    init() {
      // flex赋值逻辑已移至XFormCol组件内部处理
      // 不再在此处设置attr.flex，由XFormCol根据mode、layout、attrType自动计算
      if (this.attr.keyName && typeof this.attr.keyName === 'string') {
        if (this.attr.keyName.indexOf('logic@') !== -1) {
          const data = Object.assign(this.getExtData(), { serviceName: process.env.VUE_APP_SYSTEM_NAME })
          this.getData(data, res => this.getDataCallback(res))
        } else if (this.attr.keyName.indexOf('search@') !== -1) {
          // `tool.getFullTree(this.getRights().where(row.getType()==$organization$))`
          // 判断是否根据角色查询
          let source = this.attr.keyName.substring(7)
          const userid = this.currUser.id
          let roleName = 'roleName'
          if (source.startsWith('根据角色[') && source.endsWith(']获取人员')) {
            const startIndex = source.indexOf('[') + 1
            const endIndex = source.indexOf(']', startIndex)
            roleName = source.substring(startIndex, endIndex)
            source = '根据角色获取人员'
          }
          const searchData = { source, userid, roleName }
          // 判断是否根据某个表单项联动 仅返回列表结构并筛选
          if (source.startsWith('根据表单项[') && source.endsWith(']联动人员')) {
            this.updateResOptions('人员')
          } else if (source.startsWith('根据表单项[') && source.endsWith(']联动部门')) {
            this.updateResOptions('部门')
          } else if (this.attr.type === 'select' || this.attr.type === 'checkbox') {
            // 仅获取最内层数据
            searchToListOption(searchData, res => this.getDataCallback(res))
          } else {
            // 其他资源通用逻辑
            searchToOption(searchData, res => this.getDataCallback(res))
          }
        } else if (this.attr.keyName.indexOf('async ') !== -1 || this.attr.keyName.indexOf('function ') !== -1) {
          this.updateOptions()
        } else if (this.attr.keyName.indexOf('systemParam@') !== -1 && this.attr.keyName.length >= 12 && this.attr.keyName.substring(0, 12) === 'systemParam@') {
          const configName = this.attr.keyName.substring(12)
          if (configName && configName !== 'undefined' && this.currUser.appdata && this.currUser.appdata.params) {
            this.getDataCallback(this.currUser.appdata.params[configName])
          }
        } else {
          let configName
          if (this.attr.keyName.indexOf('config@') !== -1) {
            configName = this.attr.keyName.substring(7)
          } else {
            configName = this.attr.keyName
          }
          if (configName && configName !== 'undefined') {
            this.$appdata.getDictByKey(
              configName,
              this.serviceName,
              res => this.getDataCallback(res),
              this.env === 'dev'
            )
          }
        }
      } else if (this.attr.keys) {
        // 对静态配置的keys也进行预处理
        this.getDataCallback(this.attr.keys)
      }
      this.focusInput()
    },
    addressSearchComboboxSelect(data) {
      this.form = Object.assign(this.form, JSON.parse(data))
    },
    onDivisionsChange(data) {
      this.emitFunc('addressSearchComboboxSelect', {
        key: this.attr.model,
        value: data
      })
    },
    getDataCallback(res) {
      // 根据selectValueType预处理options数据
      this.option = this.processOptionsForValueType(res)

      if (this.attr.type === 'treeSelect') {
        this.$nextTick(() => {
          this.$refs.xTreeSelect.init({
            option: this.option,
            form: this.form,
            queryType: this.attr.queryType,
            name: this.attr.name,
            model: this.attr.model,
            mode: this.mode,
          })
        })
      } else if (this.attr.type === 'radio' || ['radioGroup', 'clickChange'].includes(this.attr.showMode)) {
        this.initRadioValue()
      }
    },
    initRadioValue() {
      const model = this.attr.model
      if (
        this.mode === '新增/修改' &&
        (this.form[model] === undefined || this.form[model] === null) &&
        !this.attr.prop
      ) {
        if (this.attr.keys && this.attr.keys.length > 1) {
          this.form[model] = this.attr.keys[0].value
        } else if (this.option.length > 1) {
          this.form[model] = this.option[0].value
        }
      }
    },
    // 文件框时设置上传组件的值
    setFiles(fileIds) {
      if (!this.form[this.attr.model]) {
        this.form[this.attr.model] = []
      }
      this.form[this.attr.model] = [...fileIds]
    },
    // 懒加载检索方法
    fetchFunction(value) {
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.option = []
      this.searching = true
      this.getData(
        {
          word: value
        },
        res => {
          if (fetchId !== this.lastFetchId) {
            return
          }
          this.option = res
          this.searching = false
        }
      )
    },
    // 获取数据
    getData(value, callbackFun) {
      if (value !== '') {
        const logicName = this.attr.keyName
        const logic = logicName.substring(6)
        // 调用logic前设置参数
        if (this.getDataParams && this.getDataParams[this.attr.model]) {
          Object.assign(value, this.getDataParams[this.attr.model])
        }
        // 获取下拉框数据，启用请求复用策略（相同请求共享结果）
        runLogic(
          logic,
          Object.assign(value, {
            orgId: this.currUser.orgid,
            userId: this.currUser.id
          }),
          this.serviceName,
          this.env === 'dev',
          {
            dedupe: true,
            dedupeStrategy: 'reuse'
          }
        )
          .then(res => {
            callbackFun(res)
          })
          .catch(e => {
            // 重复请求被复用时不会进入 catch，只有真正失败才会
            if (e.code !== 'ERR_DUPLICATE_REQUEST') {
              callbackFun([])
              console.error('获取数据失败：' + e)
            }
          })
      }
    },
    filterOption(input, option) {
      const child = option.componentOptions.children[0]
      if (child.text) {
        return child.text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      } else if (child.elm.innerText) {
        return child.elm.innerText.toLowerCase().indexOf(input.toLowerCase()) >= 0
      } else {
        return child.child.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
    },
    // 表单项变更函数中调用 控制表单组中表单项组名为 groupName 的表单是否展示
    // func：x-form-show（显示）/x-form-no-show（不显示）
    emitShowFormFunc(func, groupName, data) {
      this.emitFunc(func, groupName, data)
    },
    emitFunc(func, data) {
      if(func === 'x-form-show' || func === 'x-form-no-show') {
        this.$emit('x-form-item-emit-func', func, data)
      } else {
        this.$emit('x-form-item-emit-func', func, data, data?.model ? this.form[data.model] : this.form)
      }
    },
    itemMounted(h) {
      this.$emit('mounted', h)
    },
    rowChoose(rows) {
      this.$emit('rowChoose', rows, this.attr, this.closeRowChooseInput)
    },
    searchRowChooseData() {
      if (this.searching) {
        return
      }
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.searching = true
      if (fetchId !== this.lastFetchId) {
        return
      }
      this.rowChooseFixedQueryValue = []
      this.rowChooseFixedQueryValue[this.attr.model] = this.form[this.attr.model]
      this.$nextTick(() => {
        this.$refs.rowChooseTable.refresh(true)
      })
    },
    showCloseRowChooseInput() {
      this.rowChoosePopoverVisible = true
    },
    closeRowChooseInput() {
      this.rowChoosePopoverVisible = false
    },
    rowChooseSearchAfterQuery() {
      this.searching = false
    },
    // 获取 recording 转换后的数据
    getRecodingData() {
      return this.$refs.recording.getRecordingData()
    },
    recordingData(data) {
      this.emitFunc('recordingData', data)
    },
    getPopupContainer(triggerNode) {
      // 行编辑模式特殊处理
      if (typeof this.$vnode?.key === 'string' && this.$vnode.key.startsWith('editRow')) {
        // 限制最多向上查找5层
        let parent = triggerNode.parentNode
        let depth = 0
        const maxDepth = 10

        while (parent && parent !== document.body && depth < maxDepth) {
          if (parent.tagName === 'TBODY') {
            return parent
          }
          parent = parent.parentNode
          depth++
        }
        // 如果5层内没找到，回退到body
        return document.body
      }
      return triggerNode.parentNode
    },
    colorPickerComboboxSelect(val) {
      this.form[this.attr.model] = val
    }
  }
}
</script>

<style lang="less" scoped>
.custom-dropdown {
  position: absolute;
  z-index: 1050;
}

.multiple_select {
  vertical-align: middle;
  :deep(.ant-select-selection) {
    max-height: 32px;
    overflow-y: scroll;
  }
}
</style>
