<template>
  <vxe-modal
    ref="multiAdd"
    v-model="show"
    :title="'批量添加'"
    width="900"
    height="auto"
    resize
    destroy-on-close
    @close="cancelButtonClick"
  >
    <p style="color: red;padding-left:20px">批量生成的点位将按序排在通道末尾的点位后</p>
    <vxe-form
      ref="form"
      :data="formData"
      :rules="formRules"
      title-align="center"
      title-width="100"
    >
      <vxe-form-item title="数据源" field="dataSource" span="6">
        <vxe-select v-model="formData.dataSource" placeholder="数据来源" size="big">
          <vxe-option
            v-for="item in enums.senderDataSourceEnum"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </vxe-select>
      </vxe-form-item>

      <vxe-form-item title="使用通道" field="tunnelId" span="8">
        <vxe-select
          v-model="formData.tunnelId"
          placeholder="请选择使用通道"
          size="medium"
          @change="tunnelChange"
        >
          <vxe-option v-for="item in tunnelList" :key="item.id" :value="item.id" :label="item.tunnelName"/>
        </vxe-select>
      </vxe-form-item>

      <vxe-form-item title="通道数据类型" field="protocolPointType" span="9" title-width="150px">
        <vxe-select v-model="formData.protocolPointType" placeholder="请选择通道数据类型" size="medium">
          <vxe-option
            v-for="item in protocolDataType"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </vxe-select>
      </vxe-form-item>
      <vxe-form-item v-show="formData.dataSource=='GATHER'" title="设备类型" field="eqType" span="6">
        <vxe-select v-model="formData.eqType" placeholder="请选择设备类型" size="medium"
                    @change="flushEqsOfSelectEqType">
          <vxe-option
            v-for="item in enums.equipmentTypeEnum"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </vxe-select>
      </vxe-form-item>
      <vxe-form-item v-show="formData.dataSource=='GATHER'" title="设备名" field="equipmentId" span="10">
        <vxe-select v-model="formData.equipmentId" placeholder="请选择设备名" size="medium"
                    @change="flushAttrsOfSelectEq">
          <vxe-option v-for="(item,index) in eqsOfSelectEqType" :key="index" :value="item.id" :label="item.name"/>
        </vxe-select>
      </vxe-form-item>
      <vxe-form-item v-show="formData.dataSource=='GATHER'" title="设备属性" field="equipmentAttrs" span="14">
        <el-select v-model="formData.equipmentAttrs" multiple collapse-tags placeholder="请选择设备属性" size="small">
          <el-option
            v-for="item in attrsOfSelectEq"
            :value="item.id"
            :label="item.equipmentAttribute.explanation"
          />
        </el-select>
      </vxe-form-item>

      <vxe-form-item
        v-show="formData.dataSource=='FORECAST'"
        title="预测数据属性"
        field="forecastType"
        span="10"
        title-width="120"
      >
        <vxe-select v-model="formData.forecastType" placeholder="请选择预测数据属性" @change="forecastDayChange">
          <vxe-option v-for="item in enums.forecastType" :key="item.value" :value="item.value" :label="item.label"/>
        </vxe-select>
      </vxe-form-item>
      <vxe-form-item v-show="formData.dataSource=='FORECAST'" title="预测天数" span="10" field="forecastNode">
        <el-select
          v-model="formData.forecastNode"
          multiple
          collapse-tags
          placeholder="请选择预测天数"
          size="small"
          @change="forecastNodeChangeEvent"
        >
          <el-option v-for="item in forecastDay" :key="item.value" :value="item.value" :label="item.label"/>
        </el-select>
      </vxe-form-item>
      <vxe-form-item v-show="formData.dataSource=='FORECAST'" title="预测点位" span="10" field="forecastPointNumber">
        <el-select v-model="formData.forecastPointNumber" multiple collapse-tags placeholder="请选择预测点数"
                   size="small">
          <el-option v-for="item in forecastAttributeList" :value="item.pointNumber" :label="item.pointNumber"/>
        </el-select>
      </vxe-form-item>

      <!--占地方用的-->
      <div style="height: 300px"/>
      <vxe-form-item align="center" span="24">
        <vxe-button type="submit" status="primary" :disabled="saveButDisable" @click="submitForm">保存</vxe-button>
        <vxe-button @click="cancelButtonClick()">取消</vxe-button>
      </vxe-form-item>
    </vxe-form>
  </vxe-modal>
