<!-- 步骤1 设备基本信息 -->
<template>
  <div v-show="currentStep==0" :class="className">
    <div class="form-title">设备基本信息</div>
    <div class="form-sub-title">
      带*为必填项
    </div>
    <!--
    <div class="device-name">
      <div class="lable-title"><span>*</span>设备名称</div>
      <div class="lable">
        <el-input
          v-model="requestData.name"
          placeholder="请输入设备名称"
          clearable
          maxlength="32"
        />
      </div>
    </div>
    -->
    <div class="device-sn">
      <div class="lable-title"><span>*</span>设备编号</div>
      <div class="lable">
        <el-input
          v-model="requestData.serialNumber"
          placeholder="请输入设备编号"
          clearable
          maxlength="32"
        />
      </div>
    </div>
    <div class="device-detail">
      <div class="left">
        <!--
        <div class="check-date">
          <div class="lable-title"><span>*</span>送检时间</div>
          <div class="lable">
            <el-date-picker
              v-model="requestData.submitDate"
              type="date"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd"
            />
          </div>
        </div>
        <div class="check-factory">
          <div class="lable-title"><span>*</span>送检厂家</div>
          <div class="lable">
            <el-input
              v-model="requestData.vendorName"
              placeholder="请输入送检厂家"
              clearable
              maxlength="32"
            />
          </div>
        </div>
        <div class="device-model">
          <div class="lable-title"><span>*</span>设备型号</div>
          <div class="lable">
            <el-input
              v-model="requestData.modelName"
              placeholder="请输入设备型号"
              clearable
              maxlength="32"
            />
          </div>
        </div>
        <div class="device-productionDate">
          <div class="lable-title"><span>*</span>出厂日期</div>
          <div class="lable">
            <el-date-picker
              v-model="requestData.reportDate"
              type="date"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd"
            />
          </div>
        </div>
        <div class="protocol-value">
          <div class="lable-title"><span>*</span>设备类型</div>
          <div class="lable">
            <el-select v-model="requestData.productType" filterable placeholder="请选择">
              <el-option
                v-for="item in options.deviceProtocolOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>-->
      </div>
      <div class="right">
        <div v-if="requestData.productType=='MODBUS_RTU'" class="device-com">
          <div class="lable-title">串口</div>
          <div class="lable">
            <el-select v-model="requestData.devName" filterable placeholder="请选择串口">
              <el-option
                v-for="item in options.deviceComOptions"
                :key="item.id"
                :label="item.id"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_RTU'" class="device-baud">
          <div class="lable-title">波特率</div>
          <div class="lable">
            <el-select v-model="requestData.baudRate" filterable placeholder="请选择波特率">
              <el-option
                v-for="item in options.deviceBaudOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_RTU'" class="device-checkbit">
          <div class="lable-title">校验位</div>
          <div class="lable">
            <el-select v-model="requestData.parity" filterable placeholder="请选择校验位">
              <el-option
                v-for="item in options.deviceCheckbitOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="requestData.productType=='MQTT'" class="device-model">
          <div class="lable-title">订阅主题</div>
          <div class="lable">
            <el-input
              v-model="requestData.topic"
              placeholder="请输入订阅主题"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='MQTT'" class="device-model">
          <div class="lable-title">用户名</div>
          <div class="lable">
            <el-input
              v-model="requestData.username"
              placeholder="请输入用户名"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='MQTT'" class="device-model">
          <div class="lable-title">密码</div>
          <div class="lable">
            <el-input
              v-model="requestData.password"
              placeholder="请输入密码"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_TCP' || requestData.productType=='IEC104' || requestData.productType=='MQTT'" class="device-ip">
          <div class="lable-title">IP</div>
          <div class="lable">
            <el-input
              v-model="requestData.ipAddr"
              placeholder="请输入IP"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_TCP' || requestData.productType=='IEC104' || requestData.productType=='MQTT'" class="device-port">
          <div class="lable-title">端口</div>
          <div class="lable">
            <el-input-number v-model="requestData.ipPort" controls-position="right" :min="1" :max="65535" @change.native="dpvChange" />
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_RTU'" class="device-databit">
          <div class="lable-title">数据位</div>
          <div class="lable">
            <el-select v-model="requestData.dataBits" filterable placeholder="请选择数据位">
              <el-option
                v-for="item in options.deviceDatabitOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="requestData.productType=='MODBUS_RTU'" class="device-stopbit">
          <div class="lable-title">停止位</div>
          <div class="lable">
            <el-select v-model="requestData.stopBits" filterable placeholder="请选择停止位">
              <el-option
                v-for="item in options.deviceStopbitOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="requestData.productType=='LOW_POWER'" class="device-model">
          <div class="lable-title">eid</div>
          <div class="lable">
            <el-input
              v-model="requestData.eid"
              placeholder="请输入eid"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='LOW_POWER'" class="device-model">
          <div class="lable-title">设备类型</div>
          <div class="lable">
            <el-radio-group v-model="requestData.equip_type" @change="$forceUpdate()">
              <el-radio :label="0" border>微功耗</el-radio>
              <el-radio :label="2" border>低功耗</el-radio>
            </el-radio-group>

            <!-- <el-input
              v-model="requestData.equip_type"
              placeholder="请输入设备类型：0为微功耗，2为低功耗。"
              clearable
            /> -->
          </div>
        </div>
        <div v-if="requestData.productType=='LOW_POWER'" class="device-model">
          <div class="lable-title">设备频点</div>
          <div class="lable">
            <el-input
              v-model="requestData.fre_point"
              placeholder="请输入 设备频点"
              clearable
            />
          </div>
        </div>
        <div v-if="requestData.productType=='LOW_POWER'" class="device-model">
          <div class="lable-title">上报周期</div>
          <div class="lable">
            <el-input
              v-model="requestData.business_cycle"
              placeholder="请输入 上报周期"
              clearable
            />
          </div>
        </div>
      </div>
    </div>
    <!--
    <div v-if="loadPictures==3" class="photo-list">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="device-frontphoto">
            <div class="lable-title"><span>*</span>设备正面照</div>
            <div class="lable">
              <upload-photo :key="'photo1-'+photoUpdateKey[1]" :photo-info="{ name: '1', url: deviceDefaultPictures['p1'],size:deviceDefaultSize['p1'] }" @photoChanged="savePhotoData" @delphoto="delphoto" @photoRemoved="removePicture" />
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="device-backphoto">
            <div class="lable-title"><span>*</span>设备反面照</div>
            <div class="lable">
              <upload-photo :key="'photo2-'+photoUpdateKey[2]" :photo-info="{ name: '2', url: deviceDefaultPictures['p2'],size:deviceDefaultSize['p2'] }" @delphoto="delphoto" @photoChanged="savePhotoData" @photoRemoved="removePicture" />
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="device-plate">
            <div class="lable-title"><span>*</span>设备铭牌</div>
            <div class="lable">
              <upload-photo :key="'photo3-'+photoUpdateKey[3]" :photo-info="{ name: '3', url: deviceDefaultPictures['p3'],size:deviceDefaultSize['p3'] }" @delphoto="delphoto" @photoChanged="savePhotoData" @photoRemoved="removePicture" />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-else class="photo-list">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="device-frontphoto">
            <div class="lable-title">设备正面照</div>
            <div class="lable">
              加载中...
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="device-backphoto">
            <div class="lable-title">设备反面照</div>
            <div class="lable">
              加载中...
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="device-plate">
            <div class="lable-title">设备铭牌</div>
            <div class="lable">
              加载中...
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    -->
    <!-- 底部按钮 -->
    <div class="bottom-button">
      <div class="cancel-device">
        <el-button class="light-button" @click="cancelAct">取消</el-button>
      </div>
      <div class="save-device">
        <el-button class="dark-button" @click="submitDeviceConfig()">下一步</el-button>
      </div>
      <div class="save-device save-btn">
        <!-- <el-button class="dark-button " @click="submitDeviceConfig(true)">保存</el-button> -->
      </div>
    </div>
  </div>
