<template>
  <div>
    <dee-dialog
      width="70%"
      :title="dialogTitle"
      :dialog-visible="dialogShow"
      @handleClose="cancel"
    >
      <dee-table class="dee-table" :selection-row="selectionRow" :columns="changeAffectedColumns" :data="changeAffectedData" @clickRowFun="changeNumber" @selection-change="getSelectionList" @cell-data-change="cellDataChange">
        <div slot="header">
          {{ '所选对象:' + rowData.target.oriNumber+' '+rowData.target.oriName+' '+ rowData.target.oriVersion+ ' ' }}
          <el-select v-model="value" placeholder="请选择" @change="selectType">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </dee-table>
      <div class="flexCenter" style="margin-top: 10px">
        <el-button type="primary" size="small" @click="submit">提交</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </div>
    </dee-dialog>
  </div>
</template>

<script>

import { getLinkByNumber, addLinks, showMessage, getImRecordLinks } from '@/utils/util'
import {
  getNextVersionKey,
  getDxPartDescribeLink
} from '@/api/configuration'
import setNumber from './setNumber'
import { event } from '../utils'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},

  props: {
    rowData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogShow: {
      type: Boolean,
      default: () => false
    },
    dialogTitle: {
      type: String,
      default: () => false
    }
  },

  data() {
    const vm = this
    // 这里存放数据
    return {
      selectionRow: {
        selectable: (row, index) => {
          if (row.isabled) {
            return false
          } else {
            return true
          }
        }
      },
      treeData: [],
      modeType: '',
      changeAffectedColumns: [
        {
          title: '改前编号',
          key: 'oriNumber'
        },
        {
          title: '改前名称',
          key: 'oriName'
        },
        {
          title: '改前版本',
          key: 'oriVersion'
        },
        {
          title: '更改方式',
          key: 'changeModeCode',
          component: {
            render(h, row) {
              return h('el-select', {
                attrs: {
                  size: 'small',
                  disabled: row.isabled ? row.isabled : false
                },
                props: {
                  value: row.changeModeCode
                },
                on: {
                  input: function(event) {
                    row.changeModeCode = event
                  },
                  change: function(val) {
                    if (val === '升版') {
                      const dxType = vm.modeType === 'DxPartDescribeLink' ? 'DxDocument' : 'DxPart'
                      getNextVersionKey.bind(vm)(dxType, row.oriNumber).then(res => {
                        vm.$set(row, 'objVersion', res)
                        vm.$set(row, 'objNumber', row.oriNumber)
                        vm.$set(row, 'objName', row.oriName)
                      })
                    } else {
                      this.$set(row, 'objVersion', '')
                    }
                  }
                }
              },
              row.versionOptions.map(function(item) {
                return h('el-option', {
                  attrs: {
                    label: item.label,
                    value: item.value,
                    key: item.value
                  }
                }, [])
              })
              )
            }
          }
        },
        {
          title: '改后编号',
          key: 'objNumber',
          component: {
            name: setNumber,
            props: {
              bindField: 'objNumber',
              size: 'small'
            }
          }
        },
        {
          title: '改后名称',
          key: 'objName',
          component: {
            name: setNumber,
            props: {
              bindField: 'objName',
              size: 'small'
            }
          }
        },
        {
          title: '改后版本',
          key: 'objVersion'
        },
        {
          title: '更改备注',
          key: 'comments',
          component: {
            render(h, row) {
              return h('el-input', {
                attrs: {
                  size: 'small',
                  disabled: row.isabled ? row.isabled : false
                },
                props: {
                  value: row.comments
                },
                on: {
                  input: function(event) {
                    row.comments = event
                  }
                }
              }, [])
            }
          }
        }
      ],
      changeAffectedData: [],
      value: '',
      options: [
        {
          label: '收集相关CAD文档',
          value: 'DxCADDocument'
        },
        {
          label: '收集相关文档',
          value: 'DxPartDescribeLink'
        },
        {
          label: '收集上级部件(一级)',
          value: 'DxPartFloor'
        },
        {
          label: '收集下级部件(一级)',
          value: 'DxPartCeiling'
        }
      ],
      selectionList: [],
      links: {
        'DxPartFloor': 'targetUsageLinks',
        'DxPartCeiling': 'sourceUsageLinks',
        'DxDocument': 'partDescribeLinks',
        'DxCADDocument': 'buildRules'
      },
      setChangeAffectedData: []
    }
  },
  computed: {
    imId() {
      return this.$store.getters.getImId
    }
  },
  // 监控data中的数据变化
  watch: {
  },
  // 生命周期 - 创建完成(可以访问当前this实例)
  created() {
    event.$on('tree-data', (val) => {
      getImRecordLinks('DxChangeIM', 'imRecordLinks', val).then(res => {
        this.treeData = res
      })
    })
  },
  // 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
  },
  activated() {
  },
  // 方法集合
  methods: {
    selectType(modeType) {
      this.modeType = modeType
      if (modeType === 'DxPartDescribeLink') {
        getDxPartDescribeLink(this.rowData.target.oriNumber).then(res => {
          this.changeAffectedData = res.items.map(item => {
            return {
              oriNumber: item.target.number,
              oriName: item.target.name,
              oriVersion: item.target.versionKey,
              objNumber: '',
              objName: '',
              objVersion: '',
              changeModeCode: '',
              comments: '',
              show: true,
              recordType: 3,
              isOriginal: '3',
              id: item.target.id,
              subTypeName: item.targetIdType,
              versionOptions: item.targetIdType === 'DxDocument' ? [{
                label: '升版',
                value: '升版'
              }] : [{
                label: '升版',
                value: '升版'
              },
              {
                label: '换号',
                value: '换号'
              }]
            }
          })
          this.treeData.forEach(t => {
            this.changeAffectedData.forEach(c => {
              if (c.oriNumber === t.target.oriNumber) {
                this.$set(c, 'isabled', true)
              } else {
                this.$set(c, 'isabled', false)
              }
            })
          })
        })
      } else {
        this.changeAffectedData = []
        this.setChangeAffectedData = []
        let changeAffectedData = []
        const attrFiled = modeType === 'DxPartFloor' ? 'source' : 'target'
        const service = this.$getService(modeType.indexOf('DxPart') >= 0 ? 'DxPart' : modeType)
        service.byNumber(this.rowData.target.oriNumber).then(res => {
          getLinkByNumber(modeType.indexOf('DxPart') >= 0 ? 'DxPart' : modeType, 'id', res.id, this.links[modeType]).then(res => {
            if (!res) return
            changeAffectedData = this.$utils.groupBy(res, function(item) { return [item.target.masterId] })
            changeAffectedData = changeAffectedData.map(item => {
              item.sort(function(a, b) {
                const version1 = a[attrFiled].masterId + a[attrFiled].displayVersion
                const version2 = b[attrFiled].masterId + b[attrFiled].displayVersion
                return version1 < version2 ? 1 : -1
              })
              return item
            })
            this.changeAffectedData = changeAffectedData.map(item => {
              return {
                oriNumber: item[0][attrFiled].number,
                oriName: item[0][attrFiled].name,
                oriVersion: item[0][attrFiled].versionKey,
                objNumber: '',
                objName: '',
                objVersion: '',
                changeModeCode: '',
                comments: '',
                show: true,
                isOriginal: false,
                isabled: modeType === 'DxCADDocument',
                id: item[0][attrFiled].id,
                subTypeName: item[0].sourceIdType,
                versionOptions: item[0].sourceIdType === 'DxDocument' ? [{
                  label: '升版',
                  value: '升版'
                }] : [{
                  label: '升版',
                  value: '升版'
                },
                {
                  label: '换号',
                  value: '换号'
                }]
              }
            })
            this.treeData.forEach(t => {
              this.changeAffectedData.forEach(c => {
                if (c.oriNumber === t.target.displayNumber) {
                  this.$set(c, 'isabled', true)
                  this.changeAffectedColumns[this.changeAffectedColumns.length - 1].component.disabled = true
                  this.changeAffectedColumns[3].component.disabled = true
                }
              })
            })
          })
        })
      }
    },
    getSelectionList(data) {
      this.selectionList = data
    },
    cellDataChange(data) {
      if (data.row.changeModeCode === '升版') {
        const dxType = this.modeType === 'DxPartDescribeLink' ? 'DxDocument' : 'DxPart'
        getNextVersionKey.bind(this)(dxType, data.row.oriNumber).then(res => {
          this.$set(data.row, 'objVersion', res)
        })
        this.$set(data.row, 'objNumber', data.row.oriNumber)
        this.$set(data.row, 'objName', data.row.oriName)
      } else {
        this.$set(data.row, 'objVersion', '')
      }
      this.changeAffectedData[data.rowIndex] = data.row
      this.setChangeAffectedData = this.setChangeAffectedData.filter(item => item.id !== data.row.id)
      this.setChangeAffectedData.push(data.row)
    },
    changeNumber(data) {
      this.changeAffectedData[data.index] = data.row
      this.setChangeAffectedData = this.setChangeAffectedData.filter(item => item.id !== data.row.id)
      this.setChangeAffectedData.push(data.row)
    },
    submit() {
      if (!this.setChangeAffectedData.length) return
      const data = JSON.parse(JSON.stringify(this.setChangeAffectedData)).map(item => {
        this.$delete(item, 'show')
        this.$delete(item, 'id')
        item.operator = 'ADD'
        item.recordType = this.modeType === 'DxPartDescribeLink' ? 3 : this.rowData.recordType
        return {
          target: item,
          operator: 'ADD'
        }
      })
      addLinks('DxChangeIM', this.imId, 'imRecordLinks', data).then(res => {
        this.$emit('refresh')
        showMessage('操作成功!', 'success')
        this.cancel()
      })
    },
    cancel() {
      this.$emit('close')
      this.value = ''
      this.changeAffectedData = []
      this.setChangeAffectedData = []
    }
  }
}
</script>
<style lang='scss'>
.flexCenter {
  display: flex;
  justify-content: center;
}
</style>