<template>
  <div id="tableWrap">

    <div v-if="isComparison">
      <a-button class="closeBtn" :disabled="!hasSelected" type="work" @click="onNext">
        版本对比
      </a-button>
      <a-table
        :data-source="tableData"
        :columns="versionsDate"
        :bordered="true"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{x: xscroll}"
        :pagination="{
          'show-less-items':true,
          'show-quick-jumper':true,
          'hideOnSinglePage':true
        }"
      >
        <span slot="processStatus" slot-scope="text,record">
          {{ statusFormat(record) }}
        </span>
        <span slot="operationType" slot-scope="text,record">
          {{ operationFormat(record) }}
        </span>
      </a-table>
      <div class="footer-btn">
        <a-button class="closeBtn" type="work" @click="onClose">
          取消
        </a-button>
        <a-button class="submitBtn" type="add" @click="onClose">
          确定
        </a-button>
      </div>
    </div>
    <div v-if="!isComparison">
      <div>隐藏相同项 <span><a-switch :default-checked="false" @change="onChangeSwitch" /></span> </div>
      <a-table
        :data-source="comparisonDate"
        :columns="comparisonColumns"
        :bordered="true"
        position="both"
      >
      </a-table>
      <div class="footer-btn">
        <a-button class="closeBtn" type="work" @click="onClose">
          取消
        </a-button>
        <a-button class="submitBtn" type="add" @click="onClose">
          确定
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getVersionContrast } from '@/api/masterDataManger/searchMasterData'
// import { colorList } from '@/components/SettingDrawer/settingConfig'
export default {
  data() {
    return {
      showdate: '',
      showVersions: true,
      selectedRowKeys: [],
      comparisonColumns: [
        {
          title: '属性名称/版本',
          dataIndex: 'nameVersions',
          key: 'nameVersions'
        }
      ],
      initialData: [
        {
          nameVersions: '创建人',
          type: 'createBy'
        },
        {
          nameVersions: '创建时间',
           type: 'createTime'
        },
        {
          nameVersions: '最后更新人',
           type: 'updateBy'
        },
        {
          nameVersions: '最后更新时间',
           type: 'updateTime'
        },
        {
          nameVersions: '操作类型',
           type: 'operationType'
        },
        {
          nameVersions: '审批意见',
          type: 'approveDesc'
        }
      ],
      comparisonDate: [],
      // 过滤key集合
      versionKeyFilter: ['createTime', 'createBy', 'updateTime', 'updateBy', 'operationType', 'approveDesc'],
      // 过滤value集合
      versionValueFilter: ['创建时间', '创建人', '最后更新时间', '最后更新人', '操作类型', '审批意见'],
      // 版本下标
      versionDataIndex: [],
      // 对比相同项data
      filterData: [],
      IdAB: [],
      xscroll: 1000
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length === 2
    }
  },
  props: {
    tableData: {
      type: Array,
      required: true
    },
    versionsDate: {
      type: Array,
      required: true
    },
    isComparison: {
      type: Boolean,
      default() {
        return true
      }
    },
    modelId: {
      type: String,
      default() {
        return ''
      }
    },
    changeColumns: {
      type: Array,
      default() {
        return []
      }
    },
    typeList: {
      type: Array,
      default() {
        return []
      }
    },
    statusFormat: {
        type: Function,
        default: null
    },
    operationFormat: {
        type: Function,
        default: null
    }
  },
   watch: {
      versionsDate: {
        deep: true,
        immediate: true,
        handler(val) {
          const length = this.versionsDate.length
          if (length > 9) {
            this.xscroll = this.versionsDate.length * 200 - 200
          }
        }
      }
  },
  created() {
    this.$emit('changeShow', true)
  },
  methods: {
    // 隐藏相同项
    hideData(data) {
      data.forEach(item => {
        if (item[this.versionDataIndex[0]] !== item[this.versionDataIndex[1]]) {
          this.filterData.push(item)
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
      const arr = []
      selectedRows.forEach(item => {
          arr.push(item.id)
          this.IdAB = arr
      })
    },
    onNext() {
      const data = {
        modelId: this.modelId,
        idA: this.IdAB[0],
        idB: this.IdAB[1]
      }
    getVersionContrast(data).then(res => {
          this.dataAction(res.rows)
          // this.dataAction2()
          console.log(`versionDataIndex`, this.comparisonColumns)
          const arr = []
          const data = res.rows
          // nameVersion type Version1初版本数据
          const element = data[0]
          const keysarr = Object.keys(element)
          const valuearr = Object.values(element)
            for (let j = 0; j < keysarr.length; j++) {
              const bj = {}
              const eles = keysarr[j]
              const values = valuearr[j]
              if (this.versionKeyFilter.indexOf(eles) !== -1) {
                const keyindex = this.versionKeyFilter.findIndex(item => item === eles)
                bj.nameVersions = this.versionValueFilter[keyindex]
                const versionindex = this.versionDataIndex[1]
                bj[versionindex] = values
                bj['type'] = eles
                bj.key = j
                arr.push(bj)
              }
              if (eles === 'logJson') {
                  const logjson = JSON.parse(values)
                  this.typeList.forEach(item => {
                       const attrcode = {}
                       attrcode.nameVersions = item.attrName
                       attrcode.type = item.attrCode
                       if (Object.keys(logjson).indexOf(item.attrCode) !== -1) {
                        attrcode[this.versionDataIndex[1]] = logjson[item.attrCode]
                       }
                       arr.push(attrcode)
                  })
                  // for (let k = 0; k < logjson.length; k++) {
                  //   const elk = logjson[k]
                  //   const attrcode = {}
                  //   // attrcode.key=j
                  //   attrcode.nameVersions = elk.attr_name
                  //   attrcode.type = elk.attr_code
                  //   attrcode[this.versionDataIndex[1]] = elk.value
                  //   arr.push(attrcode)
                  // }
                }
              // console.log('arr1 :>> ', arr);
          }

          // Versions2 获取创建人等信息
            const element2 = data[1]
            // const keysarr2 = Object.keys(element2)
            // const valuearr2 = Object.values(element2)

            for (let index = 0; index < arr.length; index++) {
              const element = arr[index]
              const version2key = element.type
              const versionindex = this.versionDataIndex[0]
              element[versionindex] = element2[version2key]
            }

            // Versions2 获取具体数据json
            for (let h = 0; h < arr.length; h++) {
              const hele = arr[h]
              const hlogJson = JSON.parse(element2.logJson)
              const versionindex2 = this.versionDataIndex[0]
              Object.keys(hlogJson).forEach(key => {
                if (hele.type === key) {
                  hele[versionindex2] = hlogJson[hele.type]
                }
              })

                  //   for (let m = 0; m < hlogJson.length; m++) {
                  //   const mel = hlogJson[m]
                  //   if (hele.type === mel.attr_code) {
                  //     const versionindex2 = this.versionDataIndex[0]
                  //     hele[versionindex2] = mel.value
                  //   }
                  // }
            }

          // console.log('object arr final :>> ', arr);
          this.comparisonDate = arr
          this.initialData = arr
          this.hideData(arr)
    })
      this.$emit('changeShow', false)
    },
    // 数据处理1  nameVersions
    dataAction(data) {
      const arr1 = []
      data.forEach(item => {
        arr1.push(item.operationVersion)
      })
      arr1.reverse()
      arr1.forEach((item, index) => {
        const obj = {}
        obj.title = '版本' + item
        obj.dataIndex = 'Versions' + item
        this.versionDataIndex.push(obj.dataIndex)
        obj.key = index
        obj.ids = item
        this.comparisonColumns.push(obj)
      })
    },
    // 数据处理2
    dataAction2(data) {
      this.changeColumns.forEach(item => {
        const obj = {}
        obj.nameVersions = item.title
        obj.type = item.dataIndex
        this.initialData.splice(-6, 0, obj)
      })
      this.initialData.forEach((item, index) => {
          item.key = index
      })
      // this.comparisonDate = this.initialData
      // data.forEach(item => {
      // })
    },
    onClose() {
      this.showVersions = false
      this.$emit('getShowVersions', this.showVersions)
    },
    onSub() {
     this.$emit('getShowVersions', true)
    },
    onChangeSwitch(checked) {
      if (checked) {
        this.comparisonDate = this.filterData
      } else {
        this.comparisonDate = this.initialData
      }
    }
  }

}
</script>

<style  lang="less" scoped>

#tableWrap{
  box-sizing: border-box;
  padding: 25px 30px;
  .footer-btn{
    text-align: center;
    margin-top: 20px;
    .ant-btn{
      margin: 0 20px;
    }
  }

}

</style>
