<template>
  <div class="temp-point-view">
    <el-steps :active="activeName" align-center>
      <el-step title="步骤1" description="确定与数据字典中信息点对应"></el-step>
      <el-step title="步骤2" description="确定值得处理方式"></el-step>
      <el-step title="步骤3" description="确认并维护涉及到得原始点位对应得对象标识"></el-step>
    </el-steps>
    <div class="collapse-item" v-show="activeName == 0">
      <el-form class="form" :rules="rules" ref="form" :model="form1" label-width="120px">
        <el-form-item label="对应数据字典" prop="dict">
          <dictionary-cas @change="changeDictionaryCas" ref="dictionaryCas"></dictionary-cas>
        </el-form-item>
      </el-form>
      <div>
        <div v-for="(it,ind) in typeList" :key="ind">
          <p style="margin:10px 0;">信息点名称: {{ it.name }}</p>
          <div class="flex-around">
            <div class="point-despoint">
              <p class="center">原始点位说明</p>
              <p class="p10">{{ pointDes }}</p>
            </div>
            <div class="point-despoint">
              <p class="center">数据字典值说明</p>
              <p class="content-view p10" v-if="it.unitObj.dataSource">{{ delDataSource(it.unitObj.dataSource) }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="center" style="margin-top:20px;">
        <el-button @click="next">下一步</el-button>
      </div>
    </div>
    <div class="collapse-item" v-if="activeName == 1">
      <div v-for="(it,ind) in typeList" :key="ind">
        <p style="margin:10px 0;">信息点名称: {{ it.name }}</p>
        <div class="flex-around">
          <div class="point-despoint">
            <p class="center">原始点位说明</p>
            <p class="p10">{{ pointDes }}</p>
          </div>
          <div class="point-despoint">
            <p class="center">数据字典值说明</p>
            <p class="content-view p10">{{ delDataSource(it.unitObj.DataSource) }}</p>
          </div>
        </div>
        <el-form class="form" :rules="rules" ref="form2" :model="form2" label-width="140px">
          <el-form-item label='值处理方式' prop='DataRuleType'>
            <el-select v-model='it.DataRuleType' placeholder='请选择'>
              <el-option v-for='item in handleTypeArr' :key='item.value' :label='item.label'
                         :value='item.value'></el-option>
            </el-select>
          </el-form-item>
          <!-- components -->
          <div :ref='"noHandle"+ind' v-if='it.DataRuleType == "无需处理，直接使用"'></div>
          <auto-handle :devFlag="false" :ref='"autoHandle"+ind' v-else-if='it.DataRuleType == "需自动单位转换"'
                       :unitObj='it.unitObj'></auto-handle>
          <enum-handle :devFlag="false" :ref='"enumHandle"+ind' v-else-if='it.DataRuleType == "需按设置枚举转换"'></enum-handle>
          <formula-handle :devFlag="false" :ref='"formulaHandle"+ind'
                          v-else-if='it.DataRuleType == "需按公式转换"'></formula-handle>
          <!-- <split-handle :devFlag="false" ref='splitHandle' v-else-if='form2.DataRuleType == "需按拆分枚举转换"'></split-handle> -->
        </el-form>
      </div>
      <div class="center" style="margin-top:20px;">
        <el-button @click="undo">上一步</el-button>
        <el-button @click="next">下一步</el-button>
      </div>
    </div>
    <div class="collapse-item" v-if="activeName == 2">
      <div v-if="renderData.length" style="height:258px;">
        <handsontable-component ref="handsontable" @change="changeTable"></handsontable-component>
      </div>
      <div v-if="!renderData.length" class="center" style="padding: 50px 0;box-sizing:border-box;">
        <i class="icon-wushuju iconfont"></i> 暂无数据
      </div>
      <div v-if="pages.total>pages.size" class="right">
        <pagination :page="pages" @change="changePage"></pagination>
      </div>
      <div class="center" style="margin-top:20px;">
        <el-button @click="undo">上一步</el-button>
        <el-button v-show="renderData.length" @click="save">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
//components
import noHandle from '@/components/config_point/step3_edit/no_handle'
import autoHandle from '@/components/config_point/step3_edit/auto_handle'
import enumHandle from '@/components/config_point/step3_edit/enum_handle'
import formulaHandle from '@/components/config_point/step3_edit/formula_handle'
import splitHandle from '@/components/config_point/step3_edit/split_handle'
import handsontableComponent from "@/components/common/handsontable"
import dictionaryCas from '@/components/config_point/dictionaryCascader'
import pagination from "@/components/common/myPagination"
import handsonUtils from "@/utils/hasontableUtils"
import {
  groupCreatePointRelation
} from "@/api/scan/request";
import {
  mapGetters,
  mapActions
} from "vuex";
import {
  getEquipmentAll,
  getQueryProperty
} from '@/fetch/data_plat'
import {
  updatePoint,
  batchCreate,
  queryDescription
} from '@/fetch/point_http'

export default {
  name: "tempsThree",
  computed: {
    ...mapGetters("project", [
      "datasourceId",
      "protocolType"
    ]),
    projectId() {
      return this.$store.getters['layout/projectId']
    }
  },
  props: {
    renderData: {
      type: Array,
      default: function () {
        return []
      }
    },
    pages: Object,
    queryParam: Object
  },
  data() {
    return {
      activeName: 0,
      form1: {
        dict: 1
      },
      options: [],
      dataDict: {}, //数据字典
      infoDict: {}, //信息点字典
      InfomationPoint: null, //信息点
      unitObj: {}, //传给自动单位转换的obj
      handleTypeArr: [{
        label: '无需处理，直接使用',
        value: '无需处理，直接使用'
      },
        {
          label: '需自动单位转换',
          value: '需自动单位转换'
        },
        {
          label: '需按设置枚举转换',
          value: '需按设置枚举转换'
        },
        {
          label: '需按公式转换',
          value: '需按公式转换'
        },
        // {
        //     label: '需按拆分枚举转换',
        //     value: '需按拆分枚举转换'
        // }
      ],
      dealType: [], //处理方式
      form2: {
        ValueDescription: '',
        DataRuleType: '无需处理，直接使用'
      },
      rules: {
        DataRuleType: [{
          required: true,
          message: '请选择值处理方式',
          trigger: 'change'
        }],
        dict: [{ required: true }]
      },
      pointDes: "",
      typeList: []
    }
  },
  created() {
  },
  mounted() {
    this.init()
  },
  components: {
    noHandle,
    autoHandle,
    enumHandle,
    formulaHandle,
    splitHandle,
    handsontableComponent,
    dictionaryCas,
    pagination
  },
  methods: {
    getMain(param, pagechange) {
      if (!pagechange) {
        this.activeName = 0
        this.dealType = []
        this.form1 = {
          dict: 1
        }
        this.$refs.dictionaryCas.setCascaderVal([])
        this.form2 = {
          ValueDescription: '',
          DataRuleType: '无需处理，直接使用'
        }
        this.unitObj = {}
      }
      let params = {
        data: {
          DataSourceId: this.datasourceId,
          KeyEquipmentParameter: param.EquipmentParameter,
          KeyEquipmentType: param.EquipmentType
        },
        type: this.protocolType
      }
      queryDescription(params, res => {
        this.pointDes = !!res.Content ? res.Content.join("、") : "--"
      })
    },
    //保存
    save() {
      // let data = this.hot.getSourceData()
      // let params = data.map(item => {
      //   let obj = Object.assign({}, {
      //     DataSourceId: this.datasourceId,
      //     PointId: item.Id,
      //     EquipmentMark: item.EquipmentMark
      //   })
      //   return Object.assign(obj, this.dealType)
      // }),
      //   sameFalg = false,
      //   magFalg = false;
      // params.map((item, index) => {
      //   if (!item.EquipmentMark) {
      //     magFalg = true
      //   }
      //   params.map((child, childIndex) => {
      //     if (childIndex != index && child.EquipmentMark == item.EquipmentMark) {
      //       sameFalg = true
      //     }
      //   })
      // })
      // if (sameFalg) {
      //   this.confirm("点位中存在对象标识相同的点位，确认保存吗?", params)
      // } else {
      //   this.createParam(params)
      // }
      let pa = []
      this.dealType.forEach((t, i) => {
        pa.push(Object.assign({
          DataSourceId: this.queryParam.DataSourceId,
          KeyEquipmentParameter: this.queryParam.EquipmentParameter,
          KeyEquipmentType: this.queryParam.EquipmentType,
        }, t));
      })
      groupCreatePointRelation(pa, res => {
        // if (i == this.dealType.length - 1) {
        this.$message.success("处理成功")
        this.$emit("changed")
        // }
      })
    },
    confirm(assage, params) {
      this.$confirm(assage, { type: 'warning' }).then(_ => {
        this.createParam(params)
      }).catch(_ => {
      })
    },
    createParam(params) {
      let updateParams = {
        data: {
          Content: []
        },
        type: this.protocolType
      }
      params.map((item) => {
        updateParams.data.Content.push({
          Id: item.PointId,
          EquipmentMark: item.EquipmentMark
        })
      })
      updatePoint(updateParams, data => {
        batchCreate(params, res => {
          this.$message.success("处理成功")
          this.$emit("changed")
        })
      })
    },
    undo() {
      this.activeName -= 1
    },
    errMsg() {
      this.$message({
        message: '有必填项未填',
        type: 'warning'
      })
    },
    next() {
      var that = this;
      if (this.activeName == 0) {
        this.$refs.dictionaryCas.validate(valid => {
          if (valid) {
            this.activeName += 1
          } else {
            this.errMsg()
          }
        })
      } else if (this.activeName == 1) {
        let isNext = true;
        for (let i = 0; i < this.typeList.length; i++) {
          let flag = this.typeList[i].DataRuleType
          let compon = '';
          switch (flag) {
            case '无需处理，直接使用':
              this.typeList[i].other = {}
              // this.saveForm(this.form2, {})
              break
            case '需自动单位转换':
              compon = `autoHandle${i}`
              this.$refs[compon][0].getForm(autoHandle => {
                if (autoHandle) {
                  this.typeList[i].other = autoHandle;
                  // this.saveForm(this.form2, autoHandle)
                } else {
                  isNext = false
                  this.errMsg()
                }
              })
              break
            case '需按设置枚举转换':
              compon = `enumHandle${i}`
              this.$refs[compon][0].getForm(enumHandle => {
                if (enumHandle) {
                  this.typeList[i].other = enumHandle;
                  // this.saveForm(this.form2, enumHandle)
                } else {
                  isNext = false
                  this.errMsg()
                }
              })
              break
            case '需按公式转换':
              compon = `formulaHandle${i}`
              this.$refs[compon][0].getForm(formulaHandle => {
                if (formulaHandle) {
                  this.typeList[i].other = formulaHandle;
                  // this.saveForm(this.form2, formulaHandle)
                } else {
                  isNext = false
                  this.errMsg()
                }
              })
              break
            // case '需按拆分枚举转换':
            //     this.$refs.splitHandle.getForm(splitHandle => {
            //         if (splitHandle) {
            //             this.saveForm(this.form2, splitHandle)
            //         } else {
            //             isNext = false
            //             this.errMsg()
            //         }
            //     })
            //     break
          }
        }
        if (isNext) {
          this.saveForm();
          this.activeName += 1
          let setting = {
            data: this.renderData,
            maxRows: 1000,
            colHeaders: ['对象标识', '原始点位描述', '位置标签', '备注'],
            columns: [{
              data: 'EquipmentMark'
            },
              {
                data: 'Description',
                readOnly: true
              },
              {
                data: 'LocationFlag',
                readOnly: true
              },
              {
                data: 'Remarks',
                readOnly: true
              }
            ]
          }
          if (this.renderData.length) {
            this.$nextTick(_ => {
              this.hot = this.$refs.handsontable.init(setting)
            })
          }
        }
      }
    },
    saveForm() {
      let params = this.typeList.map((t, i) => {
        let temp = this.dictionaryData[i],
          tempNames = t.name.split('-');
        let eachData = {
          InfomationPointCode: temp[temp.length - 1],
          InfomationPoint: tempNames[tempNames.length - 1],
          DataRuleType: t.DataRuleType,
          // DataSourceId: this.datasourceId, //数据源id
          // PointId: this.editData.Point.Id, //点位ID
          TypeCode: temp[0],
          Type: tempNames[0],
          // EquipmentMark: this.form.EquipmentMark
        }
        if (temp.length == 3) {
          //设备-部件-空间
          eachData.EquipmentTypeCode = temp[1]
          eachData.EquipmentType = tempNames[1]
        } else if (temp.length == 4) {
          eachData.SpecialtyCode = temp[1]
          eachData.Specialty = tempNames[1]
          eachData.SystemCode = temp[2]
          eachData.System = tempNames[2]
          eachData.EquipmentTypeCode = eachData.SystemCode  //为了配置从动参取值存储
          eachData.EquipmentType = eachData.System
        }
        let type = t.DataRuleType;
        switch (type) {
          case '无需处理，直接使用':
            // otherParams = {
            // EquipmentMark: other.EquipmentMark
            // }
            break
          case '需自动单位转换':
            let DataRuleContent1 = JSON.stringify([{
              seq: 1,
              ruletype: 'type1',
              content: [{
                from: t.other.unit[0] + '-' + t.other.unit[1],
                to: this.unitObj.unit
              }]
            }])
            eachData.DataRuleContent = DataRuleContent1;
            // otherParams = {
            // DataRuleContent: DataRuleContent1,
            // EquipmentMark: other.EquipmentMark
            // }
            break
          case '需按设置枚举转换':
            let DataRuleContent2 = t.other.pointArr.length ?
              JSON.stringify([{
                seq: 1,
                ruletype: 'type2',
                content: t.other.pointArr
              }]) :
              undefined
            eachData.DataRuleContent = DataRuleContent2;
            // otherParams = {
            // EquipmentMark: other.EquipmentMark,
            // DataRuleContent: DataRuleContent2
            // }
            break
          case '需按公式转换':
            let subRule = t.other.from ? {
                seq: 1,
                ruletype: 'type4',
                content: [{
                  from: t.other.from,
                  to: t.other.to
                }]
              } :
              undefined
            let extractRule = {
              seq: 2,
              ruletype: 'type5',
              content: t.other.extract ? [{
                extract: 'number'
              }] : []
            }
            let countRule = t.other.mark ? {
                seq: 3,
                ruletype: 'type6',
                content: [{
                  calculationtype: t.other.mark,
                  value: t.other.markValue
                }]
              } :
              undefined
            let DataRuleContent3 = []
            if (subRule) {
              DataRuleContent3.push(subRule)
            }
            DataRuleContent3.push(extractRule)
            if (countRule) {
              DataRuleContent3.push(countRule)
            }
            DataRuleContent3 = DataRuleContent3.length ? JSON.stringify(DataRuleContent3) : undefined
            eachData.DataRuleContent = DataRuleContent3;
            // otherParams = {
            // EquipmentMark: other.EquipmentMark,
            // DataRuleContent: DataRuleContent3
            // }
            break
          case '需拆分处理':
            let SplitPoints = t.other.devArr.length ? t.other.devArr : undefined
            let DataRuleContent4 = undefined
            var enum5 = null
            if (t.other.tranfVal) {
              enum5 = {
                seq: 2,
                ruletype: 'type2',
                content: t.other.pointArr
              }
            } else {
              enum5 = {
                seq: 2,
                ruletype: 'type2',
                content: []
              }
            }
            SplitPoints.forEach(ele => {
              let cutStr = {
                seq: 1,
                ruletype: 'type4',
                content: [{
                  from: ele.SplitStart,
                  to: ele.SplitEnd
                }]
              }
              ele.DataRuleContent = JSON.stringify([cutStr, enum5])
            })
            eachData.SplitPoints = SplitPoints;
            // otherParams = {
            //   SplitPoints: SplitPoints
            // }
            break
        }
        return eachData;
      })
      this.dealType = params
      // this.create(params)
    },
    validateDict(rule, value, cb) {
      if (value.length < 4) {
        cb(new Error('请选到第四级(可能本对象没有信息点)'))
      } else {
        cb()
      }
    },
    handleItemChange(val) {
      if (val.length == 3) {
        let params = {
          type: val[2]
        }
        getQueryProperty(params, res => {
          if (res.Result == 'success') {
            let data = res.Content
            let arr = data
              .filter(item => {
                return item.inputMode == 'L' || item.inputMode == 'M'
              })
              .map(item => {
                return {
                  code: item.infoPointCode,
                  name: item.infoPointName
                }
              })
            this.infoDict = {}
            data.forEach(item => {
              this.infoDict[item.infoPointCode] = item
            })
            this.optionObj = {}
            this.getOptionItem(this.options, val[2])
            if (arr.length) {
              this.optionObj.content = arr
            } else {
              this.optionObj.content = undefined
            }
          }
        })
      }
    },
    getOptionItem(arr, code) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].code == code) {
          this.optionObj = arr[i]
        }
        if (arr[i].content && arr[i].content.length > 0) {
          this.getOptionItem(arr[i].content, code)
        } else {
          this.$set(arr, 'content', [])
        }
      }
    },
    getEqAll() {
      let params = {
        format: true
      }
      getEquipmentAll(params, res => {
        if (res.Result == 'success') {
          this.options = res.Content
          this.getDataDict(this.options)
        }
      })
    },
    //缓存数据字典
    getDataDict(arr) {
      for (var i = 0; i < arr.length; i++) {
        this.dataDict[arr[i].code] = arr[i]
        if (arr[i].content && arr[i].content.length > 0) {
          this.getDataDict(arr[i].content)
        } else {
          this.$set(arr[i], 'content', [])
        }
      }
    },
    init() {
      //获取所有的设备
      this.getEqAll()
    },
    //处理函数
    delDataSource(val) {
      if (!val) {
        return '--'
      }
      val = JSON.parse(val)
      let str = ''
      val.forEach(el => {
        str += el.code + '.' + el.name + ' '
      })
      return str
    },
    //对应数据字典变化
    changeDictionaryCas({ val, labels, data }) {
      this.dictionaryData = val;
      this.dictionaryNames = labels;
      this.unitObj = data
      if (this.typeList.length) {
        this.typeList = this.typeList.map(t => {
          if (labels.indexOf(t.name) < 0) {
            return undefined
          }
          return t;
        }).filter(item => item)
        let temp = this.typeList.map(t => {
          return t.name;
        })
        for (let i = 0; i < labels.length; i++) {
          if (temp.indexOf(labels[i]) < 0) {
            this.typeList.push({
              name: labels[i],
              DataRuleType: '无需处理，直接使用'
            })
          }
        }
      } else {
        this.typeList = labels.map(t => {
          return {
            name: t,
            DataRuleType: '无需处理，直接使用'
          }
        })
      }
      this.typeList = this.typeList.map((t, i) => {
        t.unitObj = data[val[i][val[i].length - 1]];
        return t;
      })
    },
    //分页发生更改
    changePage() {
      this.$emit('changePage', this.queryParam);
    },
    // 修改table
    changeTable(changeData, source) {
      console.log(source)
      if (source == 'edit' || source == 'Autofill.fill') {
        let trimmedArr = this.trimmedRows();
        let param = handsonUtils.getParam(changeData, source, this.hot, trimmedArr);
        let updateParams = {
          data: {
            Content: []
          },
          type: this.protocolType
        }
        updateParams.data.Content = param.map(t => {
          return {
            Id: t.Id,
            EquipmentMark: t.EquipmentMark
          }
        })
        console.log(updateParams)
        updatePoint(updateParams, data => {
          this.$message.success("修改成功")
        })
      }
    },
    //获取被筛选掉的行号
    trimmedRows() {
      var plugin = this.hot.getPlugin("trimRows").trimmedRows;
      let dataLength = this.renderData.length;
      let dataArr = new Array();
      for (let i = 0; i < dataLength; i++) {
        dataArr.push(i);
      }
      if (plugin.length <= 0) {
        dataArr = undefined;
      } else {
        dataArr = this.array_diff(dataArr, plugin);
      }
      return dataArr || [];
    },
    //去除数组中相同的元素
    array_diff(a, b) {
      for (var i = 0; i < b.length; i++) {
        for (var j = 0; j < a.length; j++) {
          if (a[j] == b[i]) {
            a.splice(j, 1);
            j = j - 1;
          }
        }
      }
      return a;
    },
  },
  watch: {
    'renderData': {
      handler(n, o) {
        if (n.length && this.hot) {
          this.hot.loadData(n);
          console.log('load')
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>
<style lang="scss" scoped>
.temp-point-view {
  padding: 10px;
  box-sizing: border-box;

  .el-steps {
    margin-bottom: 10px;
  }

  .flex-around {
    display: flex;
    justify-content: space-around;
    // margin-bottom: 5px;
    width: 100%;
    overflow: hidden;

    .point-despoint {
      width: 240px;
      border: 1px solid #dcdfe6;
      height: 190px;
      margin-bottom: 10px;

      .content-view {
        padding: 5px;
        box-sizing: border-box;
      }
    }
  }

  .collapse-item {
    height: 328px;
    overflow-y: auto;
  }
}
</style>
