<template>
  <!--  <div class="popupSelect-container">-->
  <!--    <div class="popupSelect-input" @click="openDialog">-->
  <!--      <el-input :placeholder="placeholder" v-model="innerValue" readonly>-->
  <!--        <i slot="suffix" class="el-input__icon el-icon-circle-close" @click.stop="clear"></i>-->
  <!--        <i slot="suffix" class="el-input__icon el-icon-edit"></i>-->
  <!--      </el-input>-->
  <!--    </div>-->
  <vxe-modal :title="title" :close-on-click-modal="false" v-model="visible" v-if="visible" lock-scroll transfer :width="relationWidth" height="70%" width="60%">
    <!--      <el-row class="JNPF-common-search-box" :gutter="16">-->
    <!--        <el-form @submit.native.prevent>-->
    <!--          <el-col :span="10">-->
    <!--            <el-form-item label="关键词">-->
    <!--              <el-input v-model="keyword" placeholder="请输入关键词查询" clearable />-->
    <!--            </el-form-item>-->
    <!--          </el-col>-->
    <!--          <el-col :span="8">-->
    <!--            <el-form-item>-->
    <!--              <el-button type="primary" icon="el-icon-search" @click="search()">-->
    <!--                {{$t('common.search')}}-->
    <!--              </el-button>-->
    <!--              <el-button icon="el-icon-refresh-right" @click="reset()">{{$t('common.reset')}}-->
    <!--              </el-button>-->
    <!--            </el-form-item>-->
    <!--          </el-col>-->
    <!--        </el-form>-->
    <!--&lt;!&ndash;        <div class="JNPF-common-search-box-right">&ndash;&gt;-->
    <!--&lt;!&ndash;          <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">&ndash;&gt;-->
    <!--&lt;!&ndash;            <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false"&ndash;&gt;-->
    <!--&lt;!&ndash;              @click="refresh()" />&ndash;&gt;-->
    <!--&lt;!&ndash;          </el-tooltip>&ndash;&gt;-->
    <!--&lt;!&ndash;        </div>&ndash;&gt;-->
    <!--      </el-row>-->
    <search ref="Search" :list="searchList" @reset="reset" @search="search" />
    <JNPF-table v-loading="listLoading" :data="filteredList" :border="true" highlight-current-row :hasNO="false" @selection-change="handleSelectionChange" height="calc(100% - 161px)">
      <!--        @row-click="rowClick"-->
      <el-table-column v-if="relationConfObj.isCheck" width="35">
        <template slot-scope="scope">
          <el-radio v-model="checked" @change.native="clickChange(scope.row)">{{ '' }}</el-radio>
        </template>
      </el-table-column>
      <el-table-column v-else type="selection" width="55"></el-table-column>

      <!--        <el-table-column type="index" width="50" label="序号" align="center" />-->
      <el-table-column :prop="String(item.value)" :label="item.label" v-for="(item, i) in columnOptions" :key="i">
        <template slot-scope="scope">
          {{ scope.row[columnDict[item.value]] }}
        </template>
      </el-table-column>
    </JNPF-table>
    <div style="display: flex; align-items: center; justify-content: space-between">
      <pagination :total="total" :small="relationWidth === '95%'" :layout="relationlayout" :page.sync="current" :limit.sync="size" @pagination="initData" />
      <div v-if="!relationConfObj.isCheck" style="margin-top: 9px; float: left">
        <el-button type="primary" size="mini" @click="checkChangeClick">提交</el-button>
      </div>
    </div>
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="visible = false" size="small">{{$t('common.cancelButton')}}</el-button>-->
    <!--        <el-button type="primary" @click="select()" size="small">{{$t('common.confirmButton')}}-->
    <!--        </el-button>-->
    <!--      </span>-->
  </vxe-modal>
  <!--  </div>-->
</template>

