<template>
  <div>
    <el-dialog
      v-if="customDialogShowList"
      v-loading="loading"
      :visible.sync="customDialogShowList"
      :title="customDialog.name"
      :close-on-click-modal="false"
      :before-close="dialogCancel"
      :custom-class="
        customDialog.width && customDialog.height ? 'custom-class-dialog' : ''
      "
      :style="{
        '--customHeight': `${customDialog.height}px`,
        '--messageHeight': `${messageHeight}px`,
        '--listTitleHeight': `${customDialog.style == 2 ? 48 : 0}px`,
      }"
      class="hontent-custom-dialog"
      append-to-body
      top="7vh"
      :width="customDialog.width ? `${customDialog.width}px` : '60%'"
      @opened="afterOpen"
    >
      <template v-if="messageValue && messageValue != ''">
        <div class="message" v-html="messageValue"></div>
      </template>
      <el-container :style="style" class="custom-container">
        <div id="container" class="list-selector__container">
          <div
            v-if="customDialog.style == 2"
            v-show="treeShow"
            id="left"
            :style="{
              '--leftWidth': `${transtionWidth}px`,
            }"
            class="list-selector__range"
          >
            <el-card>
              <div slot="header" class="clearfix">
                <span>{{ leftTreeTitle ? leftTreeTitle : '查询树' }}</span>
              </div>
              <ht-tree
                ref="combinationTree"
                :data="combinationTreeData"
                :default-expand-all="defaultExpandAll"
                :props="defaultProps"
                :node-key="nodeKey"
                highlight-current
                :check-on-click-node="true"
                :lazy="
                  customDialog && customDialog.treeDataMode === 1 ? true : false
                "
                :load="loadTree"
                :filter-node-method="filterNode"
                :support-filter="true"
                :expand-on-click-node="expandOnClickNode"
                :default-expanded-keys="defaultExpandedKeys"
                @node-click="combiTreeClick"
              ></ht-tree>
            </el-card>
          </div>
          <div id="center" class="list-selector__main">
            <el-card shadow="hover">
              <template v-if="customDialog.style == 2">
                <div slot="header">
                  <span>{{ treeNodeValue ? treeNodeValue : '列表' }}</span>
                </div>
              </template>
              <el-header v-if="querysShow" class="middle-header">
                <ht-table-search-panel
                  ref="searchPanel"
                  :divide="
                    customDialog.style == 2 || isSetPk !== ''
                      ? 2
                      : customDialog.style == 2 && isSetPk !== ''
                      ? 1
                      : 3
                  "
                  :is-enter-search="true"
                  :label-width="100"
                  :is-flex-layout="false"
                  :style="{
                    '--searchPanelWidth': `${middleWidth}px`,
                  }"
                  @submit.native.prevent
                  @application-search="
                    (val) => {
                      search(true, val)
                    }
                  "
                >
                  <ht-table-search-field
                    v-for="(item, $index) in conditionBind"
                    :key="$index"
                    :type="item.type"
                    :label="item.comment"
                    :value-format="
                      item.dbType == 'date' || item.controllerType == '15'
                        ? 'yyyy-MM-dd HH:mm:ss'
                        : item.controllerType == '16'
                        ? 'yyyy-MM-dd'
                        : ''
                    "
                    :format="
                      item.dbType == 'date' || item.controllerType == '15'
                        ? 'yyyy-MM-dd HH:mm:ss'
                        : item.controllerType == '16'
                        ? 'yyyy-MM-dd'
                        : ''
                    "
                    :prop="item.field"
                    :config="item.config"
                    :operation="getOperation(item.condition)"
                  />
                </ht-table-search-panel>
              </el-header>
              <el-main class="custom-dialog_main">
                <el-table
                  ref="orgTable"
                  :data="dialogData"
                  stripe
                  border
                  class="org-table"
                  size="medium"
                  style="width: 100%"
                  :row-key="
                    isSetPk !== ''
                      ? (row) => getRowKey(row, isSetPk)
                      : 'custom_dialog_rowId'
                  "
                  @row-click="orgRowClick"
                  @selection-change="orgTableSelection"
                  @select="onTableSelect"
                  @select-all="selectAll"
                >
                  <el-table-column
                    v-if="customDialog.selectNum != 1"
                    type="selection"
                    align="center"
                    reserve-selection
                    width="55"
                  ></el-table-column>
                  <el-table-column
                    v-if="customDialog.selectNum === 1"
                    align="center"
                    width="55"
                  >
                    <template slot-scope="scope">
                      <el-radio
                        v-model="tableRadioVal"
                        :label="scope.$index"
                        class="textRadio"
                        @selection-change="orgTableSelection"
                      >
                        &nbsp;
                      </el-radio>
                    </template>
                  </el-table-column>
                  <el-table-column
                    type="index"
                    width="50"
                    align="center"
                    label="序号"
                  ></el-table-column>
                  <el-table-column
                    v-for="(field, fieldIndex) in displayfield"
                    :key="field.field + fieldIndex"
                    :show-overflow-tooltip="true"
                    :prop="field.field"
                    :label="field.comment"
                    :width="field.width"
                  ></el-table-column>
                </el-table>
              </el-main>
              <el-footer v-if="customDialog.needPage">
                <el-row
                  v-if="customDialog.needPage"
                  type="flex"
                  justify="end"
                  style="padding-top: 15px; justify-content: space-between"
                >
                  <el-button
                    v-if="customDialog.style == 2"
                    :icon="toggleBtn"
                    size="mini"
                    type="default"
                    @click="toggleTree"
                  ></el-button>
                  <el-pagination
                    small
                    :current-page="pagination.page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  ></el-pagination>
                </el-row>
              </el-footer>
            </el-card>
          </div>
          <div v-if="isSetPk !== ''" id="right" class="list-selector__selected">
            <el-card shadow="hover">
              <div slot="header" class="selector-selected__header clearfix">
                <span>已选择({{ selectsCount }})</span>
                <el-button
                  type="text"
                  style="float: right; padding: 3px 0"
                  @click="clearAllSelects"
                >
                  {{ $t('ht.common.clear') }}
                </el-button>
              </div>
              <el-scrollbar
                v-if="selectsCount > 0"
                class="selector-selected__scroll"
              >
                <draggable
                  v-model="selects"
                  class="selector-selected__wrap"
                  tag="ul"
                  v-bind="dragOptions"
                  handle=".list-selector__handle"
                  @start="isDragging = true"
                  @end="isDragging = false"
                >
                  <li
                    v-for="(select, selectIndex) in selects"
                    :key="select[primaryFieldProp] + selectIndex"
                    class="selector-selected__item"
                  >
                    <div
                      class="selector-selected__item-left"
                      @dblclick="removeSelected(select)"
                    >
                      <ht-icon
                        v-if="!single"
                        name="drag"
                        class="list-selector__handle follow-theme-color"
                        width="16"
                        height="16"
                        fill=""
                      />
                      <div class="selector-text">
                        {{ select[primaryFieldProp] }}
                      </div>
                    </div>
                    <i
                      v-if="!single"
                      :class="
                        selectIndex == 0
                          ? 'is-disabled'
                          : 'selector-selected__up'
                      "
                      class="el-icon-top hover-follow-theme-color"
                      @click="sort(select, 'up')"
                    ></i>
                    <i
                      v-if="!single"
                      class="el-icon-bottom hover-follow-theme-color"
                      :class="
                        selectIndex == selects.length - 1
                          ? 'is-disabled'
                          : 'selector-selected__down'
                      "
                      @click="sort(select, 'down')"
                    ></i>
                    <i
                      class="el-icon-error selector-selected__remove hover-follow-theme-color"
                      @click="removeSelected(select)"
                    ></i>
                  </li>
                </draggable>
              </el-scrollbar>
              <div v-else class="el-tree__empty-block">
                <span class="el-tree__empty-text">
                  {{ t('el.table.emptyText') }}
                </span>
              </div>
            </el-card>
          </div>
        </div>
      </el-container>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button size="small" @click="dialogCancel">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="isDisabledConfirmBtn"
          @click="dialogConfirm"
        >
          确认
        </el-button>
      </span>
    </el-dialog>
    <!-- 树形对话框 -->
    <el-dialog
      title="动态传入参数查询"
      :width="customDialog.width ? `${customDialog.width}px` : '60%'"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :custom-class="
        customDialog.width && customDialog.height ? 'custom-class-dialog' : ''
      "
      :style="{
        '--customHeight': `${customDialog.height}px`,
        '--messageHeight': `${messageHeight}px`,
      }"
      class="hontent-custom-dialog"
      append-to-body
      top="7vh"
    >
      <template v-if="messageValue && messageValue != ''">
        <div class="message" v-html="messageValue"></div>
      </template>
      <!-- 动态传入参数查询树 -->
      <table
        class="form-table"
        style="margin-left: 24px; width: 90%"
        cellspacing="0"
        cellpadding="0"
        border="0"
      >
        <tbody v-for="(item, $index) in conditionfieldTree" :key="$index">
          <tr v-if="item.defaultType == '4'">
            <th width="130px">{{ item.comment }}:</th>
            <td>
              <ht-input
                v-if="item.type != 'date'"
                v-model="item.paramVal"
                type="text"
                style="width: 100%"
                :placeholder="'请输入' + item.comment"
                autocomplete="off"
              ></ht-input>
              <ht-date
                v-if="item.type == 'date'"
                v-model="item.paramVal"
                style="width: 100%"
                :placeholder="'请输入' + item.comment"
                format="yyyy-MM-dd"
              ></ht-date>
            </td>
          </tr>
        </tbody>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 树形弹框 -->
    <el-dialog
      :visible.sync="customDialogShowTree"
      :title="customDialog.name"
      :close-on-click-modal="false"
      :before-close="dialogCancelTree"
      append-to-body
      top="6vh"
      :width="customDialog.width ? `${customDialog.width}px` : '60%'"
      :custom-class="
        customDialog.width && customDialog.height ? 'custom-class-dialog' : ''
      "
      :style="{
        '--customHeight': `${customDialog.height}px`,
        '--messageHeight': `${messageHeight}px`,
      }"
      class="hontent-custom-dialog"
    >
      <template v-if="messageValue && messageValue != ''">
        <div class="message" v-html="messageValue"></div>
      </template>
      <el-container :style="style" style="overflow: auto" class="custom-tree">
        <ht-tree
          ref="tree"
          :data="props1"
          :props="defaultProps"
          :node-key="nodeKey"
          highlight-current
          :show-checkbox="customDialog.selectNum === -1"
          :check-on-click-node="true"
          :check-strictly="checkStrictly"
          :default-expand-all="defaultExpandAll"
          :load="loadTree"
          :lazy="customDialog && customDialog.treeDataMode === 1 ? true : false"
          :expand-on-click-node="expandOnClickNode"
          :default-expanded-keys="defaultExpandedKeys"
          style="width: 100%"
          :filter-node-method="filterNode"
          :support-filter="true"
          @node-click="treeClick"
          @check-change="getChecked"
        ></ht-tree>
      </el-container>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button size="small" @click="dialogCancelTree">取 消</el-button>
        <el-button size="small" type="primary" @click="dialogTreeConfirm">
          确认
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import $ from 'jquery'
  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 CustomQuery from '@/services/CustomQuery'
  import _ from 'lodash'
  const draggable = require('vuedraggable')
  export default {
    name: 'CustomDialog',
    components: { draggable },
    mixins: [dialog, locale, inputName, permission, form],
    props: {
      custdialog: {
        type: Object,
        default: () => {
          return {}
        },
      },
      value: String,
      maxRow: Number,
      subIndex: Number,
      sunIndex: Number,
      subPath: String,
      currentSubData: Array,
      modelName: String,
      //唯一标识字段
      primaryField: {
        type: String,
        default: '',
      },
      isSubtableBackfill: {
        type: Boolean,
        default: false,
      },
      isPreview: {
        type: Boolean,
        default: false,
      },
      defaultExpandAll: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        isEditInputShow: false,
        customValue: '',
        defualtTooltipplacement: 'bottom',
        dialogVisible: false, //打开树形输入动态参数值的对话框
        pageParam: {}, //树形对话框参数
        conditionfieldTree: [], //树形对话框条件字段
        data: {
          qxdd: {},
        },
        inputSuffixWidth: 0,
        placeholderBo: '',
        quickSearch: '', //填写提示
        conditionBind: [], //参数查询字段
        nodeKey: 'ID_', //树形数据父Id
        customDialogShowList: false,
        customDialogShowTree: false,
        selectOrgProps: {
          label: 'name',
        },
        treeNodeName: '',
        treeNodeValue: '',
        style: '', //对话框宽高
        selectOrgs: [],
        inputSuffixHeight: 33,
        config: null,
        updating: false,
        displayfield: [], //显示字段
        customDialog: {},
        queryParam: '', //查询条件输入的值
        props1: [],
        showData: [],
        checkBoxDataAll: [], //选中对象的集合
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'isLeaf',
        },
        propsData: [],
        querysShow: false, //是否显示搜索框
        tableRadioVal: '',
        isCurrentChange: false, //是否不执行 orgTableSelection方法
        param: [], //绑定的表单字段
        treeList: [],
        displayField: {},
        queryParams: [],
        placeholders: [],
        oldselectOrgs: [],
        combinationTreeData: [],
        combiTreeDisplayField: [],
        combinationTreeQuerys: [],
        combinationRule: {},
        toggleBtn: 'el-icon-arrow-left',
        treeShow: true,
        transtionWidth: 300,
        leftTreeTitle: '',
        writeable: true,
        fixedParams: {}, // 传过来的固定值
        executeScriptResult: null,
        isDisabledConfirmBtn: true,
        selects: [],
        fromKey: '',
        requestParams: {},
        expandOnClickNode: false,
        loading: false,
      }
    },
    computed: {
      //默认展开的节点的 key 的数组
      defaultExpandedKeys: function () {
        // if (
        //   this.props1 &&
        //   this.props1.length > 0 &&
        //   this.props1[0][this.nodeKey]
        // ) {
        //   return [this.props1[0][this.nodeKey]]
        // }
        return []
      },
      middleWidth() {
        if (this.customDialog.style == 2 && this.isSetPk == '') {
          return this.customDialog.width - 274
        } else if (this.isSetPk !== '' && this.customDialog.style != 2) {
          return this.customDialog.width - this.transtionWidth
        } else if (this.customDialog.style == 2 && this.isSetPk !== '') {
          return this.customDialog.width - 274 - this.transtionWidth
        } else {
          return this.customDialog.width
        }
      },
      isSetPk() {
        let returnStrArray = utils.isJSON(this.customDialog.resultfield)
          ? JSON.parse(this.customDialog.resultfield)
          : this.customDialog.resultfield
        if (returnStrArray && returnStrArray.length > 0) {
          let result = returnStrArray.filter((item) => item.isPK)
          return (result && result.length && result[0].field) || ''
        } else {
          return ''
        }
      },
      // isSetTag() {
      //   let returnStrArray = JSON.parse(this.customDialog.resultfield)
      //   if (returnStrArray && returnStrArray.length > 0) {
      //     let result = returnStrArray.filter((item) => item.isTag)
      //     return (result && result.length && result[0].field) || ''
      //   } else {
      //     return ''
      //   }
      // },
      primaryFieldProp: function () {
        return this.isSetPk == this.fromKey || this.fromKey == ''
          ? this.isSetPk
          : this.fromKey
      },
      selectsCount() {
        return this.selects && this.selects.length > 0 ? this.selects.length : 0
      },
      checkStrictly() {
        if (
          this.customDialog.treeDataMode &&
          this.customDialog.treeDataMode > 0
        ) {
          return true
        } else {
          return false
        }
      },
      messageHeight() {
        return this.customDialog && this.customDialog.tips
          ? JSON.parse(this.customDialog.tips).height
          : 0
      },
      messageValue() {
        return this.customDialog && this.customDialog.tips
          ? JSON.parse(this.customDialog.tips).value
          : ''
      },
    },
    watch: {
      dialogData: {
        handler(val) {
          if (this.value && val.length > 0) {
            let modelName =
              this.modelName.split('.')[this.modelName.split('.').length - 1]
            const currentBindInfo =
              this.custdialog.custDialog.mappingConf &&
              this.custdialog.custDialog.mappingConf != undefined &&
              this.custdialog.custDialog.mappingConf.find((it) => {
                return it['target'][0].endsWith(modelName)
              })
            const from = currentBindInfo && currentBindInfo.from
            let returnStr = JSON.parse(this.customDialog.resultfield)
            let currentObj = returnStr.find((item) => {
              if (this.customDialog.dsType == 'dataSource') {
                return item.comment.toLowerCase() === from.toLowerCase()
              } else {
                return item.comment === from
              }
            })
            this.fromKey = currentObj ? currentObj.field : ''
          }
        },
        immediate: true,
        deep: true,
      },
      selects(val) {
        if (val && val.length) {
          this.isDisabledConfirmBtn = false
        } else {
          this.isDisabledConfirmBtn = true
        }
      },
    },
    mounted() {
      // 改为点击时才调用后端接口
      // if (this.value) {
      //   this.showDialog(true)
      // }
    },
    methods: {
      /**
       * 行数据的 Key
       * @param row 当前行
       * @param val 参数
       */
      getRowKey(row, val) {
        return row[val] + Math.floor(10000 + Math.random() * 90000)
      },
      // 平铺结构转嵌套结构
      tile2nest(array, key, pKey, childrenKey) {
        if (!array || array.constructor !== Array) {
          return array
        }
        // 复制一份，避免修改原始数组
        let ary = [...array]
        key = key || 'id'
        pKey = pKey || 'parentId'
        childrenKey = childrenKey || 'children'
        // 定义一个待移除数组
        let ary2remove = []
        ary.map((item) => {
          // isLeaf 字段 'Y' or 'N' 转换为 true or false
          if (item.isLeaf == 'N' || item.children) {
            item.isLeaf = false
          }
          if (item.isLeaf == 'Y' || !item.children) {
            item.isLeaf = true
          }
          if (item[key] !== item[pKey]) {
            // 找父节点
            let p = ary.filter((c) => c[key] === item[pKey])
            if (p && p.length == 1) {
              p[0][childrenKey] = p[0][childrenKey] || []
              // 将子节点放到父节点中
              p[0][childrenKey].push(item)
              ary2remove.push(item[key])
            }
          }
        })
        // 遍历移除待删除对象
        ary2remove.map((item) => {
          ary = ary.filter((c) => c[key] !== item)
        })
        return ary
      },
      showDialog(isMounted = false) {
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 800)
        this.selectOrgs = []
        this.selects = []
        const this_ = this
        this.fixedParams = {}
        var alias = this.custdialog.custDialog.alias
        this.$requestConfig
          .getCustomDialogByAlias(alias)
          .then((customDialog) => {
            if (!customDialog || !customDialog.alias) {
              this.$message.error('对话框别名【' + alias + '】不存在！')
              return
            }
            if (customDialog.style == 1) {
              var displaylist = JSON.parse(customDialog.displayfield)
              this_.nodeKey = displaylist.id
            }
            if (customDialog.needPage && customDialog.requestType === 'POST') {
              let obj = {}
              this.getLastKeyByPath(obj, customDialog.pageKey, 1)
              this.getLastKeyByPath(obj, customDialog.pageSizeKey, 10)
              this.getLastKeyByPath(obj, customDialog.totalKey, true)
              const exp = utils.parseExp(customDialog.dataParam, obj, true)
              if (exp) {
                const params = JSON.parse(exp)
                if (params.pageBean) {
                  this.pagination = {
                    ...params.pageBean,
                  }
                }
              }
            }
            //对话框按表单字段查询（参数传入的）
            let bindList = this_.custdialog.custDialog.conditions
            this_.param = [] //绑定的表单字段
            if (bindList.length > 0) {
              bindList.forEach((ele) => {
                //绑定表单字段
                if (
                  ele.bind &&
                  (ele.defaultType == '3' ||
                    ele.bind.startsWith('data.searchForm'))
                ) {
                  // 获取对话框配置的查询条件
                  let condition = null
                  if (customDialog.conditionfield) {
                    const conditions = JSON.parse(customDialog.conditionfield)
                    const condMatch = conditions.filter(
                      (item) =>
                        item.field.toLowerCase() === ele.field.toLowerCase()
                    )
                    if (condMatch && condMatch.length > 0) {
                      condition = condMatch[0].condition
                    }
                  }

                  let obj = {}
                  obj.field = ele.field
                  obj.bind = ele.bind
                  obj.bindType = ele.bindType
                  obj.default = ele.default
                  if (condition) {
                    obj.operation = this.getOperation(condition)
                  }
                  this_.param.push(obj)
                }
                //取值对象为脚本时获取value
                if (ele.bindType === 3) {
                  this_.$requestConfig.executeScript(ele.bind).then((res) => {
                    this_.executeScriptResult = res && res.value
                  })
                }
              })
            }
            //判断对话框查询是否有条件
            let userInputList = JSON.parse(customDialog.conditionfield)
            this_.quickSearch = '' //填写提示 placeholder
            this_.conditionBind = []
            let queryParams = []
            let placeholders = []
            if (userInputList.length > 0) {
              userInputList.forEach(async (ele) => {
                var obj = {}
                //条件查询参数（用户输入的） 文本框输入 defaultType 1 用户输入 2固定值 3参数传入 5脚本
                if (ele.defaultType == '1') {
                  obj[ele.field] = ''
                  queryParams.push(obj)
                  // queryParams[ele.field] = "";
                  this_.conditionBind.push(ele)
                  placeholders.push('请输入' + ele.comment)
                } else if (ele.defaultType == '5' && ele.defaultValue) {
                  const res = await this.$requestConfig.executeScript(
                    ele.defaultValue
                  )
                  if (res) {
                    this_.fixedParams[ele.field] = res.value
                  }
                } else if (ele.defaultType == '2' && ele.defaultValue) {
                  this_.fixedParams[ele.field] = ele.defaultValue
                }
              })
              this.$set(this, 'queryParams', queryParams)
              this.$set(this, 'placeholders', placeholders)
            }
            //判断是否显示条件查询输入框
            if (this_.quickSearch != '') {
              this_.querysShow = true
            } else {
              this_.querysShow = true
            }
            this_.quickSearch = '请输入' + this.quickSearch + '查询'
            this_.style = 'height:' + customDialog.height - 154 + 'px'
            if (window.screen.height && window.screen.height <= 900) {
              this.style = 'height:440px'
            }

            if (customDialog.style == 0 || customDialog.style == 2) {
              //列表

              setTimeout(() => {
                this_.customDialogShow(
                  {
                    alias: alias,
                    customDialog: customDialog,
                  },
                  isMounted
                )
              }, 100)
            } else if (customDialog.style == 1) {
              //树形
              this_.pageParam = { alias: alias, customDialog: customDialog }
              this_.customDialog = customDialog
              this_.customDialog.width = this_.customDialog.width || 1200
              this_.customDialog.height = this_.customDialog.height || 740

              //sy
              // this.customDialog.treeDataMode = 1
              // this.customDialog.selectNum = 1

              //////////

              let param = {}
              this_.conditionfieldTree = []
              //判断是否存在条件
              if (customDialog.conditionfield) {
                this_.conditionfieldTree = JSON.parse(
                  customDialog.conditionfield
                )
                if (this_.conditionfieldTree.length > 0) {
                  for (
                    let i = this_.conditionfieldTree.length - 1;
                    i >= 0;
                    i--
                  ) {
                    //判断条件字段是否是动态传入（defaultType：4：动态传入，2：固定值 ）
                    if (this_.conditionfieldTree[i].defaultType == '4') {
                      param[this_.conditionfieldTree[i].field] =
                        this_.conditionfieldTree[i].comment
                    }
                  }
                }
              }
              //有动态传入的字段
              if (!isMounted) {
                if (JSON.stringify(param) != '{}') {
                  this_.dialogVisible = true
                } else {
                  //无动态传入的字段
                  this_.customDialogTreeShow(this_.pageParam)
                }
              }
            }

            let modelName =
              this.modelName.split('.')[this.modelName.split('.').length - 1]
            const currentBindInfo =
              this.custdialog.custDialog.mappingConf &&
              this.custdialog.custDialog.mappingConf != undefined &&
              this.custdialog.custDialog.mappingConf.find((it) => {
                return it['target'][0].endsWith(modelName)
              })

            const from = currentBindInfo && currentBindInfo.from
            let returnStr =
              customDialog && customDialog.resultfield
                ? JSON.parse(customDialog.resultfield)
                : []
            let currentObj = returnStr.find((item) => {
              if (item.comment && from) {
              } else {
                return false
              }
              if (customDialog.dsType == 'dataSource') {
                return item.comment.toLowerCase() === from.toLowerCase()
              } else {
                return item.comment === from
              }
            })
            this.fromKey = currentObj ? currentObj.field : ''
            if (this.fromKey && this.isSetPk !== '') {
              let valueData = this.value ? this.value.split(',') : []
              for (var i = 0; i < valueData.length; i++) {
                let obj = {}
                obj[this.fromKey] = valueData[i]
                this.selects.push({ ...obj })
              }
              this.selectOrgs = [...this.selects]
            }
          })
      },
      treeClick(data) {
        // 单选
        if (this.customDialog.selectNum === 1) {
          this.propsData = []
          this.propsData.push(data)
          this.selects = this.propsData
        }
      },

      getChecked(data, checked, node) {
        // 多选
        if (this.customDialog.selectNum === -1) {
          this.propsData = this.$refs.tree.getCheckedNodes(false, true)
          this.selects = this.propsData
        }
      },
      async customDialogShow(pageParam, isMounted = false) {
        const _that = this
        function cb() {
          if (!isMounted) {
            _that.customDialogShowList = true
            _that.$nextTick(() => {
              _that.treeList = []
              _that.afterOpen()
            })
          }
        }
        this.customDialog = pageParam.customDialog
        this.customDialog.width = this.customDialog.width || 1200
        this.customDialog.height = this.customDialog.height || 740
        let queryUrl = this.customDialog.url
        //如果自定义对话框列表查询数据不是数据源则请求方法为restful配置的请求方式
        let requestType = this.customDialog.requestType
        if (this.customDialog.dsType == 'selectedApi') {
          let queryParams = []
          if (this.param) {
            for (let i = 0; i < this.param.length; i++) {
              let item = this.param[i]
              let val = item.bind
              if (item.bindType == '1') {
                let bindDefaultValue = item.default
                val = this.getCurrentValue(item.bind, bindDefaultValue)
              } else if (item.bindType == '3') {
                await this.$requestConfig
                  .executeScript(item.bind)
                  .then((res) => {
                    val = res && res.value
                  })
              }
              if (val != null && !utils.isEmpty(val)) {
                queryParams.push({ key: item.field, value: val })
              }
            }
          }
          queryUrl =
            '${portal}/portal/portalInterfaceManager/v1/doQuery?alias=' +
            this.customDialog.apiAlias +
            '&paramData=' +
            encodeURIComponent(Base64.encode(`${JSON.stringify(queryParams)}`))
          requestType = 'GET'
        } else if (this.customDialog.dsType == 'dataSource') {
          queryUrl =
            '${form}/form/customDialog/v1/getListData?alias=' +
            this.customDialog.alias +
            '&mapParam=' +
            (this.customDialog.mapParam ? this.customDialog.mapParam : '')
          requestType = 'POST'
        }
        this.customDialog.queryUrl = queryUrl
        this.customDialog.requestType = requestType
        if (this.dialogData.length < 1) {
          this.search(true, undefined, cb)
          this.displayfield = JSON.parse(pageParam.customDialog.displayfield)
          if (this.customDialog.dsType == 'dataSource') {
            for (var i = 0; i < this.displayfield.length; i++) {
              this.displayfield[i].field =
                this.displayfield[i].field.toLowerCase()
            }
          }
        } else if (this.dialogData.length >= 1) {
          this.search(true, undefined, cb)
        }
        if (this.dialogData.length > 0 && this.displayfield.length == 0) {
          this.search(true, undefined, cb)
          this.displayfield = JSON.parse(pageParam.customDialog.displayfield)
          if (this.customDialog.dsType == 'dataSource') {
            for (var j = 0; i < this.displayfield.length; j++) {
              this.displayfield[j].field =
                this.displayfield[j].field.toLowerCase()
            }
          }
        }
      },
      customDialogTreeShow(pageParam, node, type, cb) {
        var customDialog = this.customDialog
        let displayfield = JSON.parse(this.customDialog.displayfield)
        let mapParamObj = {} //数据来源是数据源，且有动态参数传入时调用
        let mapParam = ''
        let defaultPValue = '' //父ID值
        let hasParentId = false //是否有parentId
        if (this.conditionfieldTree.length > 0) {
          for (let i = 0; i < this.conditionfieldTree.length; i++) {
            if (['3', '4'].includes(this.conditionfieldTree[i].defaultType)) {
              //动态传入
              //得到输入的条件字段值
              let val = this.conditionfieldTree[i].paramVal
              const currField = this.conditionfieldTree[i].field
              if (!val && this.conditionfieldTree[i].defaultType == '3') {
                // 获取表单控件的配置条件
                if (
                  this.custdialog &&
                  this.custdialog.custDialog &&
                  this.custdialog.custDialog.conditions
                ) {
                  let bindList = this.custdialog.custDialog.conditions
                  if (bindList.length > 0) {
                    bindList.forEach((ele) => {
                      if (ele.field == currField) {
                        val = ele.bind
                      }
                    })
                  }
                }
              }
              if (!val) {
                continue
              }
              //得到条件字段KEY
              let key = this.conditionfieldTree[i].field
              mapParamObj[key] = val
            } else if (this.conditionfieldTree[i].defaultType == '2') {
              //固定值
              //得到输入的条件字段值
              let val = this.conditionfieldTree[i].defaultValue
              if (!val) {
                continue
              }
              //得到条件字段KEY
              let key = this.conditionfieldTree[i].field
              mapParamObj[key] = val
            }
          }
          if (this.param) {
            const pInst = utils.getOnlineFormInstance(this)
            this.param.forEach((item) => {
              let val = utils.getValueByPath(pInst, item.bind)
              val && (mapParamObj[item.field] = val)
            })
          }
          if (JSON.stringify(mapParamObj) != '{}') {
            //获取对话框配置的父ID字段
            let pid = JSON.parse(this.customDialog.displayfield).pid
            for (let m in mapParamObj) {
              if (pid == m) {
                defaultPValue = mapParamObj[m]
                break
              }
            }
            //点击的
            if (mapParamObj.hasOwnProperty('parentId') && type == 'click') {
              mapParamObj.parentId = node.data[displayfield.id]
              hasParentId = true
            }
            mapParam = JSON.stringify(mapParamObj)
            mapParam = mapParam.substring(1, mapParam.length - 1)
          }
        }

        var requestType =
          customDialog.dsType == 'dataSource'
            ? 'GET'
            : customDialog.requestType
            ? customDialog.requestType
            : 'POST'
        var url =
          '${form}/form/customDialog/v1/getTreeData?alias=' +
          pageParam.alias +
          '&mapParam=' +
          mapParam

        //点击的
        if (!hasParentId && type == 'click') {
          let ljChar = url ? (url.indexOf('?') == -1 ? '?' : '&') : ''
          url = url + ljChar + 'parentId=' + node.data[displayfield.id]
        }
        //逐级
        if (this.customDialog.treeDataMode === 1 && !type) {
          // url = url + '&' + displayfield.pid + '=' + displayfield.pvalue

          if (JSON.stringify(mapParamObj) == '{}') {
            let ljChar = url ? (url.indexOf('?') == -1 ? '?' : '&') : ''
            url = url + ljChar + 'parentId' + '=' + displayfield.pvalue
          }
        }

        var paramsObj = {}
        var dataParamObj = []
        if (customDialog.dsType != 'dataSource') {
          url = customDialog.url
          var templatePa = customDialog.dataParam
          let ctx = {}
          let allCtx = {}
          let dataSourceParentId = false
          if (customDialog.conditionfield) {
            var conditions = JSON.parse(customDialog.conditionfield)
            for (let i = 0; i < conditions.length; i++) {
              var con = conditions[i]
              allCtx[con.field] = con.defaultValue
              // 构建查询参数
              if (customDialog.dsType == 'restful') {
                let obj = {
                  key: con.field,
                  value: con.defaultValue || '',
                  paramType: con.paramType,
                }
                dataParamObj.push(obj)
              } else {
                if (requestType == 'POST') {
                  if (templatePa) {
                    ctx[con.field] = con.defaultValue
                  } else {
                    if (type == 'click' && con.field == 'parentId') {
                      paramsObj[con.field] = node.data[displayfield.id]
                    } else {
                      paramsObj[con.field] = con.defaultValue
                    }
                  }
                } else {
                  let ljChar = url ? (url.indexOf('?') == -1 ? '?' : '&') : ''
                  if (type == 'click' && con.field == 'parentId') {
                    dataSourceParentId = true
                    url =
                      url +
                      ljChar +
                      con.field +
                      '=' +
                      node.data[displayfield.id]
                  } else {
                    url = url + ljChar + con.field + '=' + con.defaultValue
                  }
                }
              }
            }
            //逐级加载
            if (
              this.customDialog.treeDataMode === 1 &&
              requestType != 'POST' &&
              !type
            ) {
              if (JSON.stringify(allCtx) == '{}') {
                let ljChar = url ? (url.indexOf('?') == -1 ? '?' : '&') : ''
                url = url + ljChar + 'parentId' + '=' + displayfield.pvalue
              }
            }

            //点击
            if (type == 'click' && !dataSourceParentId) {
              let ljChar = url ? (url.indexOf('?') == -1 ? '?' : '&') : ''
              url = url + ljChar + 'parentId' + '=' + node.data[displayfield.id]
            }
          }

          // 添加用户id 岗位id 组织id
          try {
            if (this.$requestConfig.getUserId()) {
              ctx.userId = this.$requestConfig.getUserId()
            }
            if (this.$requestConfig.getOrgId()) {
              ctx.orgId = this.$requestConfig.getOrgId()
            }
            if (this.$requestConfig.getPostId()) {
              ctx.postId = this.$requestConfig.getPostId()
            }
          } catch (e) {}
          // if (this.customDialog.treeDataMode === 1) {
          //   paramsObj[displayfield.pid] = displayfield.pvalue
          // }
          if (templatePa) {
            templatePa = utils.parseExp(templatePa, ctx)
            paramsObj = JSON.parse(templatePa)
          }
          //点击的
          if (type == 'click') {
            paramsObj[displayfield.pid] = node.data[displayfield.id]
          }

          if (customDialog.dsType == 'selectedApi') {
            requestType = 'GET'

            let queryParams = []
            if (paramsObj) {
              for (let i in paramsObj) {
                queryParams.push({
                  key: i,
                  value: paramsObj[i],
                })
              }
            }
            //逐级加载
            if (this.customDialog.treeDataMode === 1 && !type) {
              if (JSON.stringify(paramsObj) == '{}') {
                queryParams = [
                  {
                    key: displayfield.pid,
                    value: displayfield.pvalue,
                    treeParam: 'parentId',
                  },
                ]
              }
            }

            //点击的
            if (type == 'click') {
              if (JSON.stringify(paramsObj) != '{}') {
                if (paramsObj.hasOwnProperty(displayfield.pid)) {
                  paramsObj[displayfield.pid] = node.data[displayfield.id]
                } else {
                  queryParams.push({
                    key: displayfield.pid,
                    value: node.data[displayfield.id],
                    treeParam: 'parentId',
                  })
                }
              } else {
                queryParams.push({
                  key: displayfield.pid,
                  value: node.data[displayfield.id],
                  treeParam: 'parentId',
                })
              }
            }

            url =
              '${portal}/portal/portalInterfaceManager/v1/doQuery?alias=' +
              this.customDialog.apiAlias +
              '&paramData=' +
              encodeURIComponent(
                Base64.encode(`${JSON.stringify(queryParams)}`)
              )
          }
        }
        var requestParams = {}
        requestParams.requestType = requestType
        requestParams.url = url
        requestParams.dsType = customDialog.dsType
        requestParams.paramsObj = paramsObj //请求体参数
        requestParams.dataParamObj = dataParamObj //条件参数
        if (!type) {
          this.searchTree(requestParams, defaultPValue)
          this.customDialogShowTree = true
        } else {
          cb(requestParams)
        }
      },
      //树形查询
      searchTree(requestParams, defaultPValue) {
        const this_ = this
        requestParams.url = utils.parseUrl(requestParams.url)
        let data = {}
        if (requestParams.dsType == 'restful') {
          data = {
            url: requestParams.url,
            method: requestParams.requestType === 'POST' ? 'post' : 'get',
            data: requestParams.paramsObj,
            params: requestParams.dataParamObj,
          }
        } else {
          data = {
            url: requestParams.url,
            method: requestParams.requestType === 'POST' ? 'post' : 'get',
            data: requestParams.paramsObj,
          }
        }
        let query = null
        if (requestParams.dsType == 'dataSource') {
          query = this.$requestConfig.request(data)
        } else {
          query = this.$requestConfig.doQueryByRest(data)
        }

        query.then(function (response) {
          //显示字段配置
          let displayfield = JSON.parse(this_.customDialog.displayfield)
          this_.displayField = displayfield
          //把对话框配置的显示字段显示名称赋值给树形的显示值
          this_.defaultProps.label = displayfield.displayName
          if (response instanceof Object && !Array.isArray(response)) {
            response = [response]
          }
          this_.treeList = response
          //得到要加载树的信息
          if (defaultPValue) {
            displayfield.pvalue = defaultPValue
          }
          this_.props1 = this_.toTreeData(
            response,
            displayfield.id,
            displayfield.pid,
            displayfield.displayName,
            displayfield.pvalue ? displayfield.pvalue : 0
          )
        })
      },
      dialogTreeConfirm(cb) {
        if (this.isPreview) {
          this.customDialogShowList = false
          //监听列表预览页面的确认事件
          this.$message.success('返回数据为：' + JSON.stringify(this.selects))
          return
        }
        this.$emit('hideModel')
        if (this.isSubtableBackfill) {
          this.$emit('customDialog-confirm', this.propsData, cb)
        } else {
          this.calacInputSuffixHeight()
          let thisIndex = null //当前数据所在下标
          let parentIndex = null //父节点所在下标
          if (this.$parent.$el) {
            thisIndex = utils.getSomeAttributeFromParentElement(
              this.$el,
              'data-index'
            )
            if (!thisIndex) {
              thisIndex = utils.getSubScopeElAndIndex(this.$parent.$el).index
            }
            parentIndex = utils.getSomeAttributeFromParentElement(
              this.$parent.$parent.$el,
              'data-index'
            )
          }
          this.setDialogData([])
          var returnStr = JSON.parse(this.customDialog.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] = returnStr[i].field
            comment[i] = returnStr[i].comment
          }
          var nodes = this.propsData
          if (this.customDialog.selectNum === 1) {
            nodes = this.propsData[0]
            var temp = ''
            for (var j = 0; j < comment.length; j++) {
              temp += '"' + comment[j] + '":"' + nodes[field[j]] + '",'
            }
            if (temp != '') {
              temp = '{' + temp.substring(0, temp.length - 1) + '}'
            }
            str.push(utils.parseToJson(temp))
          } else {
            nodes.forEach((item, k) => {
              var temp = ''
              for (var i = 0; i < comment.length; i++) {
                temp += '"' + comment[i] + '":"' + nodes[field[i]] + '",'
                temp += '"' + comment[i] + '":"' + nodes[k][field[i]] + '",'
              }
              if (temp != '') {
                temp = '{' + temp.substring(0, temp.length - 1) + '}'
              }
              str.push(utils.parseToJson(temp))
            })
          }
          const pInst = utils.getOnlineFormInstance(this)
          this.selectOrgs = this.convertComment2Field(str, field)
          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 = ''
                  str.forEach((item) => {
                    val += item[con.from] + ','
                  })
                  if (this.modelName == 'data.' + con['target'][0]) {
                    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.substring(0, val.length - 1),
                        thisIndex
                      )
                    }
                  } else if (
                    this.modelName ==
                    'searchForm.' + con['target'][0]
                  ) {
                    let bindValue = utils.getValueByPath(
                      pInst,
                      'data.' + 'searchForm.' + con['target'][0],
                      thisIndex || thisIndex === 0 ? thisIndex : null
                    )
                    if (fillitem && fillitem.fillBackType == 2 && bindValue) {
                      return
                    } else {
                      utils.setValueByPath(
                        pInst,
                        'data.' + 'searchForm.' + con['target'][0],
                        val.substring(0, val.length - 1),
                        thisIndex
                      )
                    }
                  } 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.showData = this.propsData ? [...this.propsData] : ''
          this.customDialogShowTree = false
        }
      },
      // 将以comment为key的数组改造为以field为key的数组
      convertComment2Field(ary, fields) {
        const result = []
        if (!ary || ary.length == 0) {
          return result
        }
        ary.forEach((s) => {
          const r = {}
          Object.entries(s).forEach((kv, index) => {
            const f = fields[index]
            if (f) {
              r[f] = kv[1]
            }
          })
          result.push(r)
        })
        return result
      },
      dialogCancelTree() {
        this.setDialogData([])
        this.customDialogShowTree = false
        this.$emit('hideModel')
      },
      //查询
      search(resetPagintion, data, cb) {
        let querys = [] //查询条件
        let queryFilter = {}
        if (JSON.stringify(this.pagination) == '{}') {
          this.pagination = { page: 1, pageSize: 10, showTotal: true }
        }
        let pageBean = { pageBean: this.pagination }
        if (resetPagintion) {
          pageBean.pageBean = { page: 1, pageSize: 10, showTotal: true }
        }
        //用户输入的
        if (this.queryParams.length != 0 && this.queryParams[0] != '') {
          this.conditionBind.forEach((item, index) => {
            if (this.queryParams[index][item.field]) {
              querys.push({
                property: item.field,
                value: this.queryParams[index][item.field],
                group: 'main',
                operation: 'LIKE',
                relation: 'AND',
              })
            }
          })
        }
        //查询条件
        data &&
          data.forEach((d) => {
            const shouldPush =
              d.value != null && d.value != undefined && d.value != ''
            // 高级搜索中支持一个搜索框中关联多个属性进行搜索
            if (d.prop.indexOf(',') > 0) {
              const propAry = utils['a' /* default */].stringSplit(d.prop, ',')
              if (propAry && propAry.length > 0) {
                const groupName = `group_${propAry[0]}`
                this.clearQueryByGroupName(groupName)
                shouldPush &&
                  propAry.forEach((p) => {
                    querys.push({
                      property: p,
                      value: d.value,
                      group: groupName,
                      relation: 'OR',
                      operation: d.operation,
                    })
                  })
              }
            } else {
              shouldPush &&
                querys.push({
                  property: d.prop,
                  value: d.value,
                  group: 'advance',
                  relation: d.relation,
                  operation: d.operation,
                })
            }
          })

        //参数传入的查询拼接
        if (this.param) {
          this.param.forEach((item) => {
            querys.push({
              property: item.field,
              value:
                item.bindType === 2
                  ? item.bind
                  : item.bindType === 3
                  ? this.executeScriptResult
                  : this.getCurrentValue(item.bind, item.default),
              group: 'main',
              operation: item.operation ? item.operation : 'LIKE',
              relation: 'AND',
            })
          })
        }
        //来自组合对话框的
        if (
          this.combinationTreeQuerys &&
          this.combinationTreeQuerys.length != 0
        ) {
          for (let i = 0; i < this.combinationTreeQuerys.length; i++) {
            querys.push(this.combinationTreeQuerys[i])
          }
        }

        // post restful接口，并且配置了post参数。则以post参数作为请求参数
        if (
          this.customDialog.dsType != 'dataSource' &&
          this.customDialog.dataParam &&
          this.customDialog.dataParam.constructor == String
        ) {
          let param = this.param
          // 构建上下文数据对象
          let ctx = {}
          //根据路径构建想要的分页属性
          let obj = {}
          this.getLastKeyByPath(
            obj,
            this.customDialog.pageKey,
            pageBean.pageBean.page
          )
          this.getLastKeyByPath(
            obj,
            this.customDialog.pageSizeKey,
            pageBean.pageBean.pageSize
          )
          this.getLastKeyByPath(
            obj,
            this.customDialog.totalKey,
            pageBean.pageBean.total
          )
          querys &&
            querys.length &&
            querys.forEach((element) => {
              ctx[element.property] = element.value
            })
          const queryParamMap = this.getSearchValueByKey()
          queryParamMap.pageSize = pageBean.pageBean.pageSize
          queryParamMap.page = pageBean.pageBean.page
          queryParamMap.total = pageBean.pageBean.total
          // 添加用户id 岗位id 组织id
          try {
            if (this.$requestConfig.getUserId()) {
              ctx.userId = this.$requestConfig.getUserId()
            }
            if (this.$requestConfig.getOrgId()) {
              ctx.orgId = this.$requestConfig.getOrgId()
            }
            if (this.$requestConfig.getPostId()) {
              ctx.postId = this.$requestConfig.getPostId()
            }
          } catch (e) {}
          const exp = utils.parseExp(this.customDialog.dataParam, {
            ...ctx,
            ...queryParamMap,
            ...this.fixedParams,
          })
          try {
            param = utils.isJSON(exp) ? JSON.parse(exp) : exp
            const dataParam = utils.isJSON(this.customDialog.dataParam)
              ? JSON.parse(this.customDialog.dataParam)
              : this.customDialog.dataParam
            const queryList =
              dataParam &&
              dataParam.querys &&
              dataParam.querys.map((item) => {
                const bindKey =
                  item.value && item.value.replace('${', '').replace('}', '')
                const isFixedValue = item.value && !item.value.startsWith('${')
                const currentFixedVal = this.fixedParams[bindKey]
                  ? this.fixedParams[bindKey]
                  : isFixedValue
                  ? item.value
                  : ''
                return {
                  ...item,
                  value:
                    currentFixedVal ||
                    queryParamMap[bindKey] ||
                    ctx[bindKey] ||
                    '',
                }
              })
            param.querys = queryList
            if (!param.pageBean || param.pageBean == undefined) {
              param.pageBean = {}
            }
            if (this.customDialog.needPage) {
              param.pageBean = obj
            } else {
              param.pageBean = {}
              param.pageBean.pageSize = -1
            }
            //构造请求的参数
            let requestParam = {
              pageBean: param,
              queryUrl: this.customDialog.queryUrl,
              requestType: this.customDialog.requestType,
              dsType: this.customDialog.dsType,
              listKey: this.customDialog.listKey,
              pageKey: this.customDialog.pageKey,
              pageSizeKey: this.customDialog.pageSizeKey,
              totalKey: this.customDialog.totalKey,
              header: this.customDialog.header,
              conditionfield: this.customDialog.conditionfield,
            }
            this.getDialoglistJson(requestParam).then(() => {
              this.checkList(cb)
            })
          } catch (e) {
            this.$message.error(`body参数不是有效的JSON格式${param}`)
          }
        } else {
          if (querys.length > 0) {
            queryFilter = this.handlePostData({
              pageBean: pageBean.pageBean,
              querys,
            })
            this.customDialog.pageBean = queryFilter
            this.getDialoglistJson(this.customDialog).then(() => {
              this.checkList(cb)
            })
          } else {
            this.customDialog.pageBean = pageBean
            this.getDialoglistJson(this.customDialog).then(() => {
              this.checkList(cb)
            })
          }
        }
        this.tableRadioVal = ''
        //this.clearAllSelects()
      },
      getSearchValueByKey() {
        let queryParamsObj = {}
        if (this.queryParams.length > 0) {
          queryParamsObj = this.conditionBind.reduce((pre, cur, index) => {
            pre[cur.field] = this.queryParams[index][cur.field]
            return pre
          }, {})
        }
        return queryParamsObj
      },
      getLastKeyByPath(obj, path, value) {
        if (!obj || !path || path.constructor != String) {
          return
        }
        if (!/^\w?.*[\w|\]]$/.test(path)) {
          return
        }
        let pathAry = path.split('.')
        if (pathAry.length == 1) {
          obj[path] = value
        } else {
          let length = pathAry.length
          obj[pathAry[length - 1]] = value
        }
      },
      //重置
      reset() {
        this.queryParams.forEach((paramObj, index) => {
          for (let key in paramObj) {
            this.queryParams[index][key] = ''
          }
        })
        //组合树重置
        let nodes = {}
        if (this.$refs.combinationTree) {
          nodes = this.$refs.combinationTree.store.nodesMap
        }
        for (let key in nodes) {
          nodes[key].expanded = false
        }
        this.combinationTreeQuerys.splice(0)
        this.search(true)
      },
      getCurrentValue(bind, defaultValue) {
        let value = null
        const pInst = utils.getOnlineFormInstance(this)
        const bindPath = bind.replace(`${this.subPath}.`, '')
        if (this.sunIndex || this.sunIndex === 0) {
          value = utils.getValueByPath(
            this.currentSubData[this.subIndex],
            bindPath,
            this.sunIndex || this.sunIndex === 0 ? this.sunIndex : null
          )
        } else {
          value = utils.getValueByPath(
            pInst,
            bind,
            this.subIndex || this.subIndex === 0 ? this.subIndex : null
          )
        }
        return value || defaultValue
      },
      checkList(cb) {
        cb && cb()
        if (this.isSetPk !== '') {
          this.checkBoxDataAll = this.selects
          if (this.customDialog.selectNum === 1) {
            let resData = this.dialogData.findIndex(
              (item) =>
                item.hasOwnProperty(this.isSetPk) &&
                item[this.isSetPk] == this.checkBoxDataAll[0][this.isSetPk]
            )
            this.tableRadioVal = resData
          } else {
            let selectedMarkList = []
            this.checkBoxDataAll.map((item) => {
              if (item.hasOwnProperty(this.isSetPk)) {
                selectedMarkList.push(item[this.isSetPk])
              }
            })
            this.dialogData.forEach((row) => {
              if (selectedMarkList.includes(row[this.isSetPk])) {
                this.$nextTick(() => {
                  this.$refs.orgTable.toggleRowSelection(row, true)
                })
              } else {
                this.$nextTick(() => {
                  this.$refs.orgTable.toggleRowSelection(row, false)
                })
              }
            })
          }
        }
      },
      //点击列表某一条数据时触发
      orgRowClick(row, column, event) {
        if (this.customDialog.selectNum === 1) {
          $(event.currentTarget.children[0].children[0].children[0]).trigger(
            'click'
          )
          this.selectOrgs = []
          this.selectOrgs.push(row)
          this.selects = this.selectOrgs
        } else if (this.customDialog.selectNum != 1) {
          this.isCurrentChange = false
          //判断点击列表数据时复选框是否勾选  selected：true不勾选，false勾选
          let resData = this.isSetPk
            ? this.selectOrgs.findIndex(
                (item) =>
                  item.hasOwnProperty(this.isSetPk) &&
                  item[this.isSetPk] == row[this.isSetPk]
              )
            : this.indexArray(this.selectOrgs, row)
          let selected =
            this.selectOrgs && this.selectOrgs.length > 0 && resData !== -1
          if (selected) {
            this.isCurrentChange = true
            this.selectOrgs.splice(resData, 1)
            if (this.isSetPk) {
              let selectsIndex = this.selects.findIndex(
                (item) =>
                  item.hasOwnProperty(this.isSetPk) &&
                  item[this.isSetPk] == row[this.isSetPk]
              )
              if (selectsIndex !== -1) {
                this.selects.splice(selectsIndex, 1)
              }
            } else {
              this.selects = this.selectOrgs
            }
          }
          this.$refs.orgTable.toggleRowSelection(row)
          this.syncSelection2selects()
        }
      },
      //列表复选框有改变时触发
      orgTableSelection(selection) {
        //全选的情况特殊处理(为了与原本功能逻辑不冲突,先复制一份旧的选中数据.然后拿到全选事件中去计算)
        this.oldselectOrgs = _.cloneDeep(this.selectOrgs)
        //多选
        if (this.customDialog.selectNum != 1 && !this.isCurrentChange) {
          if (selection && selection.length > 0) {
            if (
              selection.length == 1 &&
              (!this.selectOrgs || this.selectOrgs.length == 0)
            ) {
              this.selectOrgs = selection
            } else if (
              (!this.selectOrgs || this.selectOrgs.length == 0) &&
              selection.length > 1
            ) {
              if (!this.selectOrgs) {
                this.selectOrgs = []
              }
              for (let i = selection.length - 1; i >= 0; i--) {
                this.selectOrgs.push(selection[i])
              }
            } else if (this.isCurrentChange && selection.length >= 10) {
              if (!this.selectOrgs) {
                this.selectOrgs = []
              } else {
                for (let u = this.selectOrgs.length - 1; u >= 0; u--) {
                  let res = this.indexArray(selection, this.selectOrgs[u])
                  if (res != -1) {
                    this.selectOrgs.splice(res, 1)
                  }
                }
              }
              for (let i = 0; i < selection.length; i++) {
                this.selectOrgs.push(selection[i])
              }
            } else {
              for (let i = selection.length - 1; i >= 0; i--) {
                this.selectOrgs.push(selection[i])
                break
              }
            }
          }
        }
        this.syncSelection2selects()
      },
      //点击列表某一个复选框时触发
      onTableSelect(rows, row) {
        this.isCurrentChange = false
        //判断点击列表数据时复选框是否勾选  selected：true不勾选，false勾选
        let resData = this.selectOrgs.findIndex((item) => {
          if (this.isSetPk && item.hasOwnProperty(this.isSetPk)) {
            item[this.isSetPk] == row[this.isSetPk]
          } else {
            return _.isEqual(item, row)
          }
        })
        let selected =
          this.selectOrgs && this.selectOrgs.length > 0 && resData !== -1
        if (selected) {
          this.isCurrentChange = true
          this.selectOrgs.splice(resData, 1)
          let selectsIndex = this.selects.findIndex((item) => {
            if (this.isSetPk && item.hasOwnProperty(this.isSetPk)) {
              item[this.isSetPk] == row[this.isSetPk]
            } else {
              return _.isEqual(item, row)
            }
          })
          if (selectsIndex !== -1) {
            this.selects.splice(selectsIndex, 1)
          }
        }
        this.syncSelection2selects()
      },
      selectAll(selection) {
        if (this.oldselectOrgs != null && selection.length > 0) {
          for (let x = 0; x < selection.length; x++) {
            if (this.indexArray(this.oldselectOrgs, selection[x]) === -1) {
              this.oldselectOrgs.push(selection[x])
            }
          }
          this.selectOrgs = _.cloneDeep(this.oldselectOrgs)
        } else {
          this.selectOrgs = _.cloneDeep(selection)
        }
        this.syncSelection2selects()
      },
      checkNode(data, this_, pnode) {
        if (!data.Pid) {
          //不清楚是不是有地方数据返回是Pid，这里做个判断
          data.Pid = data.pid
        }
        if (data.Pid) {
          let node = this_.$refs.tree.getNode(data.Pid)
          node.indeterminate = true
          if (node.data.Pid) {
            this_.$refs.tree.getNode(node.data.Pid).indeterminate = true
            this.checkNode(
              this_.$refs.tree.getNode(node.data.Pid).data,
              this_,
              this_.$refs.tree.getNode(node.data.Pid)
            )
          }
          if (!node.indeterminate) {
            node.indeterminate = true
          }
        } else if (pnode && !pnode.indeterminate) {
          pnode.indeterminate = true
        }
      },
      //回车查询
      searchEnterFun: function (e) {
        var keyCode = window.event ? e.keyCode : e.which
        if (keyCode == 13) {
          this.search()
        }
      },
      handleSizeChange: function (size) {
        this.isCurrentChange = true
        //每页下拉显示数据
        this.pagination.pageSize = size
        let queryValue =
          (this.$refs.searchPanel && this.$refs.searchPanel.fieldArray) || null
        this.search(false, queryValue)
      },
      handleCurrentChange: function (currentPage) {
        this.isCurrentChange = true
        //点击第几页
        let queryValue =
          (this.$refs.searchPanel && this.$refs.searchPanel.fieldArray) || null
        this.pagination.page = currentPage
        this.search(false, queryValue)
      },
      dialogCancel() {
        const this_ = this
        this.$emit('hideModel')
        this_.queryParam = ''
        this.setDialogData([])
        this_.customDialogShowList = false
        //判断是否是点击了确认再点击取消的  inputVal没有值则表示直接点击的取消
        if (!this_.inputVal) {
          this_.selectOrgs = []
          this_.selects = []
        } else {
          this_.selectOrgs = this_.showData ? [...this_.showData] : ''
          this_.selects = [...this_.selectOrgs]
          this.checkBoxDataAll = [...this_.selectOrgs]
        }
      },
      afterOpen() {
        //打开对话框之后加载树
        this.loadCombinationTree()
      },
      dialogConfirm(cb) {
        if (this.isPreview) {
          //监听列表预览页面的确认事件
          this.customDialogShowList = false
          this.$message.success('返回数据为：' + JSON.stringify(this.selects))
          return
        }
        this.$emit('hideModel')
        this.queryParam = ''
        if (this.customDialog.selectNum !== 1) {
          this.selects = this.selectOrgs
        }
        if (this.isSubtableBackfill) {
          this.$emit('customDialog-confirm', this.selectOrgs, cb)
        } else {
          this.customDialogShowList = false
          this.calacInputSuffixHeight()
          this.syncInputValue()
        }
      },
      // 同步选择结果
      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.customDialog.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.customDialog.dsType == 'dataSource'
              ? returnStr[i].field.toLowerCase()
              : returnStr[i].field
          comment[i] =
            this.customDialog.dsType == 'dataSource'
              ? returnStr[i].comment.toLowerCase()
              : returnStr[i].comment
        }
        var s = this.selectOrgs
        if (this.selectOrgs) {
          this.showData = [...this.selectOrgs]
          this.checkBoxDataAll = [...this.selectOrgs]
        } else {
          this.showData = []
          this.checkBoxDataAll = []
        }
        if (this.customDialog.selectNum === 1) {
          s = this.selectOrgs
        }
        if (this.customDialog.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.customDialog.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('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 +
                  ']关联查询取值参数未绑定表单字段'
              )
            }
          }
        }
      },
      calacInputSuffixHeight() {
        this.$emit('calacInputSuffixHeight')
      },
      removeSelectOrg(item) {
        if (this.customDialog.selectNum === 1) {
          this.selectOrgs.splice(item, 1)
          this.showData.splice(item, 1)
        } else {
          //树形
          if (this.propsData.length > 0) {
            this.propsData.splice(item, 1)
          }
          if (this.showData.length > 0) {
            this.showData.splice(item, 1)
          }
          //列表
          if (this.selectOrgs != null) {
            this.selectOrgs.splice(item, 1)
            this.checkBoxDataAll.splice(item, 1)
          }
        }
        this.syncInputValue()
      },
      clearAll() {
        this.checkBoxDataAll = []
        this.selectOrgs = []
        this.selects = []
        this.showData = []
        this.propsData = []
        this.pagination = {}
        this.syncInputValue()
        this.setDialogData([])
        this.$refs.orgTable && this.$refs.orgTable.clearSelection()
      },
      //判断数据是否包含某个对象，并返回数据包含对象的下标
      indexArray(array, item) {
        if (array.length == 0) {
          return -1
        }
        for (let i = 0; i < array.length; i++) {
          if (JSON.stringify(array[i]) == JSON.stringify(item)) {
            return i
          }
        }
        return -1
      },
      // 处理POST请求时的参数
      handlePostData(queryFilter) {
        if (
          !this.customDialog.dataParam ||
          this.customDialog.dataParam.constructor != String
        ) {
          return queryFilter
        }
        // 构建上下文数据对象
        let ctx = {}
        queryFilter &&
          queryFilter.querys.forEach((element) => {
            ctx[element.property] = element.value
          })
        const exp = utils.parseExp(this.customDialog.dataParam, ctx)
        try {
          return JSON.parse(exp)
        } catch (e) {
          CustomQuery._throwException(
            'POST参数不是有效的JSON格式：' + this.customDialog.dataParam
          )
        }
      },
      loadTree(node, resolve) {
        if (node) {
          let this_ = this
          let displayField =
            this_.customDialog.style == 2
              ? this_.combiTreeDisplayField
              : this_.displayField
          //全部展示
          if (this.customDialog.treeDataMode === 0) {
            resolve(
              this.treeList.filter(
                (value) =>
                  value[displayField.pid] === node.data[displayField.id]
              )
            )
            if (this.showData && this.showData.length > 0) {
              setTimeout(() => {
                this.showData.forEach((v) => {
                  if (!v.Pid) {
                    //不清楚是不是有地方数据返回是Pid,这里做个判断
                    v.Pid = v.pid
                  }
                  if (v.Pid == node.key) {
                    this_.$refs.tree && this_.$refs.tree.setChecked(v, true)
                  } else {
                    this_.checkNode(v, this_)
                  }
                })
              }, 400)
            }
          } else {
            //逐级展示
            let displayfield = JSON.parse(this.customDialog.displayfield)
            if (node.data instanceof Object && node.data[displayfield.id]) {
              this.customDialogTreeShow(
                this.pageParam,
                node,
                'click',
                (req) => {
                  this.$requestConfig
                    .request({
                      url: req.url,
                      method: req.requestType == 'POST' ? 'post' : 'get',
                      data: req.paramsObj,
                    })
                    .then((res) => {
                      resolve(res)
                    })
                }
              )
            } else {
              resolve([])
            }
          }
        }
      },
      //加载树的信息
      toTreeData(data, id, pid, name, pvalue) {
        this.treeNodeName = name
        // 建立个树形结构,需要定义个最顶层的父节点，pvalue是0
        return this.translateDataToTree(data, pid, id, name, pvalue)
      },
      translateDataToTree(data, pid, id) {
        //把树数据有子节点的数据全部过滤掉（只留父节点的数据）
        let tile2nest = []
        if (this.customDialog.treeDataMode === 0) {
          tile2nest = this.tile2nest(data, id, pid)
        } else {
          tile2nest = utils.tile2nest(data, id, pid)
        }
        return tile2nest || []
      },
      combiTreeClick(paramObj) {
        this.treeNodeValue = paramObj[this.treeNodeName]
        //组合对话框点击左树
        //清空旧的
        this.combinationTreeQuerys.splice(0)
        let combinationRule = JSON.parse(this.customDialog.combinationRule)
        if (!combinationRule.rules || combinationRule.rules.length == 0) {
          return
        }
        let rules = combinationRule.rules
        for (let i = 0; i < rules.length; i++) {
          let value = paramObj[rules[i].treeField]
          let property = rules[i].listField
          this.combinationTreeQuerys.push({
            property: property,
            value: value,
            group: 'treeGroup',
            operation: this.getOperation(rules[i].condition),
            relation: 'AND',
          })
        }
        this.search(true)
        this.$emit('node-click', paramObj)
      },
      //获取运算符号
      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'
        }
      },
      toggleTree() {
        if (this.treeShow) {
          this.treeShow = false
          this.transtionWidth = 0
          this.toggleBtn = 'el-icon-arrow-right'
        } else {
          this.treeShow = true
          this.transtionWidth = 300
          this.toggleBtn = 'el-icon-arrow-left'
        }
      },
      loadCombinationTree() {
        if (this.customDialog.style != 2) {
          return
        }

        let combinationRule = JSON.parse(this.customDialog.combinationRule)

        this.combinationRule = combinationRule
        let treeAlias = combinationRule.leftTree
        //获取对话框数据
        this.$requestConfig.getCustomDialogByAlias(treeAlias).then((resp) => {
          let treeDialog = resp
          let displayField = JSON.parse(treeDialog.displayfield)
          this.leftTreeTitle = treeDialog.name
          let requestType =
            treeDialog.dsType == 'dataSource'
              ? 'get'
              : treeDialog.requestType
              ? treeDialog.requestType
              : 'post'
          let url =
            '${form}/form/customDialog/v1/getTreeData?alias=' +
            treeAlias +
            '&mapParam='

          if (this.customDialog.treeDataMode === 1) {
            url = url + '&' + displayField.pid + '=' + displayField.pvalue
          }
          let paramsObj = {}
          if (treeDialog.dsType != 'dataSource') {
            url = treeDialog.url
            let templatePa = treeDialog.dataParam
            if (treeDialog.conditionfield) {
              let conditions = JSON.parse(treeDialog.conditionfield)
              for (let i = 0; i < conditions.length; i++) {
                let con = conditions[i]
                if (requestType == 'POST') {
                  if (templatePa) {
                    templatePa = templatePa.replace(
                      new RegExp('\\{' + con.field + '\\}', 'g'),
                      con.defaultValue
                    )
                  } else {
                    paramsObj[con.field] = con.defaultValue
                  }
                } else {
                  let ljChar = url.indexOf('?') == -1 ? '?' : '&'
                  url = url + ljChar + con.field + '=' + con.defaultValue
                }
              }
              if (templatePa) {
                paramsObj = JSON.parse(templatePa)
              }
            }
          }
          let requestParams = {}
          requestParams.requestType = requestType
          requestParams.url = url
          requestParams.paramsObj = paramsObj

          this.$requestConfig
            .request({
              url: requestParams.url,
              method: 'get',
            })
            .then((resp) => {
              if (treeDialog.displayfield && treeDialog.resultfield) {
                let displayField = JSON.parse(treeDialog.displayfield)
                let resultfield = JSON.parse(treeDialog.resultfield)
                this.defaultProps.label = displayField.displayName
                this.treeList = resp

                this.combiTreeDisplayField = displayField
                this.combinationTreeData = this.toTreeData(
                  resp,
                  displayField.id,
                  displayField.pid,
                  displayField.displayName,
                  displayField.pvalue ? displayField.pvalue : '0',
                  resultfield
                )
              }
            })
        })
      },
      //打开树形动态参数输入值的对话框
      handleSave() {
        this.customDialogTreeShow(this.pageParam)
        this.dialogVisible = false
      },
      //关闭树形动态参数输入值的对话框
      handleClose() {
        this.dialogVisible = false
        this.$emit('hideModel')
      },
      // 同步已选行到已选数据中去
      syncSelection2selects() {
        // 复制一份当前已选数据
        let tmpSelects = [...this.selects]
        // 先将当前页中的数据从已选数据中移除
        this.dialogData.forEach((m) => {
          let Index = tmpSelects.findIndex(
            (item) =>
              item.hasOwnProperty(this.isSetPk) &&
              item[this.isSetPk] == m[this.isSetPk]
          )
          if (Index !== -1) {
            tmpSelects.splice(Index, 1)
          }
        })
        // 将剩余的已选数据与当前页选中的数据合并
        tmpSelects = [...tmpSelects, ...this.$refs.orgTable.selection]
        let copytmpSelects = _.cloneDeep(tmpSelects)
        if (this.isSetPk !== '') {
          this.selects = this.fn1(copytmpSelects, this.isSetPk)
        } else {
          this.selects = copytmpSelects.unique(this.fromKey.toLowerCase())
        }

        // 数组去重
        this.selects = _.uniqWith(this.selects, _.isEqual)
      },
      fn1(tempArr, isSetPk) {
        for (let i = 0; i < tempArr.length; i++) {
          for (let j = i + 1; j < tempArr.length; j++) {
            //排除custom_dialog_rowId比较
            let a = tempArr[i]
            let b = tempArr[j]
            delete a.custom_dialog_rowId
            delete b.custom_dialog_rowId
            if (
              tempArr[i].hasOwnProperty(isSetPk) &&
              tempArr[j].hasOwnProperty(isSetPk) &&
              tempArr[i][this.isSetPk] == tempArr[j][this.isSetPk] &&
              _.isEqual(a, b)
            ) {
              tempArr.splice(j, 1)
              j--
            }
          }
        }
        return tempArr
      },
      removeSelected(select) {
        let selectsIndex = this.selects.findIndex(
          (item) =>
            item[this.isSetPk] == select[this.isSetPk] &&
            item[this.fromKey] == select[this.fromKey]
        )
        if (selectsIndex !== -1) {
          this.selects.splice(selectsIndex, 1)
        }
        // 对比成功之后，取消选中
        this.$nextTick(() => {
          this.$refs.orgTable.toggleRowSelection(
            this.dialogData.find((item) => {
              if (select.hasOwnProperty(this.isSetPk)) {
                return item[this.isSetPk] == select[this.isSetPk]
              } else {
                return item[this.fromKey] == select[this.fromKey]
              }
            }),
            false
          )
          let selectOrgsIndex = this.selectOrgs.findIndex(
            (item) =>
              item[this.isSetPk] == select[this.isSetPk] &&
              item[this.fromKey] == select[this.fromKey]
          )
          if (selectOrgsIndex !== -1) {
            this.selectOrgs.splice(selectOrgsIndex, 1)
          }
        })
      },
      clearAllSelects() {
        if (this.$refs.orgTable) {
          this.selects = []
          this.selectOrgs = []
          this.$refs.orgTable.clearSelection()
        }
      },
      //显示字段排序
      sort(select, type) {
        this.selects = utils.arrayMove(this.selects, select, type)
      },
      //过滤函数
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].indexOf(value) !== -1
      },
    },
  }
