<template>
  <el-dialog
    title="配置关联查询"
    width="70%"
    append-to-body
    top="8vh"
    :visible.sync="selectQueryDialog"
    v-if="selectQueryDialog"
    :close-on-click-modal="false"
  >
    <el-button
      class="btn-padding"
      icon="el-icon-plus"
      style="margin-bottom: 5px;"
      @click="
        custQueryJson.push({
          entType: 'main',
          desc: '',
          key: `${Date.parse(new Date())}_${Math.ceil(Math.random() * 99999)}`
        })
      "
      v-if="allowAdd"
      >添加关联查询</el-button
    >
    <el-tag type="warning"
      >当前下拉框的值发生变化时触发关联查询，可以添加多个关联查询（不能重复）。</el-tag
    >
    <div style="width:100%;height: 550px;overflow: auto;">
      <div
        v-for="(condition, indexCondition) in custQueryJson"
        :key="indexCondition"
      >
        <table
          class="form-table choiceType-table"
          style="margin-bottom: 1px;"
          cellspacing="0"
          cellpadding="0"
          border="0"
        >
          <tbody>
            <tr>
              <th width="100px">关联查询:</th>
              <td>
                <ht-load-data
                  ref="queryLoadData"
                  url="/form/customQuery/v1/list"
                  requestMethod="post"
                  context="form"
                  @after-load-data="afterCustomQueryLoadData"
                ></ht-load-data>
                <el-row style="min-width: 251px;">
                  <el-col :span="12">
                    <ht-select
                      clearable
                      filterable
                      :key="condition.key"
                      @change="setSelectQuery(condition.alias, indexCondition)"
                      v-model="condition.alias"
                      :options="customQueryList"
                      :props="{key: 'alias', value: 'name'}"
                      style="width: 100%;"
                  /></el-col>
                  <el-col :span="12">
                    <el-button
                      class="btn-padding"
                      icon="el-icon-refresh"
                      style="margin-left: 10px;"
                      @click="
                        setSelectQuery(
                          condition.alias,
                          indexCondition,
                          'refresh'
                        )
                      "
                    ></el-button>
                    <el-button
                      class="btn-padding"
                      icon="el-icon-delete"
                      style="margin-left: 10px;"
                      @click="custQueryJson.remove(condition)"
                    ></el-button
                  ></el-col>
                </el-row>
              </td>
              <th v-if="allowAdd" width="100px">实体类型:</th>
              <td v-if="allowAdd">
                <ht-select
                  :options="[
                    {code: 'main', name: '主实体'},
                    {code: 'sub', name: '子实体'}
                  ]"
                  :props="{key: 'code', value: 'name'}"
                  v-model="condition.entType"
                  validate="required"
                  @change="changeEntType(condition, indexCondition)"
                />
              </td>
              <th v-if="condition.entType == 'sub'" width="100px">选择子表:</th>
              <td v-if="condition.entType == 'sub'">
                <ht-select
                  :options="queryEntMap[condition.entType]"
                  :props="{key: 'path', value: 'desc'}"
                  v-model="condition.subPath"
                  validate="required"
                />
              </td>
            </tr>
            <tr>
              <th width="100px">用途说明:</th>
              <td colspan="6">
                <ht-input
                  class="desc-input"
                  v-model="condition.desc"
                ></ht-input>
              </td>
            </tr>
          </tbody>
        </table>
        <el-tabs type="border-card" style="margin-bottom:20px;">
          <el-tab-pane label="参数绑定">
            <table
              class="form-table choiceType-table"
              cellspacing="0"
              cellpadding="0"
              border="0"
            >
              <tbody>
                <tr
                  v-for="(bind, indexBind) in filterConditionField(
                    custQueryJson[indexCondition].conditionfield
                  )"
                  :key="indexBind"
                >
                  <th width="110px">{{ bind.comment }}:</th>
                  <td>
                    <div class="config-wrap">
                      <ht-select
                        clearable
                        style="margin-top: 18px"
                        :key="`${condition.key}_${indexBind}`"
                        v-model="bind.fieldPath"
                        :options="
                          getBindOptions(condition.entType, condition.subPath)
                        "
                        :props="{key: 'name', value: 'desc'}"
                      >
                        <template slot-scope="{options}">
                          <el-option-group
                            v-for="(group, idenxOptions) in options"
                            :key="idenxOptions"
                            :label="group.desc"
                          >
                            <el-option
                              v-for="item in group.children"
                              :key="item.id"
                              :label="item.desc"
                              :value="'data.' + item.path + '.' + item.name"
                            ></el-option>
                          </el-option-group>
                        </template>
                      </ht-select>
                      <div class="empty-box">
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="参数为空时返回全部结果数据"
                          placement="top"
                        >
                          <i class="el-icon-question"></i>
                        </el-tooltip>
                        为空时绑定值:
                        <ht-input
                          v-model="bind.emptyValue"
                          placeholder="请输入"
                        ></ht-input>
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
          <el-tab-pane label="设置返回值">
            <table
              class="form-table choiceType-table"
              cellspacing="0"
              cellpadding="0"
              border="0"
            >
              <tbody>
                <tr
                  v-for="(bind, indexBind) in custQueryJson[indexCondition]
                    .resultfield"
                  :key="indexBind"
                >
                  <th width="110px">{{ bind.comment }}:</th>
                  <td>
                    <ht-select
                      clearable
                      :key="`${condition.key}_${indexBind}`"
                      v-model="bind.fieldPath"
                      :options="
                        getBindOptions(
                          condition.entType,
                          condition.subPath,
                          'backVal'
                        )
                      "
                      :props="{key: 'name', value: 'desc'}"
                    >
                      <template slot-scope="{options}">
                        <el-option-group
                          v-for="(group, idenxOptions) in options"
                          :key="idenxOptions"
                          :label="group.desc"
                        >
                          <el-option
                            v-for="item in group.children"
                            :key="item.id"
                            :label="item.desc"
                            :value="'data.' + item.path + '.' + item.name"
                          ></el-option>
                        </el-option-group>
                      </template>
                    </ht-select>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
          <el-tab-pane v-if="allowAdd" label="触发方式">
            <table
              class="form-table choiceType-table"
              cellspacing="0"
              cellpadding="0"
              border="0"
            >
              <tbody>
                <tr>
                  <th width="180px">加载方式:</th>
                  <td>
                    <ht-checkbox
                      v-model="custQueryJson[indexCondition].triggerTime"
                      :options="[
                        {key: 'load', value: '加载时触发'},
                        {key: 'change', value: '值变化触发'}
                      ]"
                    />
                  </td>
                </tr>
                <tr
                  v-if="
                    custQueryJson[indexCondition].triggerTime &&
                      custQueryJson[indexCondition].triggerTime.indexOf(
                        'load'
                      ) != -1
                  "
                >
                  <th width="180px">加载时触发:</th>
                  <td>
                    <ht-radio
                      v-model="custQueryJson[indexCondition].noValuabletrigger"
                      :options="[
                        {key: false, value: '始终触发'},
                        {key: true, value: '有值不触发'}
                      ]"
                    ></ht-radio>
                  </td>
                </tr>
                <tr
                  v-if="
                    custQueryJson[indexCondition].triggerTime &&
                      custQueryJson[indexCondition].noValuabletrigger &&
                      custQueryJson[indexCondition].noValuabletrigger === true
                  "
                >
                  <th width="180px">判断有值字段:</th>
                  <td>
                    <ht-select
                      clearable
                      v-model="custQueryJson[indexCondition].noValuableField"
                      :options="
                        getBindOptions(condition.entType, condition.subPath)
                      "
                      :props="{key: 'name', value: 'desc'}"
                    >
                      <template slot-scope="{options}">
                        <el-option-group
                          v-for="(group, idenxOptions) in options"
                          :key="idenxOptions"
                          :label="group.desc"
                        >
                          <el-option
                            v-for="item in group.children"
                            :key="item.id"
                            :label="item.desc"
                            :value="'data.' + item.path + '.' + item.name"
                          ></el-option>
                        </el-option-group>
                      </template>
                    </ht-select>
                  </td>
                </tr>
                <tr
                  v-if="
                    custQueryJson[indexCondition].triggerTime &&
                      custQueryJson[indexCondition].triggerTime.indexOf(
                        'change'
                      ) != -1
                  "
                >
                  <th width="180px">监听值变化字段:</th>
                  <td>
                    <ht-select
                      clearable
                      v-model="custQueryJson[indexCondition].triggerField"
                      :options="
                        getBindOptions(condition.entType, condition.subPath)
                      "
                      :props="{key: 'name', value: 'desc'}"
                    >
                      <template slot-scope="{options}">
                        <el-option-group
                          v-for="(group, idenxOptions) in options"
                          :key="idenxOptions"
                          :label="group.desc"
                        >
                          <el-option
                            v-for="item in group.children"
                            :key="item.id"
                            :label="item.desc"
                            :value="'data.' + item.path + '.' + item.name"
                          ></el-option>
                        </el-option-group>
                      </template>
                    </ht-select>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="selectQueryDialog = false">取消</el-button>
      <el-button type="primary" @click="saveCustQuery" size="small"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import flow from '@/api/flow.js'
