<template>
  <div class="inputs ht-form-inputs__block ht-form__sunOrSub">
    <template v-if="inputWriteable && isSubCellReadOnly">
      <input
        v-validate="inputValidate"
        :value="inputVal"
        type="hidden"
        :name="inputName"
        :data-vv-as="name"
      />

      <div
        class="sub-table-cell-readonly"
        @click="handleCellClick('', initFun)"
      >
        <span v-if="inputVal && inputVal.length" class="tag-wrap">
          <span
            v-for="(item, index) in inputVal"
            :key="item.value + index"
            class="el-tag el-tag--info el-tag--small"
            @click="showEditInput"
          >
            <span class="el-select__tags-text">{{ item.value }}</span>
          </span>
        </span>
      </div>
    </template>
    <template v-else>
      <el-tooltip
        v-if="!isMobile"
        :placement="tooltipplacement || defualtTooltipplacement"
        :disabled="
          inputWriteable && errors && !errors.has('custom-form.' + inputName)
        "
      >
        <div v-if="errors && errors.first" slot="content">
          {{ errors.first('custom-form.' + inputName) }}
        </div>
        <div
          v-if="inputWriteable"
          style="width: 100%"
          class="el-select"
          :class="{ 'has-value': !disabled && value }"
          @click="disabled || isQuickSearch ? '' : showEditInput"
        >
          <template v-if="!isHidenInput">
            <div
              v-if="!isQuickSearch"
              ref="tagSpans"
              class="el-select__tags"
              :class="disabled ? 'el-select__tags__disabled' : ''"
              :style="{
                width: 'calc(100% - ' + `${inputSuffixWidth}` + 'px)',
              }"
              @click.capture="disabled ? '' : showEditInput"
            >
              <span v-if="inputVal && inputVal.length" class="tag-wrap">
                <span
                  v-for="(item, index) in inputVal"
                  :key="item.value + index"
                  class="el-tag el-tag--info el-tag--small"
                  @click="showEditInput"
                >
                  <span class="el-select__tags-text">{{ item.value }}</span>
                  <i
                    v-if="inputWriteable && !disabled"
                    class="el-tag__close el-icon-close"
                    @click.stop="removeSelectOrg(index)"
                  ></i>
                </span>
                <!-- <el-tooltip
                v-if="inputVal && inputVal.length > 2"
                class="item"
                effect="dark"
                :content="inputTooltipName"
                placement="top"
                popper-class="tooltip-width"
              >
                <span
                  class="el-tag el-tag--info el-tag--small"
                  @click="showEditInput"
                >
                  <span class="el-select__tags-text">
                    + {{ inputVal.length - 2 }}
                  </span>
                </span>
              </el-tooltip> -->
              </span>
            </div>
            <div
              :class="[
                'el-input',
                'el-input--suffix',
                disabled ? 'is-disabled' : '',
              ]"
              style="display: flex; align-items: center"
              :style="inputSuffixStyle"
            >
              <input
                v-if="!isQuickSearch"
                ref="inputEl"
                v-model="inputVal"
                v-validate="inputValidate"
                type="text"
                readonly="readonly"
                :name="inputName"
                :data-vv-as="name"
                autocomplete="off"
                class="el-input__inner"
                :placeholder="placeholder"
                style="height: 32px"
                :style="inputSuffixStyle"
                @click="showEditInput"
              />
              <!-- 允许手动输入时 -->
              <el-input
                v-if="isAllowCustom && isEditInputShow && !isQuickSearch"
                ref="editInputRef"
                v-model="customValue"
                :clearable="disabled ? false : true"
                class="edit-input"
                :disabled="disabled"
                size="small"
                :style="{
                  right: inputSuffixWidth - 1 + 'px',
                  width: 'auto!important',
                  'min-height': inputSuffixHeight - 4 + 'px',
                  height: inputSuffixHeight - 4 + 'px',
                }"
                @blur="editInputBlur"
              ></el-input>
              <template v-if="isQuickSearch">
                <div
                  v-if="customDialogInit && customDialogInit.selectNum != 1"
                  style="width: inherit"
                >
                  <el-popover
                    ref="popoverRef"
                    v-model="visible"
                    :append-to-body="true"
                    placement="bottom"
                    :popper-class="`custom-query-Options`"
                  >
                    <div slot="reference">
                      <div
                        ref="tagSpans"
                        class="el-select__tags"
                        :class="disabled ? 'el-select__tags__disabled' : ''"
                        :style="{
                          width:
                            'calc(100% - ' + `${inputSuffixWidth - 20}` + 'px)',
                        }"
                      >
                        <span
                          v-if="inputVal && inputVal.length"
                          class="tag-wrap"
                        >
                          <span
                            v-for="(item, index) in inputVal"
                            :key="item.value + index"
                            class="el-tag el-tag--info el-tag--small"
                          >
                            <span class="el-select__tags-text">
                              {{ item.value }}
                            </span>
                            <i
                              v-if="inputWriteable && !disabled"
                              class="el-tag__close el-icon-close"
                              @click.stop="removeQuerySelectOrg(index)"
                            ></i>
                          </span>
                        </span>
                      </div>
                      <input
                        ref="inputEl"
                        v-model="inputVal"
                        v-validate="inputValidate"
                        type="text"
                        readonly="readonly"
                        :name="inputName"
                        :data-vv-as="name"
                        autocomplete="off"
                        class="el-input__inner"
                        :placeholder="placeholder"
                        style="height: 32px"
                        :style="{
                          right: inputSuffixWidth - 1 + 'px',
                          'min-height': inputSuffixHeight + 'px',
                        }"
                      />
                    </div>
                    <div style="padding: 10px">
                      <el-input
                        v-model="dropDownValue"
                        placeholder="请输入搜索关键词"
                        size="small"
                        suffix-icon="el-icon-search"
                        clearable
                        @input="querySearchAsync"
                      ></el-input>
                      <el-scrollbar class="custom-query-Options__scroll">
                        <template
                          v-if="templOptionsAry && templOptionsAry.length > 0"
                        >
                          <el-checkbox-group
                            v-for="(node, index) in templOptionsAry"
                            :key="`${node.key}${index}`"
                            v-model="selectedOptions"
                            @change="handleMultipleSelect(node.key)"
                          >
                            <el-checkbox
                              :label="node.key"
                              style="margin-top: 10px"
                            >
                              <div>
                                {{ node.value }}
                              </div>
                            </el-checkbox>
                          </el-checkbox-group>
                        </template>
                        <template
                          v-if="
                            querySearchOptions && querySearchOptions.length > 0
                          "
                        >
                          <el-checkbox-group
                            v-for="(node, index) in querySearchOptions"
                            :key="`${node.key}${index}`"
                            v-model="selectedOptions"
                            @change="handleMultipleSelect(node.key)"
                          >
                            <el-checkbox
                              :label="node.key"
                              style="margin-top: 10px"
                            >
                              <div>
                                {{ node.value }}
                              </div>
                            </el-checkbox>
                          </el-checkbox-group>
                        </template>
                        <p v-else class="el-select-dropdown__empty">无数据</p>
                      </el-scrollbar>
                      <add-item
                        v-if="isAllowCustom"
                        :placeholder="placeholder"
                        @addItem="addCustomItem"
                      ></add-item>
                    </div>
                  </el-popover>
                </div>
                <ht-select
                  v-else
                  ref="editInputRef"
                  v-model="customValue"
                  v-validate="inputValidate"
                  class="custom-query-select"
                  :filterable="true"
                  :allow-create="isAllowCustom"
                  :clearable="disabled ? false : true"
                  :disabled="disabled"
                  style="width: calc(100% - 56px)"
                  :options="querySearchOptions"
                  @visible-change="handleVisibleChange"
                  @change="handleSelect($event)"
                >
                  <template v-slot:querybox>
                    <div class="custom-query-search-input">
                      <el-input
                        v-model="dropDownValue"
                        placeholder="请输入搜索关键词"
                        size="small"
                        suffix-icon="el-icon-search"
                        clearable
                        @input="querySearchAsync"
                      ></el-input>
                    </div>
                  </template>
                  <template slot-scope="{ querySearchOptions }">
                    <el-option
                      v-for="(item, index) in querySearchOptions"
                      :key="item.key + index"
                      :label="item.value"
                      :value="item"
                    ></el-option>
                  </template>
                </ht-select>
              </template>
              <span
                ref="inputSuffix"
                class="el-input__suffix"
                :style="inputSuffixStyle"
                @click="showDialog"
              >
                <span
                  class="el-input__suffix-inner"
                  :class="{ 'has-clear-all': value }"
                >
                  <i
                    v-if="
                      inputWriteable &&
                      !disabled &&
                      !(customDialogInit && customDialogInit.selectNum == 1)
                    "
                    class="el-icon-circle-close clear-icon"
                    @click.stop="clear"
                  ></i>
                  <el-button
                    slot="append"
                    class="CustomDialog-right-button"
                    :disabled="disabled"
                    type="info"
                    size="mini"
                    :style="inputSuffixStyleButton"
                  >
                    <i
                      :class="
                        custdialog.icon
                          ? 'el-input__icon ' + custdialog.icon
                          : 'el-input__icon icon-duihuakuang'
                      "
                      :style="{
                        lineHeight: inputSuffixHeight + 'px',
                      }"
                    ></i>
                    {{ custdialog.name }}
                  </el-button>
                </span>
              </span>
            </div>
          </template>
          <template v-else>
            <div
              :class="[
                'el-input',
                'el-input--suffix',
                disabled ? 'is-disabled' : '',
              ]"
            >
              <input
                v-show="false"
                ref="inputEl"
                v-model="inputVal"
                v-validate="inputValidate"
                type="text"
                readonly="readonly"
                :name="inputName"
                :data-vv-as="name"
                autocomplete="off"
                class="el-input__inner"
                :placeholder="placeholder"
                :style="inputSuffixStyle"
                @click="showEditInput"
              />
              <span
                ref="inputSuffix"
                :style="inputSuffixStyle"
                @click="showDialog"
              >
                <span
                  class="el-input__suffix-inner"
                  :class="{ 'has-clear-all': value }"
                >
                  <el-button
                    slot="append"
                    class="CustomDialog-right-button-isHidenInput"
                    :disabled="disabled"
                    type="info"
                    size="mini"
                    :style="inputSuffixStyleButton"
                  >
                    <i
                      :class="
                        custdialog.icon
                          ? 'el-input__icon ' + custdialog.icon
                          : 'el-input__icon icon-duihuakuang'
                      "
                      :style="{
                        lineHeight: inputSuffixHeight + 'px',
                      }"
                    ></i>
                    {{ custdialog.name }}
                  </el-button>
                </span>
              </span>
            </div>
          </template>
        </div>
      </el-tooltip>
      <div v-if="inputWriteable && isMobile" class="mobile-cell__wrap">
        <!-- 校验 -->
        <input
          v-model="inputVal"
          v-validate="validateRules"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />

        <van-cell
          v-if="inputWriteable && isMobile"
          v-validate="!inputVal && validateRules"
          class="cell mobile-cell"
          :class="{ 'mobile-disabled-cell': disabled }"
          :name="inputName"
          :data-vv-as="name"
          title=" "
          @click="showDialog"
        >
          <div v-show="!isHidenInput" class="flex">
            <span v-if="inputVal && inputVal.length > 0" class="cell-text">
              <template v-for="(item, i) in inputVal">
                <span v-show="i > 0 && i < 3" :key="i">,</span>
                <span v-show="i < 3" :key="i">{{ item.value }}</span>
              </template>

              <span v-if="inputVal.length > 3">
                &nbsp;共{{ inputVal.length }}个
              </span>
            </span>
            <span v-else class="placeholder-class">
              {{ mobilePlaceholder('请选择') }}
            </span>
            <van-icon
              v-if="inputVal && inputVal.length > 0 && !disabled"
              name="clear"
              color="#bfbfbf"
              @click.stop="clear"
            />
          </div>
          <template v-if="!disabled" #right-icon>
            <van-icon
              v-if="isSearchSelect && !isHidenInput"
              name="play"
              class="right-arrow"
            />
            <template v-if="!isSearchSelect">
              <van-icon v-if="!isHidenInput" name="arrow" />
              <el-button v-else class="mobile-btn">
                <i v-if="custdialog.icon" :class="custdialog.icon"></i>
                <van-icon v-else name="more-o" />

                <span class="van-button__text">{{ custdialog.name }}</span>
              </el-button>
            </template>
          </template>
        </van-cell>
      </div>
      <van-cell
        v-if="!inputWriteable && isMobile"
        class="mobile-cell"
        @click="
          value && value.split(',').length > 3 ? showAllPeople(value) : ''
        "
      >
        <template v-if="!isSearchSelect" #default>
          <span v-show="!isHidenInput">
            <span v-if="value" class="cell-text">
              <span v-if="value.split(',').length < 4">{{ value }}</span>
              <span v-else>
                {{ value.split(',').splice(0, 3).join(',') }}&nbsp;共{{
                  value.split(',').length
                }}人
              </span>
            </span>
            <span v-if="!value" class="placeholder-class"></span>
          </span>
        </template>
        <template
          v-if="!isHidenInput && value && value.split(',').length > 3"
          #right-icon
        >
          <span class="mobileCellRightIcon">
            <slot name="mobile-right-icon">
              <van-icon name="arrow" />
            </slot>
          </span>
        </template>
        <template v-if="isHidenInput" #right-icon>
          <van-button class="mobile-btn" disabled>
            <template #icon>
              <i v-if="custdialog.icon" :class="custdialog.icon"></i>
              <van-icon v-else name="more-o" />
            </template>
            {{ custdialog.name }}
          </van-button>
        </template>
      </van-cell>
      <span v-if="!inputWriteable && !isMobile">
        <template v-if="!isHidenInput">
          <span
            v-for="(item, index) in inputVal"
            :key="item.value + index"
            style="margin: 2px 6px 2px 0"
            class="el-tag--small"
            :class="[
              !inputWriteable && !disabled ? 'el-tag--light' : 'el-tag--info',
              !isPrintMode && 'el-tag',
            ]"
            :style="{
              'border-color': !inputWriteable && !disabled ? '#d9ecff' : '',
            }"
            @click.stop
          >
            <span
              v-if="hasHyperlink()"
              class="el-select__tags-text hyperlink_content"
              @click="openHyperlink"
            >
              {{ item.value }}
            </span>
            <span v-else class="el-select__tags-text">{{ item.value }}</span>
          </span>
        </template>

        <template v-else>
          <div
            :class="[
              'el-input',
              'el-input--suffix',
              disabled ? 'is-disabled' : '',
            ]"
          >
            <span ref="inputSuffix" :style="inputSuffixStyle">
              <span
                class="el-input__suffix-inner"
                :class="{ 'has-clear-all': value }"
              >
                <el-button
                  slot="append"
                  class="CustomDialog-right-button-isHidenInput"
                  :disabled="true"
                  type="info"
                  size="mini"
                  :style="inputSuffixStyleButton"
                >
                  <i
                    :class="
                      custdialog.icon
                        ? 'el-input__icon ' + custdialog.icon
                        : 'el-input__icon icon-duihuakuang'
                    "
                    :style="{
                      lineHeight: inputSuffixHeight + 'px',
                    }"
                  ></i>
                  {{ custdialog.name }}
                </el-button>
              </span>
            </span>
          </div>
        </template>
      </span>
    </template>

    <ht-custom-dialog-model
      v-show="permission === 'w'"
      ref="customDialogShow"
      :value-custom-data="value"
      :model-name="modelName"
      :custdialog="custdialog"
      :sub-index="subIndex"
      :sun-index="sunIndex"
      :sub-path="subPath"
      :current-sub-data="currentSubData"
      @calacInputSuffixHeight="calacInputSuffixHeight"
      @updateInput="updateInput"
    ></ht-custom-dialog-model>
    <ht-field-tail
      :field-name="inputName"
      :input-value="value"
      :hyperlink="hyperlink"
    />
    <span style="display: none">
      <slot name="labeldesc">{{ inputName }}</slot>
    </span>
    <!-- 超链接弹框 -->
    <ht-template-iframe-dialog ref="dialogIframe"></ht-template-iframe-dialog>
    <LookAllPeople v-if="isMobile" ref="LookAllPeople"></LookAllPeople>
  </div>