</script>
<style lang="scss" scoped>
  ::v-deep {
    .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;
    }
    .el-dialog__body {
      padding: 0px !important;
      box-sizing: border-box;
      overflow-y: auto;
      @include base-scrollbar;
    }
    @media (max-width: 800px) {
      .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: calc(
          var(--customHeight) - 124px - var(--messageHeight)
        ) !important;
        @include base-scrollbar;
      }
    }
    .el-divider--vertical {
      height: 100%;
    }
  }
  .el-input__inner[aria-invalid='true'] {
    border-color: #f56c6c;
  }

  .el-select__tags {
    background: #fff;
    margin-left: 1px;
  }

  .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;
    margin-bottom: 16px;
    .search-item {
      display: flex;
      // width: 33.33%;
      margin-right: 12px;
      align-items: center;
    }
    .btn-wrap {
      line-height: 50px;
    }
    ::v-deep.search-panel__container {
      width: calc(var(--searchPanelWidth) - 48px - 40px);
      .search-field__container {
        margin-right: 0px !important;
        padding-right: 24px;
        min-height: 32px;
        height: 100%;
        .inputs.ht-form-inputs__inline {
          width: 100% !important;
          position: relative;
        }
        .inputs .el-input__inner {
          border-radius: 0;
          height: 32px !important;
          line-height: 32px !important;
        }
      }
      .search-btn__wrap {
        text-align: left;
      }
    }
  }

  .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;
    @include base-scrollbar;
    min-height: unset;
  }

  >>> .el-card__header {
    padding: 10px;
    height: 48px;
    background: #ebebeb;
    text-align: left;
    font-size: 16px;
  }

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

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

  >>> .el-main {
    padding: 0px !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;
  }
  .custom-dialog_main {
    min-height: 465px;
    @include base-scrollbar;
  }
  ::v-deep .search-field__container {
    margin-right: 50px !important;
  }
  .custom-container {
    width: 100%;
    overflow: auto;
    @include base-scrollbar;
  }
  .list-selector__selected {
    height: 100%;
    .selector-selected__wrap {
      list-style: none;
      width: calc(100% - 24px);
      padding: 10px;

      li {
        line-height: 20px;
      }

      li + li {
        margin-top: 10px;
      }

      .selector-selected__item {
        height: 48px;
        padding: 0 6px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &:hover {
          background-color: #f8f8f8;
        }

        .selector-selected__remove {
          color: #bfbfbf;
          &:hover {
            color: #409eff;
          }
        }
        .selector-selected__up {
          &:hover {
            color: #409eff;
          }
        }
        .selector-selected__down {
          &:hover {
            color: #409eff;
          }
        }

        .selector-selected__item-left {
          display: flex;
          align-items: center;
          width: 155px;
          .selector-text {
            width: 120px;
            text-align: left;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }

          .list-selector__handle {
            cursor: move;
          }

          div {
            margin-left: 10px;
          }
        }
        i {
          font-size: 16px;
        }
      }
    }
    .el-tree__empty-block {
      height: 80px;
    }
    .is-disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }
  .message {
    margin: 0 24px;
    height: var(--messageHeight);
    overflow: auto;
  }
  .custom-tree {
    height: calc(100% - var(--messageHeight)) !important;
  }
