<template>
  <div class='point-box'>
    <div class='left'>
      <ul>
        <li>
          <span>原始点位信息</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.Description || '--'">{{editData.Point.Description || '--'}}</span>
        </li>
        <li>
          <span>位置标签</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.LocationFlag.toString() || '--'">{{editData.Point.LocationFlag.toString() || '--'}}</span>
        </li>
        <li>
          <span>对象类型</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.KeyEquipmentType || '--'">{{editData.Point.KeyEquipmentType || '--'}}</span>
        </li>
        <li>
          <span>对象参数</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.KeyEquipmentParameter || '--'">{{editData.Point.KeyEquipmentParameter || '--'}}</span>
        </li>
        <li>
          <span>值/单位说明</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.ValueDescription || '--'">{{editData.Point.ValueDescription || '--'}}</span>
        </li>
        <li>
          <span>备注</span>&nbsp;&nbsp;&nbsp;
          <span :title="editData.Point.Remarks || '--'">{{editData.Point.Remarks || '--'}}</span>
        </li>
      </ul>
    </div>
    <div class='right'>
      <el-form class='form' :rules='rules' ref='form' :model='form' label-width='140px'>
        <el-form-item label='对应数据字典' prop='diction'>
          <dictionary-cas @change="changeDictionaryCas" ref="dictionaryCas"></dictionary-cas>
        </el-form-item>
        <el-form-item label='对象标识' prop="EquipmentMark">
          <el-input v-model='form.EquipmentMark'></el-input>
        </el-form-item>
        <template v-for="(it,index) in typeList">
          <div class='dict' :key="index">
            <label class="el-form-item__label" style="width:140px;">信息点名称:</label><span style="line-height:40px">{{it.name||''}}</span>
            <p class='btm'>
              <el-input readonly type='textarea' :rows='2' placeholder='信息点的单位及值的说明' v-model='it.ValueDescription'>
              </el-input>
              <el-form-item style="margin-top:15px;" 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>
            </p>
            <!-- components -->
            <no-handle :ref='"noHandle"+index' v-if='it.DataRuleType == "无需处理，直接使用"' :noHandleShow='noHandleShow'></no-handle>
            <auto-handle :ref='"autoHandle"+index' v-else-if='it.DataRuleType == "需自动单位转换"' :unitObj='it' :autoHandleShow='autoHandleShow'>
            </auto-handle>
            <enum-handle :ref='"enumHandle"+index' v-else-if='it.DataRuleType == "需按设置枚举转换"' :enumHandleShow='enumHandleShow'></enum-handle>
            <formula-handle :ref='"formulaHandle"+index' v-else-if='it.DataRuleType == "需按公式转换"' :formulaHandleShow='formulaHandleShow'>
            </formula-handle>
            <split-handle :ref='"splitHandle"+index' v-else-if='it.DataRuleType == "需拆分处理"' :splitHandleShow='splitHandleShow'></split-handle>
          </div>
        </template>
      </el-form>
      <div class='btn-box'>
        <el-button type='primary' @click='save'>保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
