<template>
  <div class="auto">
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户ID.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_userinfoid" class="font text-left">用户编号:</label>
      </div>
      <div class="col-xs-8" >
        <input id="f_userinfoid" class="search_input input-font" readonly
               v-model=row.f_userinfo_code :value.sync="row.f_userinfo_code" />
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户姓名.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label  class="font text-left">用户姓名:</label>
      </div>
      <div class="col-xs-8" >
        <input  class="search_input input-font" v-model=row.f_user_name :value.sync="row.f_user_name" readonly />
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/小区.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">用户地址:</label>
      </div>
      <div class="col-xs-8" >
        <input class="search_input input-font" v-model=row.f_address :value.sync="row.f_address" readonly />
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户ID.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label  class="font text-left">铅封编号:</label>
      </div>
      <div class="col-xs-5" >
        <input class="search_input input-font"
               v-model=sealUID :value.sync="sealUID" readonly  />
      </div>
      <div class="col-xs-3">
        <button style="padding: 5px" type="button" class="btn btn-font btn-color" @click="scan()">NFC识别</button>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户ID.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label  class="font text-left">二维码编号:</label>
      </div>
      <div class="col-xs-5" >
        <input class="search_input input-font"
               v-model=f_qr_code :value.sync="f_qr_code" readonly  />
      </div>
      <div class="col-xs-3">
        <button style="padding: 5px" type="button" class="btn btn-font btn-color" @click="codeScan()">扫描二维码</button>
      </div>
    </div>
    <div class="row app-row">
      <div class="form-group col-sm-12 col-xs-12 col-md-12 "  :class="style__">
        <label class="text-left font">铅封照片:</label>

        <div class="auto" :class="style__">
          <div class="panel" style="padding: 10px 10px 5px 10px;">
            <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
              <div class="row" style="height: 240px;overflow: scroll;top: 1px" >
                <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 35px" v-for="(index,img) in imgs">
                  <img-self :src="img" alt="铅封照片" :width="140" :height="170"></img-self>
                  <img src="../../assets/删除.png" @click="delfile(img,index)" style="width: 15px;margin-top: -80px" alt="">
                </div>
              </div>
              <div class="row text-right div-photo">
                <button type="button" name="button" class="btn btn-photo" @click="takePic()">拍照</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/小区.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">施封原因:</label>
      </div>
      <div class="col-xs-8" >
        <v-select
          v-model="cause"
          :value.sync="cause"
          :value-single="true"
          :options='causeOption'
          placeholder='请选择施封原因'
          width="100%"
          close-on-select></v-select>
      </div>
    </div>
    <div class="row text-center" style="margin-top: 40px;">
      <button style="font-size: 20px; padding: 8px 40px"  type="button" name="button" class="col-sm-3 btn btn-primary"  @click="bind">
        施封
      </button>
    </div>
  </div>
</template>

<script>
import {HttpResetClass, PagedList} from 'vue-client'
import Vue from 'vue'
import * as Util from '../Util'