</template>

<script>
import { saveDeviceConfig, getDevicePicture, postPicture } from '@/api/device'
import { httpGet } from '@/api/common-action'
// import router from '@/router'
export default {
  components: { },
  props: {
    className: {
      type: String,
      default: 'steps-bar-default'
    },
    currentStep: {
      type: Number,
      default: 1
    },
    currentDeviceId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      requestData: {},
      // 默认选项
      options: {
        deviceComOptions: [],
        deviceProtocolOptions: [],
        deviceBaudOptions: [],
        deviceCheckbitOptions: [],
        deviceStopbitOptions: [],
        deviceDatabitOptions: []
      },
      deviceCheckId: 0,
      // 设备照片上传暂存文件
      devicePictureUploads: [],
      // 获取默认图片
      deviceDefaultPictures: {},
      // 照片加载状态 true 加载完毕 false 加载中
      loadPictures: 0,
      photoUpdateKey: [0, 0, 0],
      deviceDefaultSize: [],
      // 需要删除的图片编号数组
      delPhotoArr: []
    }
  },
  computed: {
    // LOW_POWER MODBUS_RTU MODBUS_RTU IEC104 MQTT
  },
  mounted() {
    this.$nextTick(() => {
      // 网页加载完成后执行
      // 获取当前 检测设备id
      this.deviceCheckId = this.$route.query.deviceCheckId || 0
      // console.log('this.deviceCheckId=', this.deviceCheckId)
      // 获取选项
      this.options.deviceProtocolOptions = JSON.parse(localStorage.getItem('dictDeviceProductType'))
      // 获取默认值

      this.options.deviceBaudOptions = JSON.parse(localStorage.getItem('deviceBaudOptions'))
      this.options.deviceCheckbitOptions = JSON.parse(localStorage.getItem('deviceCheckbitOptions'))
      this.options.deviceStopbitOptions = JSON.parse(localStorage.getItem('deviceStopbitOptions'))
      this.options.deviceDatabitOptions = JSON.parse(localStorage.getItem('deviceDatabitOptions'))
      this.initFunctions()
      // console.log('this.options.deviceDatabitOptions=', this.options.deviceDatabitOptions)
    })
  },
  methods: {
    // 初始化
    async initFunctions() {
      //
      // swagger 上面 获取串口选项 /dict/serial/options
      httpGet('/dict/serial/options').then(response => {
        this.requestData.deviceComOptions = response
        // console.log('getOptions /channel/serials response=', response)
      }).catch(err => {
        console.log('获取串口选项 httpGet err rs=', err)
        this.$message({
          message: '获取选项失败',
          type: 'error',
          offset: window.screen.height / 3
        })
      })
      // console.log('默认协议 this.deviceProtocolOptions=', this.requestData.deviceProtocolOptions)

      // 如果 当前设备 id 有值 ，则根据设备id获取设备基本信息
      if (this.deviceCheckId > 0) {
        // 查看检测设备 接口 /test/project/:project
        httpGet(`/test/project/${this.deviceCheckId}`).then(response => {
          this.requestData = response
          this.requestData.equip_type = 0
          // console.log('查看检测设备 this.requestData=', this.requestData)
          // 获取默认图片
          for (let index = 1; index <= 3; index++) {
            getDevicePicture(this.deviceCheckId, index).then(res => {
              // console.log('getDevicePicture res=', res.size)
              // 正面照
              const myBlob = new window.Blob([res], { type: 'image/png' })
              const imgUrl = window.URL.createObjectURL(myBlob)
              this.deviceDefaultSize['p' + index] = res.size
              if (res.size !== 0) {
                this.deviceDefaultPictures['p' + index] = imgUrl
              }
              // console.log('getDevicePicture loadPictures=', loadPictures)
              // console.log('getDevicePicture index=', index)
              this.$forceUpdate()
            }).finally(
              () => {
                // 此处 this.loadPictures 仅用于判断 照片组件是否显示
                // 所以只要请求了一次就 +1
                this.loadPictures = this.loadPictures + 1
              }
            )
          }
        })
      } else {
        this.loadPictures = 3
        if (this.options.deviceProtocolOptions.length > 0) {
          this.requestData.productType = this.options.deviceProtocolOptions[1].id
          this.requestData.ipAddr = '127.0.0.1'
          this.requestData.ipPort = '12701'
        }
      }
    },
    // 端口改变
    dpvChange(oldV, newV) {
      if (newV < 1) {
        this.requestData.devicePortValue = oldV
      } else if (newV > 65535) {
        this.requestData.devicePortValue = oldV
      }
    },
    // 暂存图片数据
    savePhotoData(file, photoName) {
      // #TODO：这里这两个变量可以合成一个，以后再搞
      this.devicePictureUploads[photoName] = file
      this.deviceDefaultPictures['p' + photoName] = file.url
    },

    // 删除照片
    removePicture(photoName) {
      delete this.deviceDefaultPictures['p' + photoName]
      this.delPhotoArr.push(photoName)
      // console.log('thisdeviceDefaultPictures', this.deviceDefaultPictures)
      this.photoUpdateKey[photoName] = new Date().getTime()
      this.$forceUpdate()
    },
    // 删除未保存图片
    delphoto(photoName) {
      delete this.deviceDefaultPictures['p' + photoName]
      // console.log('thisdeviceDefaultPictures', this.deviceDefaultPictures)
    },
    // 取消
    cancelAct() {
      this.$router.push({ path: '/device/index' })
    },

    // 提交设备基本信息
    submitDeviceConfig() {
      if (
        this.isNull(this.requestData.serialNumber, '请输入设备编号')
      ) {
        // 如果有任何一个值为空，则直接返回，不提交数据
        return
      }
      const deviceSubmitData = this.clearSubmitData(this.requestData)
      // console.log('submitDeviceConfig deviceSubmitData = ', deviceSubmitData)
      deviceSubmitData.id = this.currentDeviceId || null
      deviceSubmitData.devName = this.devName || '/dev/ttyUSB0'
      // 参数合法，数据提交到后端，到下一步
      saveDeviceConfig(deviceSubmitData).then(response => {
        this.$emit('changeDeviceId', response.id * 1)
        // 到下一步
        let currentStep = this.currentStep
        if (currentStep < 2) {
          currentStep = currentStep + 1
          this.$emit('changeStep', currentStep)
        } else {
        // 已经是最后一步了
          this.$message({
            message: '已经是最后一步了',
            type: 'error',
            offset: window.screen.height / 3
          })
        }
      })
    },
    // 提交照片
    submitPhoto(picFile, photoName, deviceCheckId) {
      const formData = new FormData()
      formData.append('file', picFile.raw)
      // console.log('formData=', formData)
      // 上传新图片
      postPicture(deviceCheckId, photoName, formData).then(response => {
        // console.log('postPicture response=', response)
        // console.log('上传了photo', photoName)
      }).catch((e) => {
        // console.log('e', e)
      })
    },
    // 清理多余数据参数，避免提交时报错
    clearSubmitData(data) {
      if (data.code) {
        delete data.code
      }
      // if (data.code) {
      //  delete data.code
      // }
      return data
    },
    // 检查必填项 是否为空
    isNull(val, msg) {
      msg = msg || '请输入必填项'
      if (!val) {
        this.$message({
          message: msg,
          type: 'error',
          offset: window.screen.height / 3
        })
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input{
  width: 100%;
}
.device-config {
  // border: 1px #f00 solid;
  text-align: center;
  font-size: 16px;
  width: 50%;
  margin: 0 auto;
  .device-detail {
    display: flex;
    .left, .right {
      width: 50%;
    }
    .left {
      padding-right: 20px;
      .protocol-value {
        // 隐藏设备类型输入框
        // 聊天记录关键词：好的，我先用css控制隐藏了
        display: none;
      }
    }
    .right {
      padding-left: 20px;
      // 隐藏设备类型输入框
      // 聊天记录关键词：好的，我先用css控制隐藏了
      display: none;
    }
  }
  .form-title {
    font-size: 20px;
    font-weight: bold;
  }
  .form-sub-title {
    font-size: 14px;
    padding-top: 4px;
    padding-bottom: 20px;
  }
  .form-sub-title,span {
    color: #FF5732;
  }
  .lable-title {
    text-align: left;
    padding-bottom: 10px;
    color: #707070;
  }
  .lable {
    padding-bottom: 20px;
    text-align: left;
    .el-select {
      width: 100%;
    }
  }
  // 底部按钮
  .bottom-button {
    display: flex;
    justify-content: center;
    padding-bottom: 20px;
    .cancel-device {
      padding-right: 20px;
    }
    .save-btn{
      padding-left: 20px;
    }
  }
  // 按钮公用样式
  .dark-button {
      background-color: #00706B;
      border: 1px #00706B solid;
      color: #fff;
    }
  .light-button {
    color: #00706B;
    border: 1px #00706B solid;
  }
}
</style>