<script>
import { getFieldDataSelect, getDataChange, getBrowserData, getConfigData } from '@/api/onlineDev/visualDev'
import search from '@/components/Generator/components/RelationForm/search'
import { deepClone } from '@/utils'
export default {
  name: 'PopupSelect',
  components: { search },
  props: {
    relationConf: {
      type: Array
    },
    value: {
      default: ''
    },
    modelId: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    relationField: {
      type: String,
      default: ''
    },
    field: {
      type: String,
      default: ''
    },
    // columnOptions: {
    //   type: Array,
    //   default: () => []
    // },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'value',
    event: 'input'
  },
  data() {
    return {
      title: '请选择',
      list: [],
      filteredList: [],
      innerValue: '',
      keyword: '',
      checked: '',
      checkedTxt: '',
      listLoading: false,
      visible: false,
      relationData: [],
      columnOptions: [],
      columnDict: [],
      fieldList: [],
      relationfieldName: null,
      total: 0,
      current: 1,
      size: 50,
      searchjson: [],
      keyId: null,
      relationWidth: '60%',
      relationlayout: 'total, sizes, prev, pager, next',
      relationConfObj: {},
      searchList: [],
      idKey: '',
      checkChangeRow: [],
      checkChangeValue: []
    }
  },
  watch: {
    value(val) {
      this.setDefault()
    }
  },
  created() {
    // this.getData()
  },
  methods: {
    getData(config, fieldName, fieldList, keyId) {
      this.relationConfObj = config
      if (window.innerWidth < 767) {
        this.relationWidth = '95%'
        this.relationlayout = 'total,prev, pager,next'
      }
      this.visible = true
      this.relationfieldName = config.itemRelationTable //表名
      this.columnOptions = deepClone(config.showTitle) // 表头
      if (keyId) this.keyId = keyId
      if (!config) return
      this.initData()
      this.getRelationConfig()
    },
    getRelationConfig() {
      getConfigData(this.relationfieldName).then((res) => {
        let data = res.data.data
        this.idKey = data.idKey
        this.title = data.fullName + '-选择数据'
        let columnData = JSON.parse(data.columnData)
        this.searchList = columnData.searchList
        let fieldKeys = this.relationConfObj.showTitle.map((i) => {
          return i.value
        })
        this.searchList = this.searchList.filter((p) => {
          return fieldKeys.includes(p.__vModel__)
        })
      })
    },
    initData() {
      this.listLoading = true
      let parmes = {
        pageQuery: {
          currentPage: this.current,
          pageSize: this.size
        },
        primaryTableId: this.relationConfObj.RelationTableCubeId,
        foreignTableId: [],
        modelId: this.relationConfObj.itemRelationTable,
        browserRequest: this.searchjson ? JSON.stringify(this.searchjson) : JSON.stringify([])
        //   this.searchjson ? JSON.stringify(this.searchjson) :
      }
      getBrowserData(this.relationConfObj.RelationTableCubeId, parmes)
        .then((res) => {
          this.columnDict = res.data.data.columnDict
          this.list = res.data.data.pageData.records
          this.total = res.data.data.pageData.total
          this.size = res.data.data.pageData.size
          this.current = res.data.data.pageData.current
          this.filteredList = this.list
          this.listLoading = false
          // this.setDefault()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    //整合数据 配合流程进行存储回显数据
    getFlowJsonData(row) {
      let rows = Object.assign({}, row)
      let jsonData = deepClone(this.columnDict)
      // delete jsonData[this.idKey]
      for (let key in jsonData) {
        for (let index in rows) {
          if (jsonData[key] === index) {
            jsonData[key] = rows[index]
          }
        }
      }
      return jsonData
    },
    search(json) {
      this.searchjson = json && json.length ? JSON.parse(json) : []
      this.current = 1
      this.size = 50
      this.initData()
      //   if (!this.keyword) {
      //     this.filteredList = this.list
      //     return
      //   }
      //   this.filteredList = this.list.filter(o => this.columnOptions.some(option =>
      //     option.value && o[this.columnDict[option.value]] && o[this.columnDict[option.value]].indexOf(this.keyword) > -1))
    },
    reset() {
      this.keyword = ''
      this.filteredList = this.list
    },
    refresh() {
      this.keyword = ''
      this.getData()
    },
    openDialog() {
      if (this.disabled) return
      this.keyword = ''
      this.checked = this.value
      this.visible = true
      if (!this.list.length) {
        this.getData()
      } else {
        this.filteredList = this.list
      }
    },
    clear() {
      this.checked = ''
      this.innerValue = ''
      this.$emit('input', this.checked)
    },
    select() {
      if (!this.checked) return
      this.innerValue = this.checkedTxt
      this.$emit('input', this.checked)
      this.visible = false
    },
    rowClick(row) {
      this.checked = row
      let jsonData = this.getFlowJsonData(row)
      if (!this.relationfieldName) return
      let data = {
        id: this.relationfieldName,
        keyId: this.keyId,
        jsonData
      }
      this.$nextTick(() => {
        this.$emit('changeRow', data)
      })
    },
    clickChange(row) {
      this.checked = row
      let jsonData = this.getFlowJsonData(row)
      // if (!this.relationfieldName) return
      let data = {
        // id:this.relationfieldName,
        // keyId:this.keyId,
        jsonData,
        id: row[this.columnDict[this.idKey]],
        relationConfObj: this.relationConfObj
      }
      this.$emit('changeRow', data)
    },
    handleSelectionChange(row) {
      this.checkChangeRow = row.map((o) => {
        return this.getFlowJsonData(o)
      })
      this.checkChangeValue = row.map((o) => {
        return o[this.columnDict[this.idKey]]
      })
      console.log(this.checkChangeRow)
    },
    checkChangeClick() {
      let valueSeparator = ''
      if (this.relationConfObj.associationSeparator) {
        valueSeparator = this.checkChangeValue.join(this.relationConfObj.associationSeparator)
      } else {
        valueSeparator = this.checkChangeValue.join(';')
      }
      let data = {
        id: valueSeparator,
        relationConfObj: this.relationConfObj,
        jsonData: this.checkChangeRow
      }
      this.$emit('changeRow', data)
      this.checkChangeValue = []
      this.checkChangeRow = []
    },
    setDefault() {
      if (!this.value) return (this.innerValue = '')
      this.getItemValue(this.value)
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].id === this.value) {
          this.innerValue = this.list[i][this.relationField]
          break
        }
      }
    },
    getItemValue(val) {
      if (!this.field || !this.modelId) return
      let relationData = this.$store.state.generator.relationData
      if (val) {
        getDataChange(this.modelId, val).then((res) => {
          if (!res.data || !res.data.data) return
          let data = JSON.parse(res.data.data)
          this.$set(relationData, this.field, data)
          this.$store.commit('generator/UPDATE_RELATION_DATA', relationData)
        })
      } else {
        this.$set(relationData, this.field, {})
        this.$store.commit('generator/UPDATE_RELATION_DATA', relationData)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.popupSelect-container {
  width: 100%;
  .popupSelect-input {
    width: 100%;
    cursor: pointer;
    >>> input {
      cursor: pointer;
    }
    .el-icon-circle-close {
      display: none;
    }
    &:hover {
      .el-icon-circle-close {
        display: block;
      }
      .el-icon-edit {
        display: none;
      }
    }
  }
}
>>> .el-dialog__body {
  height: 70vh;
  padding: 0 0 10px !important;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .JNPF-common-search-box {
    margin-bottom: 0;
    .JNPF-common-search-box-right {
      padding: 10px 10px 0 0;
    }
  }
}
</style>