export default {
  title: '施封',
  props: ['row'],
  data () {
    return {
      sealUID: '',
      imgs: [],
      cause: '',
      address: '',
      longitude: '',
      latitude: '',
      f_qr_code: '',
      causeOption: this.$appdata.getParam('施封原因')
    }
  },
  ready () {
    console.log('this.row=', JSON.stringify(this.row))
    this.getLocation()
    if (this.longitude == 0){
      this.timer = window.setInterval(this.getLocation, 3000)
    }
  },
  computed: {

  },
  methods:{
    codeScan() {
      console.log('codeScan=========')
      HostApp.__this__ = this
      HostApp.scanQRCode({callback:"javascript:HostApp.__this__.codeScanCallback()"})
    },
    codeScanCallback() {
      console.log('codeScanCallback=========')
      let result = HostApp.getQRCode()
      console.log('result=', result)
      if (result.code == 200){
        // 判断result.data是否包含等号。如果有，只要等号后面的内容
        if (result.data.indexOf('=') > 0) {
          this.f_qr_code = result.data.substring(result.data.indexOf('=') + 1)
        }else{
          this.f_qr_code = result.data
        }
      }else {
        this.$showMessage("未识别到二维码信息，请重新尝试！")
      }
    },
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    getLocation() {
      const location = HostApp.getDetailAddress()
      this.address = location.data
      const longitude = HostApp.getPreference('longitude')
      this.longitude = longitude.data
      const latitude = HostApp.getPreference('latitude')
      this.latitude = latitude.data
      if (this.longitude != 0){
        window.clearInterval(this.timer)
      }
      console.log('this.address=', this.address)
      console.log('this.longitude=', this.longitude)
      console.log('this.latitude=', this.latitude)
    },
    bind() {
      if (!this.sealUID) {
        this.$showMessage("铅封编号不能为空！")
        return
      }
      if (!this.f_qr_code) {
        this.$showMessage("二维码编号不能为空！")
        return
      }
      if (!this.imgs.length) {
        this.$showMessage("请拍摄铅封照片！")
        return
      }
      if (!this.cause) {
        this.$showMessage("请选择施封原因！")
        return
      }
      //this.getLocation()
      // if (this.longitude == 0){
      //   this.$showMessage("位置获取失败，未开启定位或者网络信号弱未获取到定位！")
      //   return
      // }
      const param = {
        seal: {
          f_uid: this.sealUID,
          f_qr_code: this.f_qr_code,
          f_userinfo_code: this.row.f_userinfo_code,
          f_userinfo_id: this.row.f_userinfo_id,
          f_filiale: this.row.f_filiale,
          f_filiale_id: this.row.f_filiale_id,
          f_user_id: this.row.f_user_id,
          f_address: this.address,
          f_longitude: this.longitude,
          f_latitude: this.latitude,
          f_operate_name: Vue.user.name,
          f_operate_id: Vue.user.id,
          f_operate_date: Util.toStandardTimeString(),
          f_state: '有效'
        },
        operateList: {
          f_cause: this.cause,
          f_operate_date: Util.toStandardTimeString(),
          f_creation_date: Util.toStandardTimeString(),
          f_creation_name: Vue.user.name,
          f_creation_name_id: Vue.user.id
        },
        files: [],
        imgs: [],
        f_devices_no: this.generateUUID()
      }
      for (const img of this.imgs) {
        const i1 = img.lastIndexOf('?')
        const i2 = img.lastIndexOf('/')
        const key = img.substring(i2+1, i1)
        const filename = img.substring(0, i1)
        param.files.push({
          f_img_url: key,
          f_operate_date: Util.toStandardTimeString(),
          f_operator: Vue.user.name,
          f_operatorid: Vue.user.id
        })
        param.imgs.push({
          key: key,
          filename: filename
        })
      }
      //tag)
      let paramStr = JSON.stringify(param)
      console.log('paramStr=', paramStr)
      // 多长截断一次
      let subLength = 800
      for (let i = 0; i < paramStr.length; i += subLength) {
        HostApp.param_cache(paramStr.substr(i, subLength))
      }
      HostApp.__this__ = this
      HostApp.syncLogic({
        'logic': 'sealBind',
        'callback': 'javascript:HostApp.__this__.sealBindBack()',
        'backresult': 1
      })
    },
    sealBindBack(jo) {
      if(jo.state == 'ok') {
        let res = JSON.parse(jo.result)
        if (res.code == 200 && res.data.code == 200) {
          this.$showMessage('施封成功！')
          this.$back(this.sealUID)
          return
        }
        if(res.msg){
          this.$showMessage(res.msg)
        }else{
          this.$showMessage(res.data.msg)
        }
        return
      }
      this.$showMessage('网络异常！')
    },
    scan() {
      HostApp.__this__ = this
      HostApp.readNfc({
        'callback': 'javascript:HostApp.__this__.scanCallback()',
        // 固定key，代表是否将logic执行结果作为参数传入回调方法，1代表true，0代表false，
        // 执行回调方法传入key为backresult
        // 如需额外拼接参数，写在logic返回值的params，例如xxlogic返回:{"params": "success"}
        'backresult': 1
      })
    },
    scanCallback() {
      console.log('scanCallback=========')
      const result = HostApp.getNfcUUID()
      console.log('result=', result)
      if (result.code == 200){
        this.sealUID = result.data
      }else {
        this.$showMessage("未识别到铅封信息，请重新尝试！")
        return
      }
    },
    takePic() {
      HostApp.__callback__ = this.cameraCallBack
      HostApp.__this__ = this

      let fileName = `${Util.guid()}.jpg`
      HostApp._open_a_page({
        type: 'boomerang',
        page: 'com.aofeng.hybrid.android.peripheral.CameraActivity',
        param: {
          file: fileName,
          requestCode: 111,
          callback: 'javascript:HostApp.__callback__("%s");',
          watermark: '铅封照片\t时间：' + Util.toStandardTimeString() + '\t' + Vue.user.name + '\t' + this.row.f_userinfo_id+ '\t' + this.row.f_user_name+ '\t' + this.row.f_address
        }
      })
    },
    cameraCallBack(fileName) {
      // if (prop == 'f_overall_path') {
      //   let f_overall_path = fileName + '?' + Math.random()
      //   HostApp.__this__.paper.f_overall_imgs.push({
      //     f_overall_path: f_overall_path
      //   })
      // } else {
      //   HostApp.__this__.paper[prop] = fileName + '?' + Math.random()
      // }
      this.imgs.push(fileName + '?' + Math.random())
      HostApp.__callback__ = null
      HostApp.__this__ = null
    },
    delfile(fileName, index) {
      if (fileName == Vue.nopic)
        return
      else {
        this.imgs.splice(index, 1)
        HostApp.delfile(fileName)
      }
    }
  }
}
</script>
<style scoped>
.app-row {
  background-color: white;
  padding: 10px 10px 0 10px;
  border-bottom: 1px solid rgba(235, 235, 235, 0.5);
}
.search_input {
  border: 0;
  outline: none;
}
.font{
  font: 15px PingFang-SC-Medium;
  color: #666666;
}
.input-font{
  font: 15px PingFang-SC-Medium;
  color: #333333;
}
.btn-font{
  font:600 16px PingFang-SC-Bold;
  color: #499EDF;
}
.btn-color{
  background-color: #FFFFFF;
  border-radius: 10px ;
  border: 1px solid #499EDF;
}
.app-text {
  font-size: 12px;
}
.panel-self{
  border-radius: 10px;
  border:1px solid #499EDF;
  background-color: #F8F8F8;
}
.yybtn-color{
  border-radius: 4px ;
  border: 1px solid #499EDF;
}
.qxbtn-color{
  background-color: #FFFFFF;
  border-radius: 4px ;
  border: 1px solid #499EDF;
}
.btn-photo{
  border: 0;
  border-radius: 7px;
  background-color: #7dc1f4;
  font: 15px PingFang-SC-Bold;
  height: 20%;
}
.div-photo{
  width: auto;
  height: auto;
  /* margin-top: 10px; */
  position: absolute;
  bottom: 10px;
  right: 10px;
}
</style>
