<!-- 导出字段翻译json配置 -->
<template>
  <div>
    <el-dialog
      title="配置格式化JSON"
      width="600px"
      top="5vh"
      :visible.sync="dialogShow"
      @close="closeDialog"
    >
      <div class="button-group">
        <!--自定义添加  -->
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
          >自定义添加</el-button
        >
        <!--选择关联查询  -->
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleOpenRelative"
          >选择关联查询</el-button
        >
        <!--查询字典查询  -->
        <el-button
          type="primary"
          icon="el-icon-notebook-2"
          @click="handleOpenDict"
          >选择枚举字典</el-button
        >
      </div>
      <el-table
        border
        stripe
        class="json-table"
        row-key="key"
        :data="data"
        :height="tableHeight"
        highlight-current-row
      >
        <el-table-column
          label="字段实际值"
          align="center"
          prop="value"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.valueTips || scope.row.value"
              placement="top"
              v-if="scope.row.valueTips || scope.row.value.length > 12"
            >
              <el-input
                :class="{
                  'check-failed': scope.row.valueFailed
                }"
                v-model="scope.row.value"
                placeholder="请输入内容"
                :maxlength="50"
              ></el-input>
            </el-tooltip>
            <el-input
              v-else
              v-model="scope.row.value"
              placeholder="请输入内容"
              :maxlength="50"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="字段显示值"
          align="center"
          prop="label"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.labelTips || scope.row.label"
              placement="top"
              v-if="scope.row.labelTips || scope.row.label.length > 12"
            >
              <el-input
                :class="{
                  'check-failed': scope.row.labelFailed
                }"
                v-model="scope.row.label"
                placeholder="请输入内容"
                :maxlength="50"
              ></el-input>
            </el-tooltip>
            <el-input
              v-else
              v-model="scope.row.label"
              placeholder="请输入内容"
              :maxlength="50"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-plus"
              circle
              @click="handleAdd"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDel(scope.row.key)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleOk"> 确 定 </el-button>
      </span>
    </el-dialog>
    <SelectDict ref="selectDict" @change="changeDict"></SelectDict>
    <selectRelative
      ref="selectRelative"
      @change="changeRelative"
    ></selectRelative>
  </div>
</template>

<script>
import utils from '@/hotent-ui-util'
import SelectDict from '@/components/ImportExportData/SelectDict'
import SelectRelative from '@/components/ImportExportData/SelectRelative'
import CustomQuery from '@/components/ImportExportData/CustomQuery.js'
export default {
  name: 'FormatJson',
  components: {SelectDict, SelectRelative},
  data() {
    return {
      dialogShow: false,
      tableHeight: 300,
      currentScope: {},
      data: [
        {
          key: 0,
          value: '',
          label: ''
        }
      ]
    }
  },
  mounted() {
    this.calcTableHeight()
    this.$root.$on('resize', () => {
      this.calcTableHeight(500)
    })
  },
  methods: {
    getDictData(dictCode) {
      if (sessionStorage.getItem('dict_data')) {
        let dict_data = JSON.parse(sessionStorage.getItem('dict_data'))
        if (dict_data[dictCode]) {
          let dictItem = dict_data[dictCode]
          // 格式key 是值  value 是显示值
          dictItem.forEach((item, index) => {
            item.key = dictCode + index
            item.value = item.value
            item.label = item.name
          })
          return dictItem
        }
      }
    },
    changeDict(dictCode) {
      let newDictItems = this.getDictData(dictCode)
      if (this.data.length == 1) {
        if (!this.data[0].value && !this.data[0].label) {
          this.data = newDictItems
        }
      } else {
        this.data = this.data.concat(newDictItems)
      }
    },
    handleOpenDict() {
      this.$refs.selectDict.openDialog()
    },
    changeRelative(row, fields) {
      CustomQuery.load(row.alias).then(relativeData => {
        console.log(relativeData, 'relativeData')
        this.formatRelativeData(relativeData, fields)
      })
    },
    //加载关联查询数据
    formatRelativeData(relativeData, fields) {
      let tempData = []
      relativeData.forEach(item => {
        tempData.push({
          key: item.id,
          value: item[fields.value],
          label: item[fields.label]
        })
      })
      if (this.data.length == 1) {
        if (!this.data[0].value && !this.data[0].label) {
          this.data = tempData
        }
      } else {
        this.data = this.data.concat(tempData)
      }
    },
    handleOpenRelative() {
      this.$refs.selectRelative.openDialog()
    },
    handleAdd() {
      this.data.push({
        key: this.data.length + 1,
        value: '',
        label: ''
      })
    },
    handleDel(key) {
      let dataTemp = utils.deepClone(this.data)
      const filterData = dataTemp.filter(item => item.key !== key)
      this.data = filterData
    },
    openDialog(scope) {
      this.dialogShow = true
      this.currentScope = scope
      this.currentScope.row.fieldDataJson
        ? (this.data = JSON.parse(this.currentScope.row.fieldDataJson))
        : null
    },
    formatJson() {
      let result
      let objValue = {}
      let objLabel = {}
      this.data.forEach((item, index) => {
        if (!item.value) {
          item.valueFailed = true
          item.valueTips = '请完善数据'
          this.$nextTick(() => {
            this.$message.warning(`请完善数据!`)
          })
        } else if (objValue[item.value]) {
          item.valueFailed = true
          item.valueTips = '字段实际值重复'
          this.$nextTick(() => {
            this.$message.warning(`字段实际值重复!`)
          })
        } else if (item.value && !objValue[item.value]) {
          objValue[item.value] = true
          item.valueFailed = false
          item.valueTips = ''
        }

        if (!item.label) {
          item.labelFailed = true
          item.labelTips = '请完善数据'
          this.$nextTick(() => {
            this.$message.warning(`请完善数据!`)
          })
        } else if (objLabel[item.label]) {
          item.labelFailed = true
          item.labelTips = '字段显示值重复'
          this.$nextTick(() => {
            this.$message.warning(`字段显示值重复!`)
          })
        } else if (item.label && !objLabel[item.label]) {
          objValue[item.label] = true
          item.labelFailed = false
          item.labelTips = ''
        }

        if (!item.labelFailed && !item.valueFailed) {
          item.pass = true
        } else {
          item.pass = false
          item.key = new Date().getTime() + index
        }
      })
      let isResultFalse = this.data.some(item => {
        if (!item.pass) {
          return true
        }
      })
      console.log(this.data, 'this.data')
      if (!isResultFalse) {
        result = []
        this.data.forEach(item => {
          let tempObj = {
            value: item.value,
            label: item.label
          }
          result.push(tempObj)
        })
      } else {
        this.$forceUpdate()
        result = false
      }
      return result
    },
    handleOk() {
      if (this.data.length) {
        let json = this.formatJson()
        if (!json) {
          return
        } else {
          this.$emit('getJson', JSON.stringify(json), this.currentScope)
        }
      } else {
        this.$emit('getJson', '', this.currentScope)
      }
      this.closeDialog()
    },
    closeDialog() {
      this.data = [
        {
          key: 0,
          value: '',
          label: ''
        }
      ]
      this.dialogShow = false
    },
    // 动态计算表格的高度，自适应当前容器
    calcTableHeight(delay) {
      setTimeout(() => {
        this.tableHeight = document.documentElement.clientHeight * 0.9 - 200
      }, delay || 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.button-group {
  margin-bottom: 20px;
}
.json-table {
  ::v-deep .el-input--small .el-input__inner {
    border-radius: 4px;
  }

  ::v-deep .el-input--small.check-failed .el-input__inner {
    border-color: red;
  }
}
</style>