</style>
<style lang="scss">
  .hontent-custom-dialog {
    .el-dialog__header {
      padding: 16px 24px;
      .el-dialog__title {
        font-size: 16px;
        font-weight: bold;
      }
    }
    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #ebebeb;
    }
    #container {
      display: flex; /*中间弹性盒布局*/
      flex-wrap: nowrap; /*排列不下时不换行*/
      text-align: center;
      overflow: hidden;
    }
    #center {
      order: 1;
      flex: 1;
      overflow: hidden;
      .el-header {
        border-bottom: none !important;
      }
      .el-form {
        padding-right: 0;
      }
    }
    #left {
      order: 0;
      width: calc(var(--leftWidth) - 24px);
      padding-right: 24px;
    }
    #right {
      order: 2;
      width: 250px;
      padding-left: 24px;
      .el-card__body {
        height: calc(
          var(--customHeight) - var(--messageHeight) - 124px - 48px -20px
        );
      }
    }
    .el-card {
      margin-bottom: 0;
    }
    .el-card__body {
      height: calc(
        var(--customHeight) - var(--messageHeight) - var(--listTitleHeight)- 124px -
          20px
      );
      overflow: auto;
      box-sizing: border-box;
      @include base-scrollbar;
    }
    .el-card__header {
      height: 48px;
      background: #f9f9f9;
      line-height: 24px;
      text-align: left;
      font-size: 16px;
    }
    .custom-class-dialog {
      .el-card__body {
        height: calc(
          var(--customHeight) - var(--messageHeight)- var(--listTitleHeight)-
            124px - 20px
        );
      }
    }
  }
</style>