//components
import noHandle from './no_handle'
import autoHandle from './auto_handle'
import enumHandle from './enum_handle'
import formulaHandle from './formula_handle'
import splitHandle from './split_handle'
import { mapGetters, mapActions } from 'vuex'
//api
import { getEquipmentAll, getQueryProperty } from '@/fetch/data_plat'
import { updatePoint, batchCreate } from '@/fetch/point_http'
import dictionaryCas from '@/components/config_point/dictionaryCascader'
export default {
  name: 'point_config_step3_edit',
  computed: {
    ...mapGetters('project', ['projectId', 'datasourceId', 'protocolType'])
  },
  data() {
    return {
      options: [],
      optionObj: {},
      infoDict: {}, //信息点字典
      dataDict: {}, //数据字典
      InfomationPoint: null, //信息点
      unitObj: {}, //传给自动单位转换的obj
      ValueDescription: {}, //值/点位描述
      form: {
        diction: '1',//占位
        DataRuleType: '无需处理，直接使用',
        EquipmentMark: ''
      },
      rules: {
        DataRuleType: [{ required: true, message: '请选择值处理方式', trigger: 'change' }],
        diction: [{ required: true }],
        EquipmentMark: [{ required: true, message: '请输入对象标识', trigger: 'blur' }],
      },
      handleTypeArr: [
        {
          label: '无需处理，直接使用',
          value: '无需处理，直接使用'
        },
        {
          label: '需自动单位转换',
          value: '需自动单位转换'
        },
        {
          label: '需按设置枚举转换',
          value: '需按设置枚举转换'
        },
        {
          label: '需按公式转换',
          value: '需按公式转换'
        },
        {
          label: '需拆分处理',
          value: '需拆分处理'
        }
      ],
      /**值回显******* */
      noHandleShow: {},
      autoHandleShow: {},
      enumHandleShow: {},
      formulaHandleShow: {},
      splitHandleShow: {},
      dictionaryData: [],
      typeList: []
    }
  },
  props: {
    editData: {
      type: Object,
      default: {}
    }
  },
  components: {
    noHandle,
    autoHandle,
    enumHandle,
    formulaHandle,
    splitHandle,
    dictionaryCas
  },
  methods: {
    //保存
    save() {
      if (!this.form.EquipmentMark) {
        this.errMsg();
        return false;
      }
      this.$refs.dictionaryCas.validate(valid => {
        if (valid) {
          for (let i = 0; i < this.typeList.length; i++) {
            let flag = this.typeList[i].DataRuleType
            switch (flag) {
              case '无需处理，直接使用':
                let componnoHandle = `noHandle${i}`
                this.$refs[componnoHandle][0].getForm(noHandle => {
                  if (noHandle) {
                    this.typeList[i].other = noHandle
                    // this.saveForm(this.form, noHandle)
                  } else {
                    this.errMsg();
                    return false;
                  }
                })
                break
              case '需自动单位转换':
                let componautoHandle = `autoHandle${i}`
                this.$refs[componautoHandle][0].getForm(autoHandle => {
                  if (autoHandle) {
                    this.typeList[i].other = autoHandle
                    // this.saveForm(this.form, autoHandle)
                  } else {
                    this.errMsg()
                    return false;
                  }
                })
                break
              case '需按设置枚举转换':
                let componenumHandle = `enumHandle${i}`
                this.$refs[componenumHandle][0].getForm(enumHandle => {
                  if (enumHandle) {
                    this.typeList[i].other = enumHandle
                    // this.saveForm(this.form, enumHandle)
                  } else {
                    this.errMsg()
                    return false;
                  }
                })
                break
              case '需按公式转换':
                let componformulaHandle = `formulaHandle${i}`
                this.$refs[componformulaHandle][0].getForm(formulaHandle => {
                  if (formulaHandle) {
                    this.typeList[i].other = formulaHandle
                    // this.saveForm(this.form, formulaHandle)
                  } else {
                    this.errMsg()
                    return false;
                  }
                })
                break
              case '需拆分处理':
                let componsplitHandle = `splitHandle${i}`
                this.$refs[componsplitHandle][0].getForm(splitHandle => {
                  if (splitHandle) {
                    this.typeList[i].other = formulaHandle
                    // this.saveForm(this.form, splitHandle)
                  } else {
                    this.errMsg()
                    return false;
                  }
                })
                break
            }
          }
          this.saveForm()
        } else {
          this.errMsg()
          return false
        }
      })
    },
    saveForm() {
      let updateParams = {
        data: {
          Content: [{ Id: this.editData.Point.Id }]
        },
        type: this.protocolType
      }
      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;
        updateParams.data.Content[0].EquipmentMark = eachData.EquipmentMark
        switch (type) {
          case '无需处理，直接使用':
            // otherParams = {
            //   EquipmentMark: other.EquipmentMark
            // }
            // updateParams.data.Content[0].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[eachData.InfomationPointCode].unit
                  }
                ]
              }
            ])
            eachData.DataRuleContent = DataRuleContent1;
            // otherParams = {
            //   DataRuleContent: DataRuleContent1,
            //   EquipmentMark: other.EquipmentMark
            // }
            // updateParams.data.Content[0].EquipmentMark = other.EquipmentMark
            break
          case '需按设置枚举转换':
            let DataRuleContent2 = t.other.pointArr.length
              ? JSON.stringify([{ seq: 1, ruletype: 'type2', content: t.other.pointArr }])
              : undefined
            // otherParams = {
            //   EquipmentMark: other.EquipmentMark,
            //   DataRuleContent: DataRuleContent2
            // }
            eachData.DataRuleContent = DataRuleContent2;
            // updateParams.data.Content[0].EquipmentMark = other.EquipmentMark
            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
            // }
            // updateParams.data.Content[0].EquipmentMark = other.EquipmentMark
            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
            // }
            updateParams.data.Content[0].EquipmentMark = t.other.eqMark
            break
        }
        return eachData;
      })
      updatePoint(updateParams, res => { this.create(params) })
    },
    create(params) {
      batchCreate(params, res => {
        if (res.Result == 'success') {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.$emit('refresh')
        }
      })
    },
    errMsg() {
      this.$message({
        message: '有必填项未填',
        type: 'warning'
      })
    },
    handleChange(arr) {
      this.unitObj = this.infoDict[arr[3]]
      this.InfomationPoint = this.unitObj ? this.unitObj.infoPointName || '--' : '--'
    },
    handleItemChange(val, cb) {
      if (val.length == 3) {
        if (val[2] != 'null') {
          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
              }

              if (typeof cb == 'function') {
                cb()
              }
            }
          })
        }
      }
    },
    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)
        }
      }
    },
    //缓存数据字典
    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', [])
        }
      }
    },
    getEqAll() {
      let params = { format: true }
      getEquipmentAll(params, res => {
        if (res.Result == 'success') {
          this.options = res.Content
          this.getDataDict(this.options)
        }
      })
    },
    init() {
      //获取所有的设备
      // this.getEqAll()
    },
    //回显数值
    async showValue(val) {
      // await this.getEqAll()
      let length = val.RelationList.length
      let eqMark = this.editData.Point.EquipmentMark
      this.form.EquipmentMark = eqMark;
      console.log('-------------')
      console.log(val)
      if (length) {
        var data = val.RelationList[0]
        let dict = [data.SpecialtyCode, data.SystemCode, data.EquipmentTypeCode]
        //回显字典
        let tempArr = val.RelationList.map(t => {
          let eachData = [];
          if (t.TypeCode == 'Eq' || t.TypeCode == 'Ec' || t.TypeCode == 'Sp') {
            eachData = [t.TypeCode, t.EquipmentTypeCode, t.InfomationPointCode]
          } else if (t.TypeCode == 'Sy') {
            eachData = [t.TypeCode, t.SpecialtyCode, t.SystemCode, t.InfomationPointCode]
          } else {
            eachData = [t.TypeCode, t.InfomationPointCode]
          }
          return eachData;
        })
        this.$nextTick(() => {
          this.$refs.dictionaryCas.setCascaderVal(tempArr);
        })
        this.typeList = val.RelationList.map(t => {
          if (t.TypeCode == 'Eq' || t.TypeCode == 'Ec' || t.TypeCode == 'Sp') {
            t.name = `${t.Type}-${t.EquipmentType}-${t.InfomationPoint}`
          } else if (t.TypeCode == 'Sy') {
            t.name = `${t.Type}-${t.Specialty}-${t.System}-${t.InfomationPoint}`
          } else {
            t.name = `${t.Type}-${t.InfomationPoint}`
          }
          return t;
        });
        this.form.DataRuleType = data.DataRuleType
        // this.handleItemChange(dict, () => {
        // this.unitObj = this.infoDict[data.InfomationPointCode]
        // this.InfomationPoint = this.unitObj.infoPointName || '--'
        // if (typeof this.unitObj.dataSource == 'string') {
        //   if (this.unitObj.dataSource.length) {
        //     this.ValueDescription = this.unitObj.dataSource
        //   } else {
        //     this.ValueDescription = '无信息点单位及值说明'
        //   }
        // } else {
        //   let str = ''
        //   this.unitObj.dataSource.forEach(ele => {
        //     str += ele.code + '.' + ele.name + ' '
        //   })
        //   this.ValueDescription = str
        // }
        // })
        if (length == 1) {
          let flag = data.DataRuleType
          var dataRules = null
          switch (flag) {
            case '无需处理，直接使用':
              this.noHandleShow = {
                EquipmentMark: eqMark
              }
              break
            case '需自动单位转换':
              dataRules = JSON.parse(data.DataRuleContent)
              let auto = dataRules[0].content[0].from.split('-')
              this.autoHandleShow = {
                EquipmentMark: eqMark,
                unit: auto
              }
              break
            case '需按设置枚举转换':
              dataRules = JSON.parse(data.DataRuleContent)
              let pointArr = dataRules[0].content
              this.enumHandleShow = {
                EquipmentMark: eqMark,
                pointArr: pointArr
              }
              break
            case '需按公式转换':
              var cut = null
              var count = null
              var extractArr = []
              if (data.DataRuleContent) {
                dataRules = JSON.parse(data.DataRuleContent)
                cut = dataRules[0].content[0]
                extractArr = dataRules[1].content
                count = dataRules[2].content[0]
              }
              this.formulaHandleShow = {
                EquipmentMark: eqMark,
                cut: cut,
                count: count,
                extractArr: extractArr
              }
              break
            case '需拆分处理':
              let dataRules = JSON.parse(data.DataRuleContent)
              let devArr = val.RelationList.map(ele => {
                let arr = JSON.parse(ele.DataRuleContent)
                return {
                  EquipmentMark: ele.EquipmentMark,
                  SplitStart: arr[0].content[0].from,
                  SplitEnd: arr[0].content[0].to
                }
              })
              var pointArr = dataRules[1].content
              this.splitHandleShow = {
                eqMark: eqMark,
                EquipmentMark: data.EquipmentMark,
                pointArr: pointArr,
                devArr: devArr
              }
              break
          }
        } else {
          let dataRules = JSON.parse(data.DataRuleContent)
          let devArr = val.RelationList.map(ele => {
            let arr = JSON.parse(ele.DataRuleContent)

            return {
              EquipmentMark: ele.EquipmentMark,
              SplitStart: arr[0].content[0].from,
              SplitEnd: arr[0].content[0].to
            }
          })
          let pointArr = dataRules[1].content
          this.splitHandleShow = {
            eqMark: eqMark,
            EquipmentMark: data.EquipmentMark,
            pointArr: pointArr,
            devArr: devArr
          }
        }
      } else {
        this.noHandleShow = {
          EquipmentMark: eqMark
        }
      }
      this.noHandleShow.EquipmentMark = eqMark
      this.autoHandleShow.EquipmentMark = eqMark
      this.enumHandleShow.EquipmentMark = eqMark
      this.enumHandleShow.pointArr = this.enumHandleShow.pointArr ? this.enumHandleShow.pointArr : [{ from: '', to: '' }]
      this.formulaHandleShow.EquipmentMark = eqMark
      this.splitHandleShow.eqMark = eqMark
      this.splitHandleShow.devArr = this.splitHandleShow.devArr ? this.splitHandleShow.devArr : [{ EquipmentMark: '', SplitStart: 1, SplitEnd: 1 }]
      this.splitHandleShow.pointArr = this.splitHandleShow.pointArr ? this.splitHandleShow.pointArr : [{ from: '', to: '' }]
    },
    //处理函数
    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.ValueDescription = this.delDataSource(data[val[i][val[i].length - 1]].DataSource)
        return t;
      })
      // this.infoDict = this.$refs.dictionaryCas.pointDataSource
      // this.InfomationPoint = this.unitObj.InfoPointName || ''
      // this.ValueDescription = this.delDataSource(this.unitObj.DataSource)
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    editData: {
      immediate: true,
      handler(val) {
        this.showValue(val)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.point-box {
  border: 1px solid #ccc;
  display: flex;
  padding: 20px 0;
  max-height: 500px;
  overflow: auto;
  .left {
    width: 40%;
    ul li {
      display: flex;
      height: 40px;
      line-height: 40px;
      span:nth-of-type(1) {
        text-align: right;
        width: 120px;
      }
      span:nth-of-type(2) {
        width: calc(100% - 120px);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .right {
    width: 60%;
    text-align: left;
    background: #fff;
    .form {
      width: 80%;
      .dict {
        .top {
          text-align: right;
          line-height: 33px;
        }
        .btm {
          margin-top: 5px;
          margin-left: 140px;
        }
      }
    }
    .btn-box {
      width: 80%;
      margin-top: 20px;
      text-align: center;
    }
  }
}
</style>