</template>
<script>
  import utils from '@/utils.js'
  import locale from '@/mixins/locale.js'
  import permission from '@/mixins/permission.js'
  import inputName from '@/mixins/inputName.js'
  import form from '@/mixins/form.js'
  import dialog from './customDialog.js'
  import mobileMode from '@/mixins/mobileMode.js'
  import HtFieldTail from '../../FieldTail/index'
  import hyperlinkHandler from '@/mixins/hyperlinkHandler.js'
  import LookAllPeople from '../../LookAllPeople/index'
  import dialogMixins from '@/mixins/customDialog.js'
  import AddItem from '../../Select/src/AddItem.vue'
  import tableFieldReadOnly from '@/mixins/tableFieldReadOnly.js'
  export default {
    name: 'HtCustomDialog',
    components: {
      HtFieldTail,
      LookAllPeople,
      AddItem,
    },
    mixins: [
      dialog,
      locale,
      inputName,
      permission,
      form,
      mobileMode,
      hyperlinkHandler,
      dialogMixins,
      tableFieldReadOnly,
    ],
    props: {
      value: String,
      single: {
        type: Boolean,
        default: false,
      },
      custdialog: Object,
      tooltipplacement: Object,
      subIndex: Number,
      sunIndex: Number,
      subPath: String,
      currentSubData: Array,
      isSearchSelect: {
        type: Boolean,
        default: false,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      isValidate: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        isEditInputShow: false,
        customValue: '',
        defualtTooltipplacement: 'bottom',
        dialogVisible: false, //打开树形输入动态参数值的对话框
        pageParam: {}, //树形对话框参数
        conditionfieldTree: [], //树形对话框条件字段
        data: {
          qxdd: {},
        },
        inputSuffixWidth: 59,
        quickSearch: '', //填写提示
        conditionBind: [], //参数查询字段
        nodeKey: 'ID_', //树形数据父Id
        customDialogShowList: false,
        customDialogShowTree: false,
        selectOrgProps: {
          label: 'name',
        },
        style: '', //对话框宽高
        selectOrgs: [],
        inputSuffixHeight: 32,
        customDialog: {},
        isCurrentChange: false, //是否不执行 orgTableSelection方法
        param: [], //绑定的表单字段
        treeList: [],
        writeable: true,
        timeout: null,
        // 用于对话框快捷搜索功能
        customDialogInit: null,
        querySearchOptions: [],
        selectList: [],
        isLoaded: false,
        visible: false,
        selectedOptions: [],
        templOptionsAry: [],
        isFirstLoad: true,
      }
    },
    computed: {
      validateRules() {
        return this.disabled && !this.isValidate ? '' : this.inputValidate
      },
      inputVal: function () {
        if (!this.value || this.value == '||[]') {
          this.calacInputSuffixHeight(this.isFirstLoad)
          this.isFirstLoad = false
          return null
        } else {
          let nameAry = this.value.split(',')
          if (this.value.indexOf('||') > 0) {
            nameAry = this.value.split('||')[0].split(',')
          }
          let result = []
          nameAry.forEach((m) => {
            let n = { value: m }
            result.push(n)
          })

          return result
        }
      },
      isAllowCustom() {
        return this.custdialog && this.custdialog.allowInput
      },
      isHidenInput() {
        return this.custdialog && this.custdialog.isHidenInput
      },
      isQuickSearch() {
        return this.custdialog && this.custdialog.isQuickSearch
      },
      inputTooltipName() {
        let data = this.inputVal.map((item) => item.value).join(',') || ''
        return data
      },
      inputSuffixStyle() {
        return {
          'min-height': this.inputSuffixHeight + 'px',
          lineHeight: this.inputSuffixHeight + 'px',
        }
      },
      inputSuffixStyleButton() {
        return {
          'min-height': this.inputSuffixHeight - 2 + 'px',
          lineHeight: this.inputSuffixHeight - 2 + 'px',
          height: 'calc(100% - 2px)',
          margin: this.isQuickSearch ? '0px' : '1px',
          border: this.isQuickSearch ? '1px solid #e4e7ed !important' : 'none',
        }
      },
    },
    watch: {
      value: {
        handler(val) {
          if (val) {
            this.customValue = val
            this.calacInputSuffixHeight()
          }
        },
        immediate: true,
      },
      inputVal: {
        handler(val) {
          this.$nextTick(() => {
            if (this.$refs.tagSpans && this.$refs.tagSpans.offsetHeight) {
              this.inputSuffixHeight = this.$refs.tagSpans.offsetHeight + 4
            }
          })
        },
        immediate: true,
        deep: true,
      },
      inputSuffixHeight: {
        handler(val) {},
      },
      customValue: {
        handler(val) {
          this.$emit('input', val)
        },
        immediate: true,
      },
      visible: {
        handler(val) {
          if (val) {
            this.handleVisibleChange(val)
          }
        },
        immediate: true,
      },
    },
    mounted() {
      this.$root.$on('online-form-resize', this.calacInputSuffixHeight)
      setTimeout(() => {
        const { subScopeEl } = utils.getSubScopeElAndIndex(this.$el)

        if (subScopeEl) {
          if (
            subScopeEl.getAttribute('row_readonly') == 'true' ||
            subScopeEl.getAttribute('row_readonly') === true
          ) {
            this.writeable = false
          } else {
            const className = Array.prototype.find.call(
              subScopeEl.classList,
              (item) => item.startsWith('row_readonly__')
            )
            if (className && className == 'row_readonly__true') {
              this.writeable = false
            }
          }
        }
        this.getCustomDialogSetting()
        this.calacInputSuffixHeight(true)
        //获取对话框按钮名称宽度
        this.calacInputSuffixWidth()
      }, 50)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.calacInputSuffixWidth)
    },
    methods: {
      //切换还原
      initFun() {
        this.visible = false

        this.calacInputSuffixHeight()
      },
      handleVisibleChange(visible) {
        if (visible && !this.isLoaded) {
          this.querySearchAsync()
          this.isLoaded = true
        }
      },
      showAllPeople(value) {
        this.$refs.LookAllPeople.showDialog(value)
      },
      editInputBlur() {
        this.$emit('input', this.customValue)
        this.isEditInputShow = false
      },
      showEditInput() {
        if (!this.isAllowCustom) {
          this.showDialog()
          return
        }
        if (this.isQuickSearch) {
          return
        }
        this.customValue = this.value
        this.isEditInputShow = true
        this.$nextTick(() => {
          this.$refs.editInputRef && this.$refs.editInputRef.focus()
        })
      },
      showDialog() {
        if (!this.inputWriteable || this.disabled) {
          return
        }
        this.$refs.customDialogShow.showDialog()
      },
      //单项删除
      removeSelectOrg(item) {
        this.inputVal.splice(item, 1)
        let value = ''
        this.inputVal.forEach((val) => {
          value += val.value + ','
        })
        if (value.length > 0) {
          value = value.substring(0, value.length - 1)
        } else {
          this.clear()
        }
        this.$emit('input', value)
        this.calacInputSuffixHeight()
        if (this.isMobile) {
          this.$refs.customDialogShow.$refs.customMobileDialogRef.removeSelectOrg(
            item
          )
        } else {
          this.$refs.customDialogShow.$refs.customDialogRef.removeSelectOrg(
            item
          )
        }
      },
      removeQuerySelectOrg(item) {
        this.inputVal.splice(item, 1)
        let value = ''
        this.inputVal.forEach((val) => {
          value += val.value + ','
        })
        if (value.length > 0) {
          value = value.substring(0, value.length - 1)
        } else {
          this.clear()
        }
        this.$emit('input', value)
        this.calacInputSuffixHeight()
      },
      //清空所有
      clear() {
        this.selectedOptions = []
        this.handleMultipleSelect()
        this.$emit('input', '')
        if (this.isMobile) {
          this.$refs.customDialogShow.$refs.customMobileDialogRef.clearAll()
        } else {
          this.$refs.customDialogShow.$refs.customDialogRef.clearAll()
        }
        this.calacInputSuffixHeight()
      },
      calacInputSuffixHeight(isValidateIgnore) {
        setTimeout(() => {
          if (!this.$refs.tagSpans) return
          if (this.$refs.tagSpans.offsetHeight) {
            this.inputSuffixHeight = this.$refs.tagSpans.offsetHeight + 4
          } else {
            this.inputSuffixHeight = 30
          }
          // 触发验证
          //  this.$validator.validate()
          if (!isValidateIgnore && this.$refs.inputEl) {
            this.$refs.inputEl.focus({
              preventScroll: true,
            })
            this.$refs.inputEl.blur()
          }
        }, 0)
        this.calacInputSuffixWidth()
      },
      calacInputSuffixWidth() {
        if (this.$refs.inputSuffix) {
          this.inputSuffixWidth = this.$refs.inputSuffix.offsetWidth
        }
        this.$nextTick(() => {
          if (this.$refs.inputEl && this.$refs.popoverRef) {
            const inputWidth = this.$refs.inputEl.offsetWidth
            this.$refs.popoverRef.popperWidth = inputWidth
            this.$refs.popoverRef.width = inputWidth
          }
        })
      },

      updateInput(data) {
        this.$emit('input', data)
      },
      getCustomDialogSetting() {
        var alias = this.custdialog.custDialog.alias
        this.$requestConfig
          .getCustomDialogByAlias(alias)
          .then((customDialog) => {
            this.customDialogInit = customDialog
            this.calacInputSuffixHeight(true)
          })
      },
      querySearchAsync() {
        var isSearchFieldExists = false
        this.custdialog.conditionfield.forEach((item) => {
          if (item.field === this.custdialog.quickSearchKeyWord) {
            isSearchFieldExists = true
          }
        })
        if (!isSearchFieldExists) {
          if (this.isMobile) {
            this.$notify({
              message: '快捷搜索字段不存在，请先在表单设计器配置',
              type: 'warning',
            })
          } else {
            this.$message({
              message: '快捷搜索字段不存在，请先在表单设计器配置',
              type: 'warning',
            })
          }
          return
        }
        let queryParams = JSON.parse(
          this.customDialogInit.conditionfield
        ).filter(
          (option) =>
            option.field.toLowerCase() ==
            this.custdialog.quickSearchKeyWord.toLowerCase()
        )
        let paramsData = []
        if (queryParams && queryParams.length) {
          //不分页查询
          paramsData.push({
            ...queryParams[0],
            field: this.custdialog.quickSearchKeyWord,
            bind: this.dropDownValue,
            operation: this.getOperation(queryParams[0].condition),
          })
        } else {
          //不分页查询
          paramsData.push({
            field: this.custdialog.quickSearchKeyWord,
            bind: this.dropDownValue,
          })
        }
        const formInst = utils.getOnlineFormInstance(this)
        const curData = formInst['data']
        this.getDialogData(
          this.customDialogInit,
          null,
          curData,
          false,
          null,
          paramsData,
          (rows) => {
            this.querySearchOptions = this.handleDialogResult(
              rows,
              this.custdialog.quickSearchKeyWord
            )
          }
        )
      },
      handleDialogResult(rows, fieldName) {
        var result = rows
        if (rows && rows.length > 0) {
          result = []
          rows.forEach((item) => {
            //忽略大小写比较
            Object.keys(item).forEach((objKey) => {
              if (objKey.toLowerCase() === fieldName.toLowerCase()) {
                const value = item[objKey]
                const key = item.hasOwnProperty('id_')
                  ? item.id_
                  : item.hasOwnProperty('ID_')
                  ? item.ID_
                  : item[objKey]
                result.push({ value, key, ...item })
              }
            })
          })
        }
        return result
      },
      handleSelect(item) {
        this.selectList = this.querySearchOptions.filter(
          (option) => option.key == item
        )
        this.syncInputValue()
      },
      handleMultipleSelect(item) {
        let data = [...this.querySearchOptions, ...this.templOptionsAry]
        this.selectList = data.filter((option) =>
          this.selectedOptions.includes(option.key)
        )
        this.syncInputValue()
      },
      //获取运算符号
      getOperation(old) {
        if (!old) {
          return ''
        }
        if (old == 'EQ') {
          return 'EQUAL'
        }
        if (old == 'LK') {
          return 'LIKE'
        }
        if (old == 'LFK') {
          return 'LIKE'
        }
        if (old == 'IN') {
          return 'IN'
        }
        if (old == 'BETWEEN') {
          return 'BETWEEN'
        }
      },
      // 同步选择结果
      syncInputValue() {
        let thisIndex = null //当前数据所在下标
        let parentIndex = null //父节点所在下标
        if (this.$parent.$el) {
          thisIndex = utils.getSubScopeElAndIndex(this.$parent.$el).index
          let subScopeEl = utils.getParentElementByClassNamePrefix(
            this.$parent.$parent.$el,
            'data-index'
          )
          if (subScopeEl) {
            const className = Array.prototype.find.call(
              subScopeEl.classList,
              (item) => item.startsWith('data-index__')
            )
            if (className) {
              parentIndex = className.split('__')[1]
            }
          }
          if (null == parentIndex) {
            subScopeEl = utils.getParentElementByAttribute(
              this.$parent.$parent.$el,
              'data-index'
            )
            if (subScopeEl && subScopeEl.attributes['data-index']) {
              parentIndex = subScopeEl.attributes['data-index'].value
            }
          }
        }
        var returnStr = JSON.parse(this.customDialogInit.resultfield)
        //拿到返回的字段
        var field = new Array([returnStr.length])
        var comment = new Array([returnStr.length])
        var str = []
        for (var i = 0; i < returnStr.length; i++) {
          field[i] =
            this.customDialogInit.dsType == 'dataSource'
              ? returnStr[i].field.toLowerCase()
              : returnStr[i].field
          comment[i] =
            this.customDialogInit.dsType == 'dataSource'
              ? returnStr[i].comment.toLowerCase()
              : returnStr[i].comment
        }
        var s = this.selectList
        if (this.customDialogInit.selectNum === 1) {
          var temp = ''
          // 当 s 存在或 s 的长度不为0时
          if (s && s.length) {
            for (var k = 0; k < comment.length; k++) {
              let sField = !utils.isEmpty(s[0][field[k]]) ? s[0][field[k]] : ''
              let encodeStr = encodeURIComponent(sField)
              temp += '"' + comment[k] + '":"' + encodeStr + '",'
            }
          }
          if (temp != '') {
            temp = '{' + temp.substring(0, temp.length - 1) + '}'
          }
          str.push(utils.parseToJson(temp))
        } else {
          if (s && s.length > 0) {
            for (var m = 0; m < s.length; m++) {
              var temp1 = ''
              for (var j = 0; j < comment.length; j++) {
                const _m = s[m]
                const _n = field[j]
                const _ov = _m[_n] //原始值
                const _uv = _m[_n.toUpperCase()] //field转大写后取到的值
                const _lv = _m[_n.toLowerCase()] //field转小写后取到的值
                const _fv =
                  _ov == null || _ov == undefined
                    ? _uv == null || _uv == undefined
                      ? _lv
                      : _uv
                    : _ov
                const encodeStr = encodeURIComponent(_fv)
                temp1 += '"' + comment[j] + '":"' + encodeStr + '",'
              }
              if (temp1 != '') {
                temp1 = '{' + temp1.substring(0, temp1.length - 1) + '}'
              }
              str.push(utils.parseToJson(temp1))
            }
          }
        }
        const pInst = utils.getOnlineFormInstance(this)
        this.custdialog.custDialog.mappingConf &&
          this.custdialog.custDialog.mappingConf != undefined &&
          this.custdialog.custDialog.mappingConf.forEach((con) => {
            this.custdialog.resultField.forEach((fillitem) => {
              if (fillitem.field == con.from || fillitem.comment == con.from) {
                var val = ''
                var from =
                  this.customDialogInit.dsType == 'dataSource'
                    ? con.from.toLowerCase()
                    : con.from
                str.forEach((item) => {
                  if (item) {
                    val +=
                      decodeURIComponent(item[from]) == 'undefined'
                        ? ''
                        : decodeURIComponent(item[from]) + ','
                  }
                })
                if (this.modelName == 'data.' + con['target'][0]) {
                  val = val.substring(0, val.length - 1)
                  let bindValue = utils.getValueByPath(
                    pInst,
                    'data.' + con['target'][0],
                    thisIndex || thisIndex === 0 ? thisIndex : null
                  )
                  if (fillitem && fillitem.fillBackType == 2 && bindValue) {
                    return
                  } else {
                    utils.setValueByPath(
                      pInst,
                      'data.' + con['target'][0],
                      val,
                      thisIndex
                    )
                  }
                } else if (
                  this.modelName &&
                  this.modelName.startsWith('searchForm.')
                ) {
                  let prePath = pInst['searchForm'] ? '' : 'data.'
                  let bindValue = utils.getValueByPath(
                    pInst,
                    prePath + 'searchForm.' + con['target'][0],
                    thisIndex || thisIndex === 0 ? thisIndex : null
                  )
                  if (fillitem && fillitem.fillBackType == 2 && bindValue) {
                    return
                  } else {
                    utils.setValueByPath(
                      pInst,
                      prePath + 'searchForm.' + con['target'][0],
                      val.substring(0, val.length - 1),
                      thisIndex
                    )
                  }
                } else if (this.modelName && this.modelName == 'customDialog') {
                  const _val = val.substring(0, val.length - 1)
                  //自定义对话框往model中写入selectorConfig
                  let bindValue = utils.getValueByPath(
                    pInst,
                    'selectorConfig.' + con['target'][0],
                    thisIndex || thisIndex === 0 ? thisIndex : null
                  )
                  if (fillitem && fillitem.fillBackType == 2 && bindValue) {
                    return
                  } else {
                    utils.setValueByPath(
                      pInst,
                      'selectorConfig.' + con['target'][0],
                      _val,
                      thisIndex
                    )
                  }

                  //最后一个配置项显示在对话框搜索栏中
                  this.$emit('input', _val)
                  this.$emit('updateInput', _val)
                } else {
                  let configAttr = con['target'][0].split('.')
                  let path = con['target'][0]
                  if (configAttr.length == 4 && parentIndex >= 0) {
                    //孙表数据赋值
                    path =
                      configAttr[0] +
                      '.' +
                      configAttr[1] +
                      '[' +
                      parentIndex +
                      '].' +
                      configAttr[2] +
                      '.' +
                      configAttr[3]
                  }
                  const _val = val.substring(0, val.length - 1)
                  if (path) {
                    if (this.modelName && this.modelName.endsWith(path)) {
                      this.$emit('input', _val)
                      this.$emit('updateInput', _val)
                    }
                    let bindPath = `${pInst.data ? 'data.' : 'model.'}${path}`
                    let bindValue = utils.getValueByPath(
                      pInst,
                      bindPath,
                      thisIndex || thisIndex === 0 ? thisIndex : null
                    )
                    if (fillitem && fillitem.fillBackType == 2 && bindValue) {
                      return
                    } else {
                      utils.setValueByPath(pInst, bindPath, _val, thisIndex)
                      //强制刷新
                      this.$forceUpdate()
                    }
                  }
                }
              }
            })
          })
        //判断对话框是否绑定了关联查询
        let custQueryJson = this.custdialog.custDialog.custQueryJson
        if (custQueryJson.length > 0) {
          for (let i = 0; i < custQueryJson.length; i++) {
            if (custQueryJson[i].conditionfield.length > 0) {
              this.doQuery(custQueryJson[i])
            } else {
              console.error(
                '[' +
                  custQueryJson[i].comment +
                  ']关联查询取值参数未绑定表单字段'
              )
            }
          }
        }
      },
      addCustomItem(newValue) {
        if (!newValue) {
          this.$message.warning('请输入')
          return
        }
        if (this.templOptionsAry.find((e) => e.key === newValue)) {
          this.$message.warning('已存在无需添加')
          return
        }
        let field =
          this.customDialogInit.dsType == 'dataSource'
            ? this.custdialog.quickSearchKeyWord.toLowerCase()
            : this.custdialog.quickSearchKeyWord
        let newItem = {
          value: newValue,
          key: newValue,
          [field]: newValue,
          isNew: true,
        }
        this.templOptionsAry.unshift(newItem)
      },
    },
  }
