<template>
  <div class="fullheight">
    <div style="height: 96%;padding: 20px;" v-if="showPage">
      <ht-table
        @load="loadData"
        :data="dataList"
        :pageResult="pageResult"
        :selection="true"
        :show-export="false"
        :show-custom-column="false"
        :quick-search-props="searchFieldList"
        ref="htTable"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <template v-slot:toolbar>
          <el-button
            size="small"
            @click="$router.push('/matrixManager')"
            icon="el-icon-d-arrow-left"
            >返回</el-button
          >

          <el-divider direction="vertical"></el-divider>

          <el-button
            size="small"
            @click="showDialog('')"
            icon="el-icon-plus"
            v-if="isIssure"
            type="primary"
            >添加</el-button
          >

          <!-- <el-button size="small" @click="save()" type="primary" icon="icon-f-right">保存</el-button> -->

          <ht-delete-button
            :url="'${uc}/uc/matrix/v1/data/remove/' + matrix.id"
            :htTable="$refs.htTable"
            pk="ID_"
            :disabled="isDisabled"
            >删除</ht-delete-button
          >
        </template>
        <template>
          <ht-table-column
            type="index"
            width="50"
            align="center"
            label="序号"
          />

          <ht-table-column
            v-for="(item, $index) in colFields"
            :key="$index"
            :prop="item.field"
            :label="item.comment"
            :hidden="item.ftype == 'id' || item.ftype == 'ck'"
            :show-overflow-tooltip="true"
          >
            <template slot="header">
              <span
                ><i
                  v-if="item.ftype == 'ro'"
                  class="icon-account"
                  style="margin-right:4px;"
                ></i
                >{{ item.comment }}</span
              >
            </template>
            <template v-slot="{row}">
              <span v-if="item.colDef && item.colDef.colType === 1">{{
                row[item.field]
              }}</span>

              <span v-if="item.colDef && item.colDef.colType === 2">{{
                parseUser(row[item.field])
              }}</span>
            </template>
          </ht-table-column>
          <ht-table-column label="操作" width="100">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="showDialog(row.ID_)">
                修 改</el-button
              >
            </template>
          </ht-table-column>
        </template>
      </ht-table>

      <el-dialog
        width="60%"
        top="8vh"
        :title="matrix.name"
        class="cd-column__dialog"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        append-to-body
      >
        <el-form :inline="true" v-form data-vv-scope="matrixDataForm">
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span style="font-size:16px;">条件字段</span>
            </div>
            <span v-for="(item, $index) in colFields" :key="$index">
              <ht-form-item :label="item.comment" v-if="item.ftype == 'cv'">
                <!-- <ht-select
                  v-if="item.colDef.ctrlType === 'select'"
                  clearable
                  :filterable="true"
                  :remote="true"
                  v-model="formData[item.field]"
                  :options="options[item.colDef.queryAlias]"
                  :props="{key: 'value', value: 'value'}"
                  class="ht-select"
                  @focus="handleFocus(item.colDef, $event)"
                  @change="handleChange"
                  @clear="clearCond(item.colDef)"
                  :remoteMethod="remoteMethod"
                /> -->

                <el-select
                  v-if="item.colDef.ctrlType === 'select'"
                  clearable
                  :filterable="true"
                  :remote="true"
                  v-model="formData['CONDK_' + item.code]"
                  class="ht-select"
                  @focus="handleFocus(item.colDef, $event, item)"
                  @change="handleChange"
                  @clear="clearCond(item.colDef)"
                  :remoteMethod="remoteMethod"
                >
                  <el-option
                    v-for="item in options[item.colDef.code]"
                    :key="item.value"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
                <ht-input
                  v-model="formData[item.field]"
                  readonly
                  v-if="item.colDef.ctrlType === 'dialog'"
                  placeholder="请选择数据"
                  class="ht-select"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-circle-close"
                    @click="clearCond(item.colDef)"
                  ></i>
                  <el-button
                    slot="append"
                    icon="icon-archives"
                    @click="showCustomDialog(item.colDef)"
                  ></el-button>
                </ht-input>
              </ht-form-item>
            </span>
          </el-card>
          <div style="margin-top:10px;"></div>
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span style="font-size:16px;">角色字段</span>
            </div>
            <span v-for="(item, $index) in colFields" :key="$index">
              <ht-form-item :label="item.comment" v-if="item.ftype == 'ro'">
                <user-selector
                  v-model="formData[item.field]"
                  :single="item.colDef.selectType === 1"
                  v-if="item.colDef.colType === 2"
                  append-to-body
                />
              </ht-form-item>
            </span>
          </el-card>
        </el-form>
        <div slot="footer">
          <el-button @click="beforeCloseDialog">{{
            $t('eip.common.cancel')
          }}</el-button>
          <el-button type="primary" @click="save">{{
            $t('eip.common.save')
          }}</el-button> 
        </div>
      </el-dialog>

      <custom-dialog-show
        :title="titlePreview"
        ref="customDialogShow"
        :custom-dialog="customDialogPreview"
        :alias="aliasPreview"
        @return-all-data="handleSavePreview"
      ></custom-dialog-show>
      <!-- 自定义对话框树形预览 参数动态传入的--->
      <custom-dialog-show-tree
        :title="titlePreview"
        ref="customDialogShowTree"
        :custom-dialog="customDialogPreview"
        :alias="aliasPreview"
      ></custom-dialog-show-tree>
      <!-- 自定义对话框树形预览  参数没有动态传入的-->
      <eip-tree-dialog
        ref="eipTreeDialog"
        @return-all-data="handleSavePreview"
        :custom-dialog="customDialogPreview"
        :alias="aliasPreview"
        :ispreview="false"
      ></eip-tree-dialog>
    </div>
  </div>