</template>

<script>
import enumerations from '../../enumeration'

export default {
  name: 'MultiAddVue',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      eqsOfSelectEqType: [],
      attrsOfSelectEq: [],
      forecastDay: [],
      forecastAttributeList: [],
      saveButDisable: false,
      formData: {
        eqType: '',
        dataSource: 'GATHER',
        tunnelId: '',
        protocolPointType: '',
        equipmentId: '',
        forecastType: '',
        forecastNode: [],
        forecastPointNumber: [],
        equipmentAttrs: []
      },
      tunnelList: [],
      formRules: {
        dataSource: [{required: true, message: '请选择数据源'}],
        tunnelId: [{required: true, message: '请选择通道'}],
        protocolPointType: [{required: true, message: '请选择数据类型'}]
      },
      enums: enumerations,
      protocolDataType: enumerations.ProtocolDataType
    }
  },
  mounted() {
    this.buildTunnelSelectData()
  },
  methods: {
    /**
     * 点击取消或关闭按钮时通知父组件修改值
     */
    cancelButtonClick() {
      this.saveButDisable = false
      this.resetForm()
      this.$emit('close')
    },

    /**
     * 当所选设备类型发生改变时 刷新设备属性下拉框对应的设备名下拉
     */
    flushEqsOfSelectEqType() {
      this.attrsOfSelectEq = []
      this.formData.equipmentAttrs = []
      this.formData.equipmentId = null
      this.resultHandler(this.getEqsByEqTypeCode(this.formData.eqType)).then(res => {
        if (res != null) {
          this.eqsOfSelectEqType = res
        }
      })
    },

    /**
     * 提交表单
     */
    submitForm() {
      const _this = this
      _this.saveButDisable = true
      this.$refs.form.validate().then(async res => {
        let max = 0
        max = await this.resultHandler(_this.$axios.get('/dataExchange/senderProtocolDataPoint/maxProtocolNoInTunnel', {params: {tunnelId: _this.formData.tunnelId}})).then(res => {
          return res == null ? 0 : res
        })
        if (this.formData.dataSource == 'GATHER') {
          if (this.formData.equipmentAttrs.length == 0) {
            _this.$XModal.message({message: '并未选择需要添加的属性'})
            return
          }
          let str = '将'
          this.eqsOfSelectEqType.forEach(function (currentValue, index, arr) {
            if (currentValue.id == _this.formData.equipmentId) {
              str += currentValue.name + '的-'
              return false
            }
          })
          const name = new Array()
          let i = 0
          this.attrsOfSelectEq.forEach(function (currentValue, index, arr) {
            i = _this.formData.equipmentAttrs.indexOf(currentValue.id)
            if (i >= 0) {
              name[i] = currentValue.equipmentAttribute.explanation
            }
          })
          for (const j in name) {
            str += '[' + name[j] + ':' + (max * 1 + j * 1 + 1) + ']-'
          }
          str += name.length + '个状态点依次添加到'
          this.tunnelList.forEach(function (currentValue, index, arr) {
            if (currentValue.id == _this.formData.tunnelId) {
              str += currentValue.tunnelName
              return false
            }
          })
          str += '通道的末端（' + (max * 1 + 1) + '）'
          this.$XModal.confirm(str).then(type => {
            if (type == 'confirm') {
              for (const i in _this.formData.equipmentAttrs) {
                const param = {
                  dataSource: _this.formData.dataSource,
                  tunnelId: _this.formData.tunnelId,
                  protocolPointType: _this.formData.protocolPointType,
                  magnification: 1
                }
                param.gatherPoint = _this.formData.equipmentAttrs[i]
                param.protocolPointNo = max * 1 + i * 1 + 1
                _this.$axios.post('/dataExchange/senderProtocolDataPoint/saveDataPoint', param).then(res => {
                  if (res.code == 0) {
                    _this.$XModal.message({message: '保存转发点位成功'})
                    _this.saveButDisable = false
                  } else {
                    _this.$XModal.message({message: '保存转发点位失败'})
                    _this.saveButDisable = false
                  }
                })
              }
            } else {
              _this.saveButDisable = false
            }
          })
        } else if (this.formData.dataSource == 'FORECAST') {
          if (this.formData.forecastPointNumber.length == 0) {
            _this.$XModal.message({message: '并未选择需要添加的预测属性'})
            return
          }
          let str = '将'
          this.enums.forecastType.forEach(function (currentValue, index, arr) {
            if (currentValue.value == _this.formData.forecastType) {
              str += currentValue.label + '的-'
              return false
            }
          })
          const days = []
          this.forecastDay.forEach(function (currentValue, index, arr) {
            var index = _this.formData.forecastNode.indexOf(currentValue.value)
            if (index >= 0) {
              days[index] = currentValue.label
            }
          })
          for (const j in days) {
            str += '[第' + days[j] + ']-'
          }
          str += '每天' + _this.formData.forecastPointNumber.length + '个预测数据依次添加到'
          this.tunnelList.forEach(function (currentValue, index, arr) {
            if (currentValue.id == _this.formData.tunnelId) {
              str += currentValue.tunnelName
              return false
            }
          })
          str += '通道的末端（' + (max * 1 + 1) + '）'
          this.$XModal.confirm(str).then(type => {
            if (type == 'confirm') {
              const param = {
                tunnelId: _this.formData.tunnelId,
                protocolPointType: _this.formData.protocolPointType,
                forecastType: _this.formData.forecastType,
                forecastNodes: _this.formData.forecastNode,
                pointNumbers: _this.formData.forecastPointNumber
              }
              _this.$axios.post('/dataExchange/senderProtocolDataPoint/batchSaveForecastPoint', param).then(res => {
                if (res.code == 0) {
                  _this.$XModal.message({message: '保存转发点位成功'})
                  _this.saveButDisable = false
                } else {
                  _this.$XModal.message({message: '保存转发点位失败'})
                  _this.saveButDisable = false
                }
              })
            }
          })
        }
      })
    },

    /**
     * 预测天数多选下拉框值发生变化时 补充预测点位下拉框的值
     */
    forecastNodeChangeEvent() {
      if (this.formData.forecastNode.length == 1) {
        this.formData.forecastPointNumber = []
        for (const i in this.forecastAttributeList) {
          this.formData.forecastPointNumber.push(this.forecastAttributeList[i].pointNumber)
        }
      } else if (this.formData.forecastNode.length == 0) {
        this.formData.forecastPointNumber = []
      }
    },
    /**
     * 当所选设备发生改变时 刷新该设备下对应的点位
     */
    flushAttrsOfSelectEq() {
      this.formData.equipmentAttrs = []
      const params = {
        equipmentType: this.formData.eqType,
        equipmentId: this.formData.equipmentId
      }
      if (this.formData.eqType == 'POWERSTATION') {
        params.equipmentId = null
      }
      this.resultHandler(this.$axios.get('/dataExchange/protocolDataPoint/gatherDataPoint', {params: params})).then(res => {
        this.attrsOfSelectEq = res
      })
    },

    /**
     *根据设备类型获取该类型下的设备属性
     * 可以传设备类型的ID 或NAME  即 可以传0 或 POWERSTATION
     * @param code
     * @returns {*}
     */
    getEqsByEqTypeCode(typeCode) {
      const axios = this.$axios
      if (typeCode === 0 || typeCode === 'POWERSTATION') {
        // 当设备类型是电站时对数数据进行处理后返回
        return new Promise(function (resolve, reject) {
          axios.get('/electricField/').then(res => {
            if (res.code == 0) {
              const eqs = []
              res.data.id = res.data.stationCode
              eqs.push(res.data)
              res.data = eqs
            }
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      } else {
        return axios.get('/dataExchange/equipmentInfo/' + typeCode)
      }
    },

    /**
     *针对于后台返回的信息进行二次处理的方法
     * @param  promise Promise
     * @returns {Promise}
     */
    resultHandler(promise) {
      const message = this.$message
      return new Promise(function (resolve, reject) {
        promise.then(res => {
          if (res.code == 0) {
            resolve(res.data)
          } else {
            message.error(res.msg)
            reject(new Error(res.msg))
          }
        }).catch(error => {
          message.error('请求后台时发生异常')
          reject(error)
        })
      })
    },
    /**
     * 查询到所有采集通道
     * @returns {*}
     */
    getAllSenderTunnel() {
      return this.$axios.get('/TunnelInfo/getTunnel/Slave')
    },

    /**
     * 预测属性变化时  天数或者小时数随之变化
     */
    forecastDayChange() {
      this.formData.forecastNode = ''
      this.forecastAttributeList = []
      if (this.formData.forecastType === 'ULTRA_SHORT_AVAILABLE' || this.formData.forecastType === 'ULTRA_SHORT_THEORETICAL') {
        this.forecastDay = [{label: '第1小时', value: 0},
          {label: '第2小时', value: 1},
          {label: '第3小时', value: 2},
          {label: '第4小时', value: 3}]
      } else {
        this.forecastDay = [{label: '第1天', value: 0}, {label: '第2天', value: 1}, {
          label: '第3天',
          value: 2
        }, {label: '第4天', value: 3}, {label: '第5天', value: 4},
          {label: '第6天', value: 5}, {label: '第7天', value: 6}, {label: '第8天', value: 7}, {
            label: '第9天',
            value: 8
          }, {label: '第10天', value: 9}, {label: '第11天', value: 10}]
      }
      this.forecastAttributeList = []
      this.resultHandler(this.$axios.get('/dataExchange/ForecastForSendAttribute/' + 0 + '/' + this.formData.forecastType)).then(res => {

        this.forecastAttributeList = res
      })
    },

    /**
     * 根据所有通道信息构建通道下拉框的 展示数据
     */
    buildTunnelSelectData() {
      this.resultHandler(this.getAllSenderTunnel()).then(res => {
        if (res !== null) {
          this.tunnelList = res
        }
      })
    },

    /**
     *对form表单内的数据进行重置
     */
    resetForm() {
      this.formData = {
        eqType: '',
        dataSource: 'GATHER',
        tunnelId: '',
        protocolPointType: '',
        equipmentId: '',
        forecastType: '',
        forecastNode: [],
        forecastPointNumber: [],
        equipmentAttrs: []
      }
      this.protocolDataType = this.enums.ProtocolDataType
    },
    tunnelChange() {
      this.protocolDataType = []
      this.formData.protocolPointType = ''
      for (let i = 0; i < this.tunnelList.length; i++) {
        if (this.formData.tunnelId === this.tunnelList[i].id) {
          if (this.tunnelList[i].tunnelType.substring(0, 3) === 'IEC' || this.tunnelList[i].tunnelType.substring(0, 3) === 'FIL') {
            this.protocolDataType = [{label: '遥信开关量', value: 'A', key: 0}, {label: 'ABCD', value: 'ABCD', key: 9}]
          } else if (this.tunnelList[i].tunnelType.substring(0, 3) === 'CDT') {
            this.protocolDataType = [{label: '遥信开关量', value: 'A', key: 0}, {label: '+AB', value: 'P_AB', key: 1}]
          } else {
            this.protocolDataType = this.enums.ProtocolDataType
          }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>