</script>
<style lang="scss" scoped>
  .hyperlink_content {
    color: var(--themeColor);
    cursor: pointer;
  }
  .edit-input {
    position: absolute;
    left: 1px;
    border: none;
    top: 50%;
    transform: translateY(-50%);
    z-index: 50;
    display: flex;
    align-items: center;
    ::v-deep .el-input__inner {
      height: 100%;
      border: none;
      color: #262626;
    }
  }
  .edit-query-input {
    position: absolute;
    left: 1px;
    border: none;
    top: 50%;
    transform: translateY(-50%);
    z-index: 50;
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    ::v-deep .el-input__inner {
      height: 100%;
      color: #262626;
      border: none;
      display: none;
    }
  }
  ::v-deep {
    .el-input__inner {
      color: #262626 !important;
    }

    .el-button--mini {
      padding: 0px 15px;
      font-size: 12px;
      border-radius: 3px;
      height: 100%;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
    .el-button--info {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
    }
    .el-input__suffix {
      position: absolute;
      height: 100%;
      right: 0px !important;
      top: 0;
      text-align: center;
      color: #c0c4cc;
      -webkit-transition: all 0.3s;
      transition: all 0.3s;
      pointer-events: none;
      z-index: 8;
      .has-clear-all {
        height: 100%;
        display: flex;
        align-items: center;
      }
    }
    .el-dialog__body {
      padding: 0;
      height: calc(100% - 120px);
      overflow-y: auto;
    }
    @media (max-width: 1280px) {
      .el-dialog {
        width: 96% !important;
        margin-top: 2vh !important;
      }
    }
    .el-dialog__wrapper {
      overflow: unset !important;
      &::-webkit-scrollbar {
        width: 0;
        background-color: transparent;
      }
    }

    .el-dialog {
      height: 90%;
      min-height: 400px;
    }
    @media (max-height: 960px) {
      .el-dialog__body .el-container {
        height: 100% !important;
      }
    }
    .el-divider--vertical {
      height: 100%;
    }
  }
  .el-input__inner[aria-invalid='true'] {
    border-color: #f56c6c;
  }

  .has-value {
    .el-select__tags {
      margin-right: 10px;
    }
  }
  .el-select__tags {
    background: #fff;
    margin-left: 1px;
  }
  .el-select__tags__disabled {
    background: #f5f7fa;
  }
  .left-aside {
    border-right: 1px solid #eee;
    padding: 10px;
  }

  .org-tree {
    height: 440px;
    margin-top: 10px;
  }

  .middle-header {
    height: unset !important;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    .search-item {
      display: flex;
      // width: 33.33%;
      margin-right: 12px;
      align-items: center;
    }
    .btn-wrap {
      line-height: 50px;
    }
  }

  .org-table {
    width: 100%;
  }

  .right-aside {
    border-left: 1px solid #eee;
  }

  .select-aside {
    border-left: 1px solid #eee;
  }

  .select-header {
    border-bottom: 1px solid #eee;
    height: 52px !important;
  }

  .select-header > span {
    padding: 10px 0;
    line-height: 53px;
  }
  .select-tree-div {
    height: calc(100% - 60px);
    overflow-y: auto;
    min-height: unset;
  }

  >>> .el-card__header {
    padding: 10px;
  }

  >>> .el-card__body {
    padding: 10px;
  }

  .org-find-card >>> .el-card__header {
    background: #f5f7fa;
  }

  >>> .el-main {
    padding: 0 20px !important;
  }

  .button-group {
    width: 70px;
    height: 170px;
    margin: 0px auto;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
  }

  .button-group > button {
    display: block;
    margin: 8px 0;
  }
  .van-cell[aria-invalid='true'] {
    border: none;
  }
  .cell {
    .flex {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      i {
        margin-left: 5px;
      }
    }
  }
  .van-cell {
    min-height: 32px;
    padding-top: 3px;
    padding-bottom: 0;
    padding-right: 0;
    &::after {
      display: none;
    }
    .van-cell__title {
      width: 1px;
      flex-grow: 0;
    }
    .placeholder-class {
      flex: 1;
      color: #bfbfbf;
      font-size: 14px;
      text-align: left;
    }
  }
  .mobile-cell__wrap {
    min-height: 32px;
    position: relative;
  }
  .CustomDialog-right-button {
    border: none;
    border-left: 1px solid #e4e7ed;
    box-sizing: content-box;
  }
  .CustomDialog-right-button-isHidenInput {
    border: 1px solid #e4e7ed;
  }
  .mobile-cell {
    padding: 0;
    display: flex;
    align-items: center;
    .van-cell__value {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .cell-text {
        color: #262626;
        font-size: 14px;
        text-align: left;
      }
      .cell-close {
        margin-left: 4px;
      }
    }
    .placeholder-class {
      color: #bfbfbf;
      font-size: 14px;
      text-align: left;
    }
    .right-arrow {
      transform: rotate(90deg);
    }
    .mobile-btn {
      height: 32px;
      color: #409eff;
      line-height: 32px;
      border-radius: 8px;
      padding: 0 0 0 16px;
      margin-left: 16px;
      border: none;

      ::v-deep {
        & > span {
          display: flex;
          justify-content: center;
          align-items: center;
        }
        i,
        .van-button__icon {
          font-size: 22px;
        }
        .van-button__text {
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
  }
  ::v-deep {
    .el-tag {
      white-space: normal;
      height: auto;
    }
  }
  .custom-query-search-input {
    padding: 10px;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    position: absolute;
    width: calc(100% - 20px);
    top: 0;
    left: 0;
    z-index: 2;
    cursor: pointer;
  }
  .custom-query-Options__scroll {
    width: 100%;
    ::v-deep.el-scrollbar__wrap {
      max-height: 300px;
    }
  }
</style>
<style>
  .tooltip-width {
    max-width: 200px;
  }
  .el-select-dropdown__list:has(.custom-query-search-input) {
    padding-top: 50px;
  }
  .custom-query-Options {
    width: 100%;
  }
</style>