</template>
<script>
const userSelector = () => import('@/components/selector/UserSelector.vue')
const customDialogShow = () =>
  import('@/views/form/customDialog/CustomDialogShow.vue')
const customDialogShowTree = () =>
  import('@/views/form/customDialog/CustomDialogShowTree.vue')
const eipTreeDialog = () =>
  import('@/views/form/customDialog/EipTreeDialog.vue')
import req from '@/request.js'
import htUtil from '@/hotent-ui-util.js'
import CustomQuery from '@/views/form/customquery/CustomQuery.js'
import form from '@/api/form.js'
export default {
  components: {
    customDialogShow,
    userSelector,
    customDialogShowTree,
    eipTreeDialog
  },
  data() {
    return {
      dialogVisible: false,
      dataList: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      matrix: {},
      colFields: [],
      formData: {},
      //自定义对话框
      aliasPreview: '',
      customDialogPreview: {},
      titlePreview: '',
      //关联查询的返回数据集合
      options: {},
      isIssure: false,
      dataSources: 'mysql',
      searchFieldList: '',
      selectedList: [],
      isDisabled: true,
      showPage: false,
      alias: '',
      queryParams: [],

      optionListClone: {},
      selectData: new Map()
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  mounted() {
    this.getSQLType()
    this.$validator = this.$root.$validator
  },
  methods: {
    showDialog(id) {
      this.$http
        .get(
          '${uc}/uc/matrix/v1/data/getOneData?pk=' +
            `${id}` +
            '&matrixId=' +
            this.matrix.id
        )
        .then(
          resp => {
            this.selectData = new Map()
            this.formData = resp.data.data
            let matrix = resp.data.matrix || {}
            if (this.formData) {
              for (let key in this.formData) {
                if (key.indexOf('ROLE_') == 0 && this.formData[key]) {
                  this.formData[key] = this.isJSON(this.formData[key])
                    ? JSON.parse(this.formData[key])
                    : this.formData[key]
                }
              }

              if (matrix.condList && matrix.condList.length > 0) {
                matrix.condList.forEach(item => {
                  this.selectData.set(item.code, {
                    key: this.formData[`CONDK_${item.code}`],
                    value: this.formData[`CONDV_${item.code}`]
                  })

                  
                })
              }
            }

            this.dialogVisible = true
          },
          error => {}
        )
      this.getSelectOptions()
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          const obj = JSON.parse(str)
          if (typeof obj == 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          return false
        }
      }
    },
    beforeCloseDialog() {
      this.dialogVisible = false
    },
    loadData(param, cb) {
      let id = this.$route.params.matrixId
      let this_ = this
      this.$http
        .post('${uc}/uc/matrix/v1/data/list/' + id, param)
        .then(
          resp => {
            let response = resp.data
            this_.matrix = response.matrix
            this_.isIssure = true
            this_.colFields = response.colFields.filter(item => {
              if (item.ftype == 'id' || item.ftype == 'ck') {
                return false
              }
              return true
            })
            if (resp.data.matrix.roleList) {
              this.searchFieldList = []
              // [{prop:'name', label:'名称'},{prop:'CODE_',label:'别名'}]
              resp.data.matrix.roleList.map(item => {
                if (item.searchField == '0') {
                  let o = {prop: 'ROLE_' + item.code, label: item.name}
                  this.searchFieldList.push(o)
                }
              })
              resp.data.matrix.condList.map(item => {
                let o = {prop: 'CONDV_' + item.code, label: item.name}
                this.searchFieldList.push(o)
              })
            }
            /*if (this_.dataSources === "oracle" ){
                          for (let i = 0; i < this_.colFields.length; i++) {
                            const colFiled = this_.colFields[i];
                            colFiled.field = colFiled.field.toUpperCase();
                          }
                        }else if ( this_.dataSources === "postgresql"){
                          for (let i = 0; i < this_.colFields.length; i++) {
                            const colFiled = this_.colFields[i];
                            colFiled.field = colFiled.field.toLowerCase();
                          }
                        }*/
            this_.dataList = response.data.rows
            this_.pageResult = {
              page: response.data.page,
              pageSize: response.data.pageSize,
              total: response.data.total
            }
          },
          error => {}
        )
        .finally(() => {
          this.showPage = true
          cb && cb()
        })
    },
    save() {
      //条件字段至少填一个
      let hasCond = false
      for (var key in this.formData) {
        if (key.indexOf('CONDK_') === 0 && this.formData[key]) {
          hasCond = true
          break
        }
      }
      if (!hasCond) {
        this.$message.warning('条件字段至少填一个')
        return
      }
      this.$http
        .post(
          '${uc}/uc/matrix/v1/data/save/' + this.matrix.id,
          JSON.stringify(this.formData)
        )
        .then(
          resp => {
            if (resp.data.state) {
              this.$message.success(resp.data.message)
              this.beforeCloseDialog()
              this.loadData()
            } else {
              this.$message.error(resp.data.message)
            }
          },
          error => {}
        )
        .finally(() => {})
    },
    parseUser(val) {
      let fullnames = []
      if (val && val != 'null' && val.startsWith('[')) {
        let list = JSON.parse(val)
        list.forEach(item => {
          fullnames.push(item.fullname)
        })
      } else {
        return val
      }
      return fullnames.join(',')
    },
    showCustomDialog(colDef) {
      this.currColDef = colDef
      this.dialogPreview(colDef.queryAlias)
    },
    //预览
    dialogPreview(alias) {
      const this_ = this
      let url = '${form}/form/customDialog/v1/getByAlias?alias=' + alias
      req.get(url).then(function(customDialog) {
        customDialog = customDialog.data
        //格式化对话框的显示字段、返回字段、条件字段、排序字段
        if (!customDialog || JSON.stringify(customDialog) == '{}') {
          this_.$message.error('未找到别名为' + alias + '的对话框')
          return
        }
        customDialog.displayfield = JSON.parse(customDialog.displayfield)
        for (let i = 0; i < customDialog.displayfield.length; i++) {
          customDialog.displayfield[i].field = customDialog.displayfield[
            i
          ].field.toUpperCase()
        }
        customDialog.resultfield = JSON.parse(customDialog.resultfield)
        customDialog.sortfield = JSON.parse(customDialog.sortfield)
        customDialog.conditionfield = JSON.parse(customDialog.conditionfield)
        //这里强制给对话框改为单选
        customDialog.selectNum = 1
        //列表
        if (customDialog.style == 0) {
          this_.aliasPreview = alias
          this_.customDialogPreview = customDialog
          this_.titlePreview = customDialog.name + '-对话框列表预览'
          setTimeout(() => {
            this_.$refs.customDialogShow.showDialog() //显示自定义对话框列表预览弹框
          })
        } else {
          //树形
          this_.aliasPreview = alias
          this_.customDialogPreview = customDialog
          this_.titlePreview = customDialog.name + '-对话框树形预览'
          let param = {}
          if (customDialog.conditionfield.length > 0) {
            for (let i = customDialog.conditionfield.length - 1; i >= 0; i--) {
              //判断条件字段是否是动态传入（defaultType：4：动态传入，2：固定值 ）
              if (customDialog.conditionfield[i].defaultType == '4') {
                param[customDialog.conditionfield[i].field] =
                  customDialog.conditionfield[i].comment
              }
            }
          }
          //有动态传入的字段
          if (JSON.stringify(param) != '{}') {
            customDialog.param = param
            setTimeout(() => {
              this_.$refs.customDialogShowTree.showDialog() //显示自定义对话框列表预览弹框
            })
          } else {
            setTimeout(() => {
              this_.$refs.eipTreeDialog.showDialog()
            })
          }
        }
      })
    },
    handleSavePreview(list) {
      if (!list) {
        return
      }
      if (list.length > 1) {
        this.$message.warning('请只选择一项！')
        return
      }
      let data = list[0]
      let code = this.currColDef.code
      let bindKey = this.currColDef.bindKey
      let bindValue = this.currColDef.bindValue
      let v1 =
          data[bindKey] ||
          data[bindKey.toUpperCase()] ||
          data[bindKey.toLowerCase()],
        v2 =
          data[bindValue] ||
          data[bindValue.toUpperCase()] ||
          data[bindValue.toLowerCase()]
      this.$set(this.formData, 'CONDK_' + code, v1)
      this.$set(this.formData, 'CONDV_' + code, v2)
    },
    getSelectOptions() {
      for (let i = 0; i < this.matrix.condList.length; i++) {
        const ele = this.matrix.condList[i]
        if (ele.ctrlType === 'select') {
          //获取关联查询基本信息
          !this.options[ele.queryAlias] &&
            this.doCustomQuery(ele, ele.queryAlias)
        }
      }
    },
    doCustomQuery(colDef, alias) {
      

      CustomQuery.load(alias, null)
        .then(res => {
          
          const data = res.rows || res

          //判断是否有关联查询数据返回
          if (data && data.length > 0) {
            let bindKey = colDef.bindKey
            let bindValue = colDef.bindValue
            let option = []
            for (let i = 0; i < data.length; i++) {
              let item = data[i]
              option.push({key: item[bindKey], value: item[bindValue]})
            }

            this.$set(this.options, colDef.code, option)
            

            if (this.selectData ) {
              

              if (this.selectData.has(colDef.code)) {
                this.options[colDef.code].push(this.selectData.get(colDef.code))

                let map = new Map()
                for (let item of this.options[colDef.code]) {
                  map.set(item.key, item)
                }
                this.options[colDef.code] = [...map.values()]
              }

              // for (let index of this.options) {
              //   let mapData = new Map()
              //   for (let item of index) {
              //     mapData.set(item.key, item)
              //   }
              //   this.options[colDef.code] = [...mapData.values()]
              // }
              this.$nextTick(() => {
                this.options = Object.assign({}, this.options)
              })
              
            }
            this.optionListClone = _.cloneDeep(this.options)
          }
        })
        .finally()
    },
    handleFocus(data, event, item) {
      this.alias = data.code

      
      this.currColDef = data
      if (
        this.optionListClone[data.code] &&
        this.optionListClone[data.code].length > 0
      ) {
        this.options[data.code] = _.cloneDeep(this.optionListClone[data.code])

        this.$nextTick(() => {
          this.options = Object.assign({}, this.options)
        })
        
      }
    },
    remoteMethod(query) {
      // this.options = {}

      this.options[this.currColDef.code] = []
      form.getByAliasCq(this.currColDef.queryAlias, res => {
        
        let params =res&& res.conditionfield && JSON.parse(res.conditionfield)
        

        let dataList = {}
        params.forEach(item => {
          // this.queryParams.push({field: item.field, value: query})
          dataList[item.field] = query
        
        })
  
        CustomQuery.get(this.currColDef.queryAlias).then(async rest => {
          if (!rest) {
            reject(`未获取到别名为：${this.currColDef.code}的关联查询`)
          } else {
            for (let item in dataList) {
              let que = {}
              que[item] = dataList[item]

              let bindKey = this.currColDef.bindKey
              let bindValue = this.currColDef.bindValue
              await CustomQuery._doQuery(rest, que, '1', res => {
                for (let i = 0; i < res.length; i++) {
                  let item = res[i]
                  this.$nextTick(() => {
                    this.options[this.currColDef.code].unshift({
                      key: item[bindKey],
                      value: item[bindValue]
                    })

                    let map = new Map()
                    for (let item of this.options[this.currColDef.code]) {
                      map.set(item.key, item)
                    }
                    this.options[this.currColDef.code] = [...map.values()]
                    this.options = Object.assign({}, this.options)
                  })
                }
              })
            }
          }
        })
      })
    },

    handleChange(value, data) {
      // if (data) {
      //   let code = this.currColDef.code
      //   this.$set(this.formData, 'CONDK_' + code, data.key)
      // }
      let datas = null

      let items = this.options[this.alias].filter(item => {
        return item.key == value
      })
      datas = items[0]

      let code = this.currColDef.code
      this.$set(this.formData, 'CONDV_' + code, datas.value)
    },
    clearCond(colDef) {
      this.currColDef = colDef
      let code = this.currColDef.code
      this.$set(this.formData, 'CONDK_' + code, '')
      this.$set(this.formData, 'CONDV_' + code, '')
    },
    getSQLType() {
      // 获取数据库类型
      let this_ = this
      form.getDataSource().then(resp => {
        this_.dataSources = resp.data[resp.data.length - 1].dbType
        this_.loadData()
      })
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    }
  }
}
</script>
<style lang="scss" scoped>
.ht-select >>> .el-select.el-select--small {
  width: 350px;
}

.el-form-item__content .ht-select {
  width: 350px;
}

.el-icon-circle-close {
  cursor: pointer;
}

.el-icon-circle-close:hover {
  transform: scale(1.5);
  -moz-transform: scale(1.5);
  -webkit-transform: scale(1.5);
  -o-transform: scale(1.5);
}

.ht-table-panel >>> .toolbar-panel {
  margin-top: 10px;
  margin-bottom: 10px;
}

::v-deep .el-table__header {
  width: 100% !important;
  table-layout: fixed;
}

::v-deep .el-table__body {
  width: 100% !important;
}

::v-deep .el-table__empty-block {
  width: 100% !important;
}

::v-deep {
  .el-select {
    .el-select__caret:first-child::before {
      content: '\e6e1';
    }
    .is-focus {
      .el-select__caret:first-child {
        transform: rotateZ(0deg);
      }
    }
  }
}
</style>