export default {
  name: 'select-query-dialog',
  components: {},
  data() {
    return {
      selectQueryDialog: false,
      custQueryJson: [],
      customQueryList: []
    }
  },
  props: ['customQuerys', 'returnData', 'queryEntMap', 'allowAdd'],
  mounted() {
    if (this.customQuerys && this.customQuerys.length > 0) {
      this.customQueryList = [...this.customQuerys]
    }
  },
  methods: {
    showDialog(queryJson) {
      this.selectQueryDialog = true
      if (queryJson && queryJson.length > 0) {
        this.custQueryJson = queryJson
      }
    },
    afterCustomQueryLoadData(data) {
      this.customQueryList = data.rows
    },
    saveCustQuery() {
      this.$emit('saveCustQueryJson', this.custQueryJson)
      this.selectQueryDialog = false
    },
    //关联查询清空时，清空对应配置项
    clearRelevanceConfig() {
      if (this.custQueryJson && this.custQueryJson.length) {
        this.custQueryJson.map(item => {
          if (!item.alias) {
            item.conditionfield &&
              item.conditionfield.forEach(it => {
                it.fieldPath = ''
              })
            item.resultfield &&
              item.resultfield.forEach(it => {
                it.fieldPath = ''
              })
          }
        })
      }
    },
    async setSelectQuery(alias, index, type = '') {
      this.clearRelevanceConfig()
      if (!alias || !this.customQueryList || !this.customQueryList.length) {
        return
      }
      if (type === 'refresh') {
        if (this.$refs.queryLoadData && this.$refs.queryLoadData[0]) {
          await this.$refs.queryLoadData[0].getData()
        }
      }
      const _this = this
      const cloneCustomQueryList = _.cloneDeep(_this.customQueryList)
      cloneCustomQueryList.forEach(item => {
        //判断选择的关联查询是否存在
        if (alias == item.alias) {
          if (typeof item.conditionfield == 'string') {
            const conditionField = JSON.parse(item.conditionfield) || [] //parseToJson(item.customQuery.conditionfield);
            const newConditionField = conditionField.map(it => {
              return {
                ...it,
                emptyValue: '无'
              }
            })
            item.conditionfield = newConditionField
            item.resultfield = JSON.parse(item.resultfield) // parseToJson(item.customQuery.resultfield);
            item.conditionfield.forEach(res => {
              _this.$set(res, 'fieldPath', '') //关联查询条件字段绑定的表单参数路径
            })
            item.resultfield.forEach(res => {
              _this.$set(res, 'fieldPath', '') //关联查询返回字段绑定的表单参数路径
            })
          }
          // 刷新最新配置
          if (type === 'refresh') {
            item.conditionfield.forEach((k, i) => {
              let oldItem = this.custQueryJson[index].conditionfield.find(
                sub => {
                  return sub.field === k.field
                }
              )
              if (oldItem) {
                item.conditionfield[i] = oldItem
              }
            })
            item.resultfield.forEach((k, i) => {
              let oldItem = this.custQueryJson[index].resultfield.find(sub => {
                return sub.field === k.field
              })
              if (oldItem) {
                item.resultfield[i] = oldItem
              }
            })
            this.custQueryJson[index].conditionfield = item.conditionfield
            this.custQueryJson[index].resultfield = item.resultfield
            this.custQueryJson[index].name = item.name
            this.$message.info('更新配置成功！点击保存表单后生效。')
            return
          }
          //把当前对象克隆一份到控件属性配置
          _this.custQueryJson = _this.custQueryJson.map((it, idx) => {
            const newObj = idx === index ? item : {}
            return {
              ...it,
              ...newObj
            }
          })
          // 删除多余属性
          _this.slimCustomQuery(_this.custQueryJson[index])
        }
      })
    },
    // 当字段与关联查询绑定后，将关联查询中多余的属性删除
    slimCustomQuery(customQuery) {
      if (customQuery && customQuery.constructor == Object) {
        // 删除多余的属性
        delete customQuery['id']
        delete customQuery['createTime']
        delete customQuery['pkVal']
        delete customQuery['objName']
        delete customQuery['needPage']
        delete customQuery['pageSize']
        delete customQuery['dsalias']
        delete customQuery['dataParam']
        delete customQuery['sortfield']
        delete customQuery['diySql']
        delete customQuery['isTable']
        delete customQuery['sqlBuildType']
        // delete customQuery["dsType"];
        delete customQuery['url']
        delete customQuery['header']
        delete customQuery['requestType']
        delete customQuery['pageKey']
        delete customQuery['pageSizeKey']
        delete customQuery['totalKey']
        delete customQuery['listKey']
      }
    },
    getBindOptions(entType, path, type = '') {
      let options = []
      if (this.allowAdd) {
        if (entType === 'main') {
          return this.queryEntMap['main']
        } else if (entType === 'sub') {
          // 如果不存在子表时 会报错 子表下拉选项为空
          if (!this.queryEntMap['sub']) {
            return []
          }
          const subFieldList = this.queryEntMap['sub'].filter(
            item => item.path == path
          )
          return type
            ? subFieldList
            : [...this.queryEntMap['main'], ...subFieldList]
        }
      } else {
        return this.returnData
      }
    },
    filterConditionField(data) {
      let conditionField = []
      if (data && data.length > 0) {
        //选择接口时，配置为参数传入defaultType为4；其他类型元件，参数传入defaultType为1
        conditionField = data.filter(
          item => item.defaultType === '1' || item.defaultType === '4'
        )
      }
      return conditionField
    },
    changeEntType(condition, indexCondition) {
      this.$set(this.custQueryJson[indexCondition], 'desc', '')
      this.$set(this.custQueryJson[indexCondition], 'triggerTime', '')
      this.$set(this.custQueryJson[indexCondition], 'noValuabletrigger', '')
      this.$set(this.custQueryJson[indexCondition], 'triggerField', '')
      this.$set(this.custQueryJson[indexCondition], 'noValuableField', '')
      if (this.custQueryJson[indexCondition].hasOwnProperty('conditionfield')) {
        this.custQueryJson[indexCondition].conditionfield.forEach(item => {
          item.fieldPath = ''
          item.emptyValue = '无'
        })
      }
      if (this.custQueryJson[indexCondition].hasOwnProperty('resultfield')) {
        this.custQueryJson[indexCondition].resultfield.forEach(item => {
          item.fieldPath = ''
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.config-wrap {
  display: flex;
  .empty-box {
    padding-left: 16px;
  }
}
::v-deep {
  .desc-input.inputs.ht-form-inputs__inline {
    width: 100%;
  }
  .choiceType-table{
  .btn-padding{
    padding: 7.8px 15px;
  }
}
}


</style>
