<style scoped>
  .divmask {
    pointer-events: none;
  }
  .app-header {
    border-radius: 50%;
    background: rgba(73, 158, 223, 0.4);
    color: #FFF;
    padding: 20px;
    text-align: center;
    font-size: 1.2em;
    z-index: 10;
    opacity:0.5;
    bottom: 50px;
    margin-top: -20px;
    position: absolute;
    top: 10%;
    right: 2%;
    height: 8%;
  }
</style>

<template>
  <div style="overflow-y: scroll;background-color: #FFFFFF">
    <div class="auto" style="height:auto;" id="safecheck" v-if="isshow">
      <div class="page-header app-header auto">
        <div @click="back()">
          <img src="../../assets/back.png"/>
        </div>
      </div>
      <div style="width: 50%;height: 462px; margin-left: 20px;margin-top: 0px;margin-bottom: 20px;float:left" id="one">
        <paper-userm></paper-userm>
      </div>
      <div style="width: 45%;height: 462px; margin-left: 20px;margin-top: 0px;margin-bottom: 20px;float:left">
        <paper-statem></paper-statem>
      </div>
      <div style="width: 95%;height: auto;margin-left: 20px;margin-bottom: 30px;float: left">
        <devicesm> </devicesm>
      </div>
      <div style="width: 95%;height: 900px;margin-left: 20px;float: left;">
        <paper-feedbackm v-bind:paper="this.data" ></paper-feedbackm>
      </div>
    </div>
  </div>
</template>

<script>
  import PaperUserm from './PaperUserm'
  import PaperStatem from './PaperStatem'
  import Devicesm from './Devicesm'
  import PaperFeedbackm from './PaperFeedbackm'
  import RadioGroup from 'vue-client/src/vue-strap/src/radioGroup'
  import Radio from 'vue-client/src/vue-strap/src/radioBtn'
  import Vue from 'vue'
  import * as Util from '../Util'

  export default {
    title: '安检单',
    props: ['f_plan_id', 'item', 'role'],
    data() {
      return {
        data: {
          f_devices: [],
          f_defect_content:''
        },
        isshow:false,
        isUpload:false,
        livedispose:'',
        startClick:false, //开始安检按钮是否可点击
        isStrat: false, //是否开始安检
        checkResult:{},//查询结果
        newcheckResult:{},
        timer: null,
        showModal: false,
        pic_to_be_viewed: '',
        showBack:true,
        devices: [],
        f_devices : [],
        isToRepair:false,
        isSafeCheckToRepair:false,//是否转维修
        config: {
          "燃气表":{
            "checkmust":true,
            "index":1,
            "items":{
              //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
              "基表编号":{"index":1,"type":"string","readonly":true},
              "气表型号":{"index":2,"type":"string","readonly":true},
              "气表品牌":{"index":3,"type":"string","readonly":true},
              "进气方向":{"index":4,"type":"string","readonly":true},
              // "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
              "上期表读数":{"index":5,"type":"number","readonly":true,isshow:false},
              "累购气量":{"index":6,"type":"number","readonly":true},
              "累购金额":{"index":6,"type":"number","readonly":true},
              "已用气量":{"index":7,"type":"number","checkmust": true},//基表数
              "已用金额":{"index":7,"type":"number","checkmust": true},
              "剩余气量":{"index":8,"type":"number","checkmust": true},//累购-已用
              //显示屏数  --实际剩余气量
              "剩余金额":{"index":8,"type":"number","checkmust": true},
              "气量异常差值":{"index":9,"type":"number","readonly": true},
              "金额异常差值":{"index":9,"type":"number","readonly": true}
            }
            // 注意，配置项的index必须与上面的固定配置保持'顺序'
          },
        },
      }
    },
    components: {
      RadioGroup,
      Radio,
      "paper-userm":PaperUserm,
      "paper-statem":PaperStatem,
      "devicesm":Devicesm,
      "paper-feedbackm":PaperFeedbackm
    },
    computed: {
      selector: {
        get() {
          return 'paper-state'
        },
        set(val) {
          if(this.isStrat){
            debugger;
            this.$goto(val, {userinfo:this.data}, 'paper-router')
          }else{
            this.$showMessage('未开始安检！')
          }
        }
      },
      actionEnabled: {
        get() {
          return this.role == 'inspect'
        }
      }
    },
    methods: {
      back(){
        if (this.role == 'inspect') {
          if(!this.isStrat){
            this.$back()
            return
          }else{
            this.savePaper(true).then(()=>{
              this.$back()
              this.isStrat = false
            })
          }
        }else{
          this.$back()
        }
      },
      checkIsStart(){
        alert('asdad')
        return
      },

      viewPic(fileName) {
        console.log('view pic: ' + fileName)
        if(this.role == 'view') {
          if(!fileName.endsWith('nopic.png')) {
            this.pic_to_be_viewed = fileName
            this.showModal = true
          }
        } else {
          HostApp.viewPic(fileName)
        }
      },
      tick() {
        this.timer = null
        this.data.f_offsite_time = Util.toStandardTimeString()
        this.timer = window.setTimeout(this.tick, 1000)
      },
      getRepairState() {
        let repaired = true
        this.data.f_defects.forEach((defect) => {
          repaired = repaired & (defect.f_ratification == '已处理')
        })
        return repaired
      },
      verifyRepairDefects() {
        this.data.f_repair_date = Util.toStandardTimeString()
        this.data.f_repaired = this.getRepairState() ? '已修' : '在修'
      },
      initconfig() {
        if(this.item.f_collection_type=='按金额'){
         this.config= {
            "燃气表":{
              "checkmust":true,
                "index":1,
                "items":{
                //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
                "基表编号":{"index":1,"type":"string","readonly":true},
                "气表型号":{"index":2,"type":"string","readonly":true},
                "气表品牌":{"index":3,"type":"string","readonly":true},
                "进气方向":{"index":4,"type":"string","readonly":true},
                // "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
                "上期表读数":{"index":5,"type":"number","readonly":true,isshow:false},
                "累购金额":{"index":6,"type":"number","readonly":true},
                "已用金额":{"index":7,"type":"number","checkmust": true},
                //显示屏数  --实际剩余气量
                "剩余金额":{"index":8,"type":"number","checkmust": true},
                "金额异常差值":{"index":9,"type":"number","readonly": true}
              }
              // 注意，配置项的index必须与上面的固定配置保持'顺序'
            },
          }
        }else{
          this.config= {
            "燃气表":{
              "checkmust":true,
                "index":1,
                "items":{
                //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
                "基表编号":{"index":1,"type":"string","readonly":true},
                "气表型号":{"index":2,"type":"string","readonly":true},
                "气表品牌":{"index":3,"type":"string","readonly":true},
                "进气方向":{"index":4,"type":"string","readonly":true},
                // "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
                "上期表读数":{"index":5,"type":"number","readonly":true,isshow:false},
                "累购气量":{"index":6,"type":"number","readonly":true},

                "已用气量":{"index":7,"type":"number","checkmust": true},//基表数
                "剩余气量":{"index":8,"type":"number","checkmust": true},//累购-已用
                //显示屏数  --实际剩余气量
                "气量异常差值":{"index":9,"type":"number","readonly": true},
              }
              // 注意，配置项的index必须与上面的固定配置保持'顺序'
            },
          }
        }
      },
      async savePaper(saveOnly) {
        console.log('savePaper-->isUpload'+this.isUpload)
        console.log('保存')
        if(this.role == 'repair') {
          let errorMsg = this.verifyRepairDefects()
          if(errorMsg) {
            this.$showMessage(errorMsg)
            return false
          }
          return this.save()
        } else {
          //保存时做校验
          let errString = this.errorVerify()
          if(saveOnly){
            if (errString) {
              this.data.f_complete = '未完成'
              this.disableTimer()
              return this.save()
            } else {
              console.log('赋值前',this.data)
              if(!this.data.f_offsite_time){
                this.$set('data.f_offsite_time', Util.toStandardTimeString())
              }
              console.log('赋值后',this.data)
              this.data.f_complete = '已完成'
              this.disableTimer()
              return this.save()
            }
          }else {
            console.log('errString-->isUpload'+this.isUpload)
            if (errString) {
              console.log(errString)
              console.log('Vue.android',Vue.android)
              console.log('this.isUpload',this.isUpload)
              if (Vue.android){
                // if(this.isUpload){
                //   this.isUpload = false
                // }
                this.$showMessage(errString)
              }
              return false
            } else {
              if(!this.data.f_offsite_time){
                this.$set('data.f_offsite_time', Util.toStandardTimeString())
              }
              console.log('赋值后',this.data)
              this.data.f_complete = '已完成'
              this.disableTimer()
              return this.uploadCheckPaper()
            }
          }
        }
      },
      genuineSave(saveOnly) {
        HostApp.__this__.save(saveOnly)
        if(!saveOnly)
          HostApp.__this__.disableTimer()
        HostApp.__callback__ = null
        HostApp.__this__ = null
      },
      uploadPaper() {
        // this.isUpload = true
        console.log('uploadPaper-->isUpload'+this.isUpload)
        this.savePaper(false).then((res) => {
          console.log(`res=${res}`)
          // console.log(`改变前this.isUpload=${this.isUpload}`)
          // this.isUpload = false
          // console.log(`改变后this.isUpload=${this.isUpload}`)
          if(res != true){
            console.log('失败')
            return
          }else{
            this.$back()
          }
        })
      },
      errorVerify() {
        let hasError = this.verifyState()
        if(hasError)
          return hasError

        if(this.data.f_entry_status != '入户')
          return null
        hasError = this.verifyUser()
        if(hasError)
          return hasError
        hasError = this.verifyDevices()
        if(hasError)
          return hasError
        hasError = this.verifyFeedback()
        if(hasError)
          return hasError
      },
      verifyState() {
        if(Vue.android && this.data.f_entry_status == '未使用天然气' && this.data.f_nongasuser_path == Vue.nopic)
          return '未使用天然气则必须拍照'
        if(Vue.android && this.data.f_entry_status == '到访不遇' && this.data.f_noanswer_path == Vue.nopic)
          return  '到访不遇必须拍照'
      },
      verifyUser() {
        let prefix = '用户基本信息：'
        if(Util.required(this.data.f_user_name))
          return prefix + '用户名必须输入'
        if(Util.required(this.data.f_user_phone))
          return prefix + '用户电话必须输入'
        // if(Util.required(this.data.f_residential_area))
        //   return prefix + '小区名称必须输入'
        if(Util.required(this.data.f_address))
          return prefix + '地址必须输入'
      },
      verifyDevices() {
        for (let dev in this.config) {
          if (this.config[dev].checkmust == true) {
            let error = true
            for(let device in this.data) {
              if (device.startsWith("device")) {
                for (let item in this.data[device]) {
                  if (this.data[device].length != 0 && this.data[device][item].f_device_type == dev) {
                    error = false
                  }
                }
              }
            }
            if (error) {
              return "请检查" + dev
            }
          }
        }

        for (let dev in this.config) {
          for(let device in this.data) {
            if (device.startsWith("device")) {
              for (let item in this.data[device]) {
                //检查每一条安检结果
                if (this.data[device].length != 0 && this.data[device][item].f_device_type == dev) {
                  for (let i in this.data[device][item].f_items) {
                    for (let it in this.config[dev].items) {
                      if (this.config[dev].items[it].checkmust == true && this.data[device][item].f_items[i].f_item_value == '' && this.data[device][item].f_items[i].f_path == '' && it == this.data[device][item].f_items[i].f_item_name) {
                        return dev + (this.data[device].indexOf(this.data[device][item]) + 1) + this.data[device][item].f_items[i].f_item_name + "未检查"
                      }
                    }
                    //检查安检下拉结果
                    if (this.data[device][item].f_items[i].type == 'selector') {
                      if (this.data[device][item].f_items[i].f_is_defect == true && this.data[device][item].f_items[i].f_path == Vue.nopic) {
                        return dev + (this.data[device].indexOf(this.data[device][item]) + 1) + this.data[device][item].f_items[i].f_item_name + this.data[device][item].f_items[i].f_item_value + "选中必须拍照"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },


      verifyFeedback() {
        let prefix = '用户反馈：'
        if(Vue.android && (!this.data.f_overall_path || this.data.f_overall_path == Vue.nopic) && this.data.f_entry_status == '入户')
          return prefix + '必须有安检总体照片'
        if(Vue.android && this.data.f_defect_notified && this.data.f_notified_path == Vue.nopic)
          return prefix + '下发安检通知书则必须给通知书拍照'
        if(!this.data.f_client_evaluation && this.data.f_entry_status == '入户')
          return  prefix + '请选择服务评价'
      },

      setUrgency() {
        this.data.f_defect_urgency = 'Z'
        let that = this
        this.data.f_defects.forEach(function(defect) {
          if(that.data.f_defect_urgency > defect.f_defect_level.charAt(0))
            that.data.f_defect_urgency = defect.f_defect_level.charAt(0)
        })
        if(this.data.f_defect_urgency == 'Z')
          this.data.f_defect_urgency = null
      },

      getAllDefect(){
        let checkResults={
          result:'正常',
          data:[]
        }
        let value = ''
        let codata = JSON.parse(JSON.stringify(this.data))
        codata.f_devices = []
        this.f_devices = []
        for(let device in codata){
          let f_device_type
          if(device.startsWith("device")){
            for(let item in codata[device]) {
              if(codata[device].length > 1 ){
                let j = Number.parseInt(item)+1
                f_device_type = `${codata[device][item].f_device_type}${j}`
              }else{
                f_device_type = codata[device][item].f_device_type
              }
              // console.log('codata[device][item]=>',codata[device][item])
              for(let i in codata[device][item].f_items){
                let items = codata[device][item].f_items[i]
                console.log('items',items)
                console.log(items.f_is_defect)
                if(items.f_is_defect == true || items.f_is_defect == 'true'){
                  console.log('进入有隐患')
                  checkResults.result = '有隐患'
                  if(!this.checkResult.hasOwnProperty(items.f_defect_level)){
                    if(f_device_type.indexOf('其他') != -1){
                      this.$set('checkResult.' + items.f_defect_level,`${f_device_type}${items.f_item_name}`)
                    }else{
                      this.$set('checkResult.' + items.f_defect_level,`${f_device_type}${items.f_item_name}${items.f_item_value}`)
                    }
                  }else{
                    console.log('类型----',f_device_type)
                    if(f_device_type.indexOf('其他') != -1){
                      this.$set('checkResult.' + items.f_defect_level,`${this.checkResult[items.f_defect_level]},${f_device_type}${items.f_item_name}`)
                    }else{
                      this.$set('checkResult.' + items.f_defect_level,`${this.checkResult[items.f_defect_level]},${f_device_type}${items.f_item_name}${items.f_item_value}`)
                    }

                  }
                }
                if(items.type == 'selector'){
                  items.selected = ''
                }
              }
              console.log('checkResult',this.checkResult)
              this.f_devices.push(codata[device][item])
            }
          }
        }
        if(this.checkResult){
          for (let key in this.checkResult){
            console.log('key=>',key)
            this.$set('newcheckResult.'+key,this.checkResult[key])
            checkResults.data.push(this.newcheckResult)
            this.newcheckResult = {}
          }
          this.checkResult = {}
        }
        console.log(`typeof-checkResults-->${typeof checkResults}`)
        codata.f_defect_content = JSON.stringify(checkResults)
        console.log('checkResults',checkResults)
        return codata
      },

      getWeixin(backData){
        let result = {f_user_name:backData.f_user_name,checker: Vue.user.name, f_check_date: Util.toStandardDateString(),f_userinfo_id:backData.f_userinfoid,f_address:backData.f_address}

        let Resultstr = ''

        for (let dev in this.config) {
          for (let device in backData) {
            if (device.startsWith("device")) {
              for (let item in backData[device]) {
                //遍历结果
                if (backData[device].length != 0 && backData[device][item].f_device_type == dev) {
                  let error = true
                  let n = 0
                  let level = ''
                  for (let i in backData[device][item].f_items) {
                    if (backData[device][item].f_items[i].f_is_defect == true || backData[device][item].f_items[i].f_is_defect == 'true') {
                      error = false
                      n +=1
                      if(level == ''){
                        level = backData[device][item].f_items[i].f_defect_level
                      }
                      let le = backData[device][item].f_items[i].f_defect_level
                      if(le.startsWith('A')){
                        let i = parseInt(le.substring(1))
                        if(i<parseInt(le.substring(level))){
                          level = le
                        }
                      }else if (le.startsWith('B')){
                        let i = parseInt(le.substring(1))
                        if(i<parseInt(le.substring(level))){
                          level = le
                        }
                      }else if(le.startsWith('C')){
                        let i = parseInt(le.substring(1))
                        if(i<parseInt(le.substring(level))){
                          level = le
                        }
                      }
                    }
                  }
                  if (error) {
                    Resultstr += dev + (backData[device].indexOf(backData[device][item]) + 1) + ':正常;'
                  } else {
                    Resultstr += dev + (backData[device].indexOf(backData[device][item]) + 1) + ':有隐患;'
                  }
                  result['f_err_number'] = n
                  result['f_danger_lever'] = level
                }
              }
            }
          }
        }
        for (let dev in this.config) {
          for (let device in backData) {
            if (device.startsWith("device")) {
              for (let item in backData[device]) {
                if (backData[device].length != 0 && backData[device][item].f_device_type == dev) {
                  for (let i in backData[device][item].f_items) {
                    if (backData[device][item].f_items[i].f_is_defect == true || backData[device][item].f_items[i].f_is_defect == 'true') {
                      Resultstr += dev + (backData[device].indexOf(backData[device][item]) + 1)+ backData[device][item].f_items[i].f_item_name + ' ' + backData[device][item].f_items[i].f_item_value + ';'

                    }
                  }
                }
              }
            }
          }
        }


        return result
      },

      uploadCheckPaper(){
        console.log('uploadCheckPaper-->isUpload'+this.isUpload)
        //获取微信推送路径
        let url = ""
        if(Vue.config.safecheck != undefined) {
          if (Vue.config.safecheck.ApproveConfig != undefined) {
            if (Vue.config.safecheck.ApproveConfig.weixinurl != undefined) {
              url = Vue.config.safecheck.ApproveConfig.weixinurl
            }
          }
        }

        let res =  this.save()
        if(res) {
          let codata = this.getAllDefect()
          //获取微信推送内容
          let WxResult = this.getWeixin(codata)
          let haslivedispose = this.$androidUtil.bzLogic('getLiveDispose', {
            f_check_item_id: this.data.f_check_item_id
          })
          //如果是转维修上传，则不做校验，上传完成后自动转维修
          console.log('this.isToRepair=======》'+this.isToRepair)
          console.log('this.livedispose=======》'+this.livedispose)
          if(!this.isToRepair){
            if(haslivedispose.data.length > 0 && (this.livedispose == 'true' || this.livedispose == true)){
              console.log('是否已转维修')
              console.log(this.isSafeCheckToRepair)
              if(!this.isSafeCheckToRepair){
                this.$showMessage('有未处理的隐患，请前往拍照上传中将安检转为维修单！')
                return
              }
            }
          }
          console.log(`codata类型-->${typeof codata}`)
          for (let key in codata){
            if(key.startsWith("device")){
              codata[key] = []
            }
          }
          console.log(`codata内容-->${JSON.stringify(codata)}`)
          // HostApp.uploadPaper({f_check_item_id: this.data.f_check_item_id, f_checker_id: this.data.f_checker_id, data: this.data})
          try {
            let response = this.$androidUtil.bzLogic('上传安检信息', {
              f_check_item_id: this.data.f_check_item_id,
              f_checker_id: this.data.f_checker_id,
              row: codata
            })
            if (response.code == 200) {
              console.log('=============response.data==================')
              console.log(JSON.stringify(response.data))
              let f_paper_id
              if(response.data != '' && response.data != null){
                f_paper_id = JSON.parse(response.data).id
              }
              this.$set('data.f_paper_id', f_paper_id)
              console.log('=============f_paper_id==================')
              console.log(JSON.stringify(f_paper_id))
              console.log(this.data.f_paper_id)
              console.log("===data"+JSON.stringify(this.data))
              for (let device in this.data){
                console.log("上传设备信息device=======>"+device)
                console.log("上传设备信息device=======>"+JSON.stringify(this.data[device]))
                if(device.startsWith("device")){
                  for(let devices of this.data[device]) {
                    devices.f_paper_id = f_paper_id
                    let ret = this.$androidUtil.bzLogic('UpCheckPaperDevices', {
                      row: devices
                    })
                    console.log(`上传设备信息结果res======${JSON.stringify(ret.data)}`)
                    if(ret.code == 200){
                      console.log(`设备信息id======${ret.data.f_device_id}`)
                      devices.f_device_id = JSON.parse(ret.data.f_device_id).id
                    }
                    console.log('上传设备信息device======')
                    console.log(JSON.stringify(devices))
                    if (ret.code != 200) {
                      //TODO 失败后处理
                      // this.isUpload = false
                      this.$showMessage("上传失败!")
                      return false
                    }
                  }
                }
              }
              // for (let device of this.f_devices) {
              //   device.f_paper_id = f_paper_id
              //   console.log('上传设备信息device======')
              //   console.log(JSON.stringify(device))
              //   let ret = this.$androidUtil.bzLogic('UpCheckPaperDevices', {
              //     row: device
              //   })
              //   console.log(`上传设备信息结果res======${ret}`)
              //   if (ret.code != 200) {
              //     //TODO 失败后处理
              //     HostApp.alert("上传失败!")
              //     return false
              //   }
              // }
              let result = this.$androidUtil.bzLogic('FinishUpload',
                {
                  f_check_item_id: this.data.f_check_item_id,
                  f_userinfo_id: codata.f_userinfoid,
                  f_last_check_result: codata.f_defect_content
                })
              if(result.code == 200){
                // this.$showAlert('上传成功!', 'success', 2000)
                this.$showMessage('上传成功!')
                this.isStrat=false
                if(url != "" ){
                  this.$resetpost(`${url}`,{data:WxResult})
                }
                return true
              }else{
                // this.isUpload = false
                this.$showMessage("上传失败!")
                return false
              }
            }else{
              // this.isUpload = false
              this.$showMessage("上传失败!")
              return false
            }
          }catch (e) {
            console.log('上传失败==='+JSON.stringify(e))
            // this.isUpload = false
            this.$showMessage("上传失败!")
          }
        }
      },

      save() {
        let codata = this.getAllDefect()
        console.log(`codata类型-->${typeof codata}`)
        console.log(`codata内容-->${JSON.stringify(codata)}`)
        for (let key in codata){
          if(key.startsWith("device")){
            codata[key] = []
          }
        }
        console.log(`codata内容-->${JSON.stringify(codata)}`)
        if(Vue.android) {
          let  value = this.$androidUtil.path({alias: 'getUserinfomation', data:{condition: "f_userinfoid = '"+ this.item.f_userinfoid+"' and f_no_checkplan = '无计划安检'"}})

          if(this.item.f_no_checkplan == '无计划安检' &&  value.data.length == 0  &&  this.item.f_no_checkplan != '打回'){
            let result = this.$androidUtil.bzLogic('SafeSaveNoPaper', {
              f_check_item_id: this.data.f_check_item_id,
              f_checker_id: this.data.f_checker_id,
              f_upload_state:'未传',
              row: codata
            })
            if (result.code == 200) {
              //保存devices
              let res = this.$androidUtil.bzLogic('getPaperInfo', {
                f_check_item_id: this.data.f_noplan_item_id
              })
              console.log(`查询paper结果res======${res.data}`)
              if(res.code == 200){
                let f_paper_id = res.data[0].id
                for (let device of this.f_devices){
                  device.f_paper_id = f_paper_id
                  console.log('设备信息device======',device)
                  let ret = this.$androidUtil.bzLogic('saveDevice', {
                    row:device
                  })
                  if(ret.code != 200){
                    //TODO 失败后处理
                    // if(this.isUpload){
                    //   this.isUpload = false
                    // }
                    this.$showMessage("保存失败!")
                    return false
                  }
                }
              }
              // this.$showAlert('保存成功!', 'success', 2000)
              this.$showMessage('保存成功!')
              return true
            } else {
              // if(this.isUpload){
              //   this.isUpload = false
              // }
              this.$showMessage("保存失败!")
              return false
            }
          }else {
            //保存paper
            let result = this.$androidUtil.bzLogic('保存安检单信息', {
              f_check_item_id: this.data.f_check_item_id,
              f_checker_id: this.data.f_checker_id,
              row: codata
            })
            if (result.code == 200) {
              //保存devices
              let res = this.$androidUtil.bzLogic('getPaperInfo', {
                f_check_item_id: this.data.f_check_item_id
              })
              console.log(`查询paper结果res======${res.data}`)
              if(res.code == 200){
                let f_paper_id = res.data[0].id
                for (let device of this.f_devices){
                  device.f_paper_id = f_paper_id
                  console.log('设备信息device======',device)
                  let ret = this.$androidUtil.bzLogic('saveDevice', {
                    row:device
                  })
                  if(ret.code != 200){
                    //TODO 失败后处理
                    // if(this.isUpload){
                    //   this.isUpload = false
                    // }
                    this.$showMessage("保存失败!")
                    return false
                  }
                }
              }
              // this.$showAlert('保存成功!', 'success', 2000)
              this.$showMessage('保存成功!')
              return true
            } else {
              // if(this.isUpload){
              //   this.isUpload = false
              // }
              this.$showMessage("保存失败!")
              return false
            }
          }

        }else{
          console.log("保存的值",codata)
          let  value = this.$androidUtil.path({alias: 'getUserinfomation', data:{condition: "f_userinfoid = '"+ this.item.f_userinfoid+"' and f_no_checkplan = '无计划安检'"}})

          if(this.item.f_no_checkplan == '无计划安检' &&  value.data.length == 0  &&  this.item.f_no_checkplan != '打回'){
            this.$androidUtil.bzLogic('SafeSaveNoPaper', {
              f_check_item_id: this.data.f_check_item_id,
              f_checker_id: this.data.f_checker_id,
              f_upload_state: '未传',
              row: codata
            }).then((res)=> {
              if (res.data.code == 200) {
                //保存devices
                this.$androidUtil.bzLogic('getPaperInfo', {
                  f_check_item_id: this.data.f_check_item_id
                }).then((res)=>{
                  console.log(`查询paper结果res======${res}`)
                  if(res.data.code == 200){

                    let f_paper_id = res.data.data[0].id
                    for (let device of this.f_devices){
                      device.f_paper_id = f_paper_id
                      console.log('设备信息device======',device)
                      this.$androidUtil.bzLogic('saveDevice', {
                        row:device
                      }).then((ret)=>{
                        console.log(`保存设备信息结果res======`,ret)
                        if(ret.code != 200){
                          // if(this.isUpload){
                          //   this.isUpload = false
                          // }
                          //TODO 失败后处理
                          this.$showMessage("保存失败!")
                          return false
                        }
                      })
                    }
                  }
                })
                // this.$showAlert('保存成功!', 'success', 2000)
                this.$showMessage('保存成功!')
                return true
              } else {
                // if(this.isUpload){
                //   this.isUpload = false
                // }
                this.$showMessage("保存失败!")
                return false
              }
            })
          }else{
            this.$androidUtil.bzLogic('保存安检单信息', {
              f_check_item_id: this.data.f_check_item_id,
              f_checker_id: this.data.f_checker_id,
              row: codata
            }).then((res)=> {
              console.log('asdddddddddddddddddddddddddddddd')
              if (res.data.code == 200) {
                //保存devices
                this.$androidUtil.bzLogic('getPaperInfo', {
                  f_check_item_id: this.data.f_check_item_id
                }).then((res)=>{
                  console.log(`查询paper结果res======${res}`)
                  if(res.data.code == 200){

                    let f_paper_id = res.data.data[0].id
                    for (let device of this.f_devices){
                      device.f_paper_id = f_paper_id
                      console.log(`设备信息device======${device}`)
                      this.$androidUtil.bzLogic('saveDevice', {
                        row:device
                      }).then((ret)=>{
                        console.log(`保存设备信息结果res======${ret}`)
                        if(ret.code != 200){
                          // if(this.isUpload){
                          //   this.isUpload = false
                          // }
                          //TODO 失败后处理
                          this.$showMessage("保存失败!")
                          return false
                        }
                      })
                    }
                  }
                })
                // this.$showAlert('保存成功!', 'success', 2000)
                this.$showMessage('保存成功!')
                return true
              } else {
                // if(this.isUpload){
                //   this.isUpload = false
                // }
                this.$showMessage("保存失败!")
                return false
              }
            })
          }}},

      disableTimer() {
        if(this.timer) {
          window.clearTimeout(this.timer)
          this.timer = null
        }
      },
      loaded(paper) {
        if(!paper.hasOwnProperty('id')) {
          this.$showMessage("该安检单在手机上已经不存在，可能是卸载过程序。可以进入重新安检，或返回安检计划。")
          this.init()
        } else {
          Util.booleanFilter(paper)
          HostApp.__this__.$set('data', paper)
          HostApp.__this__.$goto('paper-state', {}, 'paper-router')
          // 如果打回重检则重新计时
          console.log('HostApp.__this__.role' + HostApp.__this__.role + ' HostApp.__this__.f_approved:' + HostApp.__this__.data.f_approved)
          if(HostApp.__this__.role == 'inspect'
            && HostApp.__this__.data.f_approved
            && HostApp.__this__.data.f_approved == '打回') {
            console.log('打回')
            HostApp.__this__.data.f_onsite_time = Util.toStandardTimeString()
            HostApp.__this__.tick()
          }
        }
        HostApp.__callback__ = null
        HostApp.__this__ = null
      },
      S4() {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
      },
      init () {
        this.data.f_noplan_item_id =  this.S4()+""+this.S4()+""+this.S4()+""+this.S4()+""+this.S4()+""+this.S4()+""+this.S4()+""+this.S4()
        this.data.ename = Vue.user.ename
        this.data.f_outlets = Vue.user.f_parentname
        this.data.f_meetunit = Vue.user.orgpathnames
        this.data.orgpathstr = Vue.user.orgpathstr
        this.data.f_check_item_id = this.item.id
        this.data.f_check_plan_id = this.f_plan_id
        this.data.f_checker_id = Vue.user.id
        this.data.f_checker_name = Vue.user.name
        this.data.f_check_type = this.item.f_user_type
        this.data.f_subcompany = this.item.f_subcompany
        this.data.f_approved = this.item.f_approved
        this.data.f_repair_approved = this.item.f_repair_approved
        this.data.f_no_checkplan = this.item.f_no_checkplan
        this.data.f_approved = this.item.f_approved
        this.data.f_filialeid = this.item.f_filialeid
        this.data.f_orgstr = this.item.f_orgstr
        this.data.version = this.item.version
        this.$set('data.f_meters', this.item.f_plan_meters)
        this.$set('data.f_userinfo_code', this.item.f_userinfo_code)
        // 安检状态
        this.$set('data.f_entry_status', '入户')
        this.$set('data.f_usegas', '已使用')
        this.$set('data.f_state',this.item.f_state)
        // 用户信息
        this.$set('data.f_user_name', this.item.f_user_name)
        this.$set('data.f_user_phone', this.item.f_user_phone)
        this.$set('data.f_userinfoid', this.item.f_userinfoid)
        this.$set('data.f_address', this.item.f_address)
        this.$set('data.f_card_id', this.item.f_card_id)
        this.$set('data.f_area', this.item.f_area)
        this.$set('data.f_street', this.item.f_street)
        this.$set('data.f_room',this.item.f_room)
        this.$set('data.f_building', this.item.f_building)
        this.$set('data.f_unit',this.item.f_unit)
        this.$set('data.f_floor', this.item.f_floor)
        this.$set('data.f_residential_area' , this.item.f_residential_area)
        this.$set('data.f_idnumber', this.item.f_idnumber)
        this.$set('data.f_comments', this.item.f_comments)
        this.$set('data.f_userproperties', this.item.f_userproperties)
        // 处置方式
        this.$set('data.f_no_gas_device', false)
        this.$set('data.f_close_valve', false)
        this.$set('data.f_unload_battery', false)
        if (this.data.f_check_item_id == '' && this.item.f_no_checkplan == '无计划安检') {
          this.data.f_check_item_id = this.data.f_noplan_item_id
        }

        //房屋结构
        // this.$set('data.f_room_style', '多层')
        //供暖方式
        //  this.$set('data.f_heating_style', '热力公司集中供暖')
        if(this.item.f_plan_meters) {
          for (let de in this.devices) {
            this.$set('data.device' + this.devices[de].n, [])
            for (let i = 0; i < this.item.f_plan_meters.length; i++) {
              if(this.item.f_plan_meters[i].f_meter_type) {
                if (this.devices[de].device == "燃气表" && this.item.f_plan_meters[i].f_meter_type.indexOf('机表') > 0) {
                  delete this.config['燃气表']['items']['累计购气量']
                  this.data['device' + this.devices[de].n].push({
                    f_device_type: "燃气表",
                    f_items: [{
                      f_defect_level: null,
                      f_device_id: "",
                      f_is_defect: "",
                      f_item_name: "表品牌",
                      f_item_value: this.item.f_plan_meters[i].f_aliasname,
                      f_path: "",
                      type: "string"
                    },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "位置",
                        f_item_value: this.item.f_plan_meters[i].f_weizhi,
                        f_path: "",
                        type: "selector"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表号",
                        f_item_value: this.item.f_plan_meters[i].f_meter_no,
                        f_path: "",
                        type: "number"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表封号",
                        f_item_value: this.item.f_plan_meters[i].f_metertitles,
                        f_path: "",
                        type: "number"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表型号",
                        f_item_value: this.item.f_plan_meters[i].f_diaphgram_size,
                        f_path: "",
                        type: "selector"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表底数",
                        f_item_value: this.item.f_plan_meters[i].f_prior_reading,
                        f_path: "",
                        type: "number"
                      }
                    ]
                  })
                } else if (this.devices[de].device == "燃气表") {
                  delete this.config['燃气表']['items']['表底数']
                  this.data['device' + this.devices[de].n].push({
                    f_device_type: "燃气表",
                    f_items: [{
                      f_defect_level: null,
                      f_device_id: "",
                      f_is_defect: "",
                      f_item_name: "表品牌",
                      f_item_value: this.item.f_plan_meters[i].f_aliasname,
                      f_path: "",
                      type: "string"
                    },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "位置",
                        f_item_value: this.item.f_plan_meters[i].f_weizhi,
                        f_path: "",
                        type: "selector"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表号",
                        f_item_value: this.item.f_plan_meters[i].f_meter_no,
                        f_path: "",
                        type: "number"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表封号",
                        f_item_value: this.item.f_plan_meters[i].f_metertitles,
                        f_path: "",
                        type: "number"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "表型号",
                        f_item_value: this.item.f_plan_meters[i].f_diaphgram_size,
                        f_path: "",
                        type: "selector"
                      },
                      {
                        f_defect_level: null,
                        f_device_id: "",
                        f_is_defect: "",
                        f_item_name: "累计购气量",
                        f_item_value: this.item.f_plan_meters[i].f_prior_reading,
                        f_path: "",
                        type: "number"
                      }
                    ]
                  })
                }
              }
            }
          }
        }

        this.$goto('paper-state', {}, 'paper-router')
      },
      extend(initalObj, finalObj) {
        var obj = finalObj || {};
        for (var i in initalObj) {
          var prop = initalObj[i];

          // 避免相互引用对象导致死循环，如initalObj.a = initalObj的情况
          if (prop === obj) {
            continue;
          }

          if (typeof prop === 'object') {
            if (obj[i]) {
              this.extend(obj[i], prop)
            } else {
              obj[i] = prop;
            }
          }
        }
        return obj;
      },
  /*
  var a = {
  "燃气表":{
    "index": 1,
    "checkmust":true,
    "items":{
      "表具故障":{"index": 13,"multiple":true,"type":"selector","options":[{"data":"死表","isdefect":true,"level":"安检维修"},{"data":"常通","isdefect":true,"level":"安检维修"},{"data":"表体漏气","isdefect":true,"level":"一级隐患安检维修"},{"data":"接口漏气","isdefect":true,"level":"一级隐患安检维修"},{"data":"偷气","isdefect":true,"level":"一级隐患"},{"data":"反装","isdefect":true},{"data":"气量不符","isdefect":true,"level":"安检维修"},{"data":"其他","isdefect":true,"level":"一级隐患"}]},
      "其他":{"index": 14,"isshow":false,"type":"string"},
      "表具隐患类型":{"index": 15,"multiple":true,"type":"selector","options":[{"data":"挂物","isdefect":true},{"data":"包裹","isdefect":true},{"data":"不便维修","isdefect":true},{"data":"封闭包裹","isdefect":true,"level":"一级隐患"},{"data":"与电源或火源过近","isdefect":true,"level":"三级隐患"}]}
    }
  },
  "报警器":{
    "index": 2,
    "checkmust":true,
    "items":{
      "有否":{"index": 1,"multiple":false,"type":"selector","options":[{"data":"有","isdefect":false,"isdefault":true},{"data":"无","isdefect":false}]},
      "厂家":{"index": 2,"multiple":false,"isshow":false,"type":"selector","options":[{"data":"汉威","isdefect":false},{"data":"鑫豪斯","isdefect":false},{"data":"友谊","isdefect":false},{"data":"其他","isdefect":false},{"data":"富昌","isdefect":false},{"data":"科信","isdefect":false}]},
      "安装时间":{"index": 3,"isshow": false,"type":"date"},
      "到期时间":{"index": 4,"isshow": false,"type":"date"},
      "是否通电":{"index": 5,"multiple":false,"isshow": false,"type":"selector","options":[{"data":"是","isdefect":false,"isdefault":true},{"data":"否","isdefect":true}]},
      "安装渠道":{"index": 6,"isshow": false,"multiple":false,"type":"selector","options":[{"data":"惠众","isdefect":false},{"data":"其他","isdefect":false}]},
      "电磁阀接口漏气":{"index": 7,"multiple":false,"isshow": false,"type":"selector","options":[{"data":"否","isdefect":false,"isdefault":true},{"data":"是","isdefect":true,"level":"一级隐患安检维修"}]}
    }
  }}
   */
      putDevices() {
        //console.log('Vue.config.safecheck', Vue.config.safecheck.safetype)
        this.$set('data.approve', "true")
        this.$set('data.writeback', "false")
        if (Vue.config.safecheck.ApproveConfig != undefined) {
          if (Vue.config.safecheck.ApproveConfig.approve != undefined) {
            this.$set('data.approve', Vue.config.safecheck.ApproveConfig.approve)
          }
          if (Vue.config.safecheck.ApproveConfig.writeback != undefined) {
            this.$set('data.writeback', Vue.config.safecheck.ApproveConfig.writeback)
          }
          if (Vue.config.safecheck.ApproveConfig.livedispose != undefined) {
            this.livedispose = Vue.config.safecheck.ApproveConfig.livedispose
          }
        }
        console.log('当前安检类型----'+this.item.f_safecheck_type)
        if(!this.item.f_safecheck_type){
          this.config = this.extend(this.config, Vue.config.safecheck[Vue.config.safecheck.SafecheckType['年度普检']['民用']])
        }else{
          if (Vue.config.safecheck.DevicesConfig != undefined)
            this.config = this.extend(this.config, Vue.config.safecheck[Vue.config.safecheck.SafecheckType[this.item.f_safecheck_type]['民用']])
        }
        //遍历安检项配置
        for (let i in this.config) {
          //取得安检项索引值
          let n = this.config[i].index
          this.devices[n - 1] = {device: i, n: n, checkmust: this.config[i].checkmust}
          this.$set('data.' + 'device' + n, [])
          let items = []
          for (let it in this.config[i].items) {
            //赋值下拉选项
            if (this.config[i].items[it].type == 'selector') {
              for (let op in this.config[i].items[it].options)
                if (this.config[i].items[it].options[op].isdefault == true) {
                  items.push({
                    f_defect_level: this.config[i].items[it].options[op].level,
                    f_is_defect: this.config[i].items[it].options[op].isdefect,
                    f_item_name: it,
                    f_item_value: this.config[i].items[it].options[op].data,
                    f_path: "",
                    type: "selector"
                  })
                }
            }
          }
          n = n + 1
        }

      },
      //获取当前时间
      getNowFormatDate(){
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
          + " " + date.getHours() + seperator2 + date.getMinutes()
          + seperator2 + date.getSeconds();
        return currentdate;
      }
    },
    ready() {
      this.initconfig()
      this.putDevices()
      //如果已检，则提取安检单

      if (this.item.f_state != '未检' || this.item.f_no_checkplan == '无计划安检') {
        if (this.role != 'inspect') {
          let that = this
          let id
          if (this.role == 'view') {
            id = this.item.id
          } else if (this.role == 'androidview') {
            id = this.item.f_paper_id
          }
          this.$resetpost(`${this.$androidUtil.getProxyUrl()}/rs/path/getUserinfomation`, {data: {condition: `id = '${id}'`}}).then((respanse) => {
              console.log('result....', respanse)
              if (respanse.data.length != 0) {
                // 包含 其它 特殊处理的数组
                // 对应位置

                console.log('devices => ', respanse.data[0])

                that.data = Object.assign(that.data, respanse.data[0])
                if (respanse.data[0].f_devices) {
                  for (let da in that.devices) {
                    that.$set('data.device' + that.devices[da].n, [])
                  }
                  respanse.data[0].f_devices.forEach((item) => {
                    for (let de in that.devices) {
                      if (that.devices[de].device == item.f_device_type) {
                        item.f_items.forEach((f_item) => {
                          console.log('f_item====>', f_item)
                          console.log('f_item.f_path====>', f_item.f_path)
                          let itemValues = []
                          f_item.f_item_lists.forEach((tempItem) => {
                            console.log('emm => ', f_item.f_item_name, '   ', tempItem.f_item_value)
                            if (tempItem.f_item_value !== 'null') {
                              itemValues.push(tempItem.f_item_value)
                            }
                          })
                          f_item.f_item_value = itemValues
                        })
                        that.data['device' + that.devices[de].n].push({
                          f_device_type: item.f_device_type,
                          f_items: item.f_items
                        })
                      }
                    }
                  })
                }
                Util.replaceFalse(that.data)
                Util.booleanFilter(that.data)
                if (this.role == 'view') {
                  Util.ratifyPics(that.data)
                  Util.ratifyPics(that.picture)
                } else {
                  Util.androidRatifyPics(that.data, this.$androidUtil.getProxyUrl())
                }
                console.log("that.data:", that.data)
              } else {
                alert("该安检单可能已不在本地!")
                this.init()
              }
              // this.$goto('paper-message-blank', {userinfo:this.data,devices:this.devices,config:this.config,role:this.role}, 'self')
              this.isshow = true
            }
          ).catch(
            (respanse) => {
              console.log('respanse',respanse)
              alert('查找安检单失败')
            })
        }
        // else {
        //   let that = this
        //   this.$androidUtil.bzLogic('FetchCheckPaper', {id: this.item.id}).then((respanse) => {
        //       if (respanse.data.data.length != 0) {
        //         that.data = Object.assign(that.data, respanse.data.data[0])
        //         if (respanse.data.data[0].f_devices) {
        //           for (let da in that.devices) {
        //             that.$set('data.device' + that.devices[da].n, [])
        //           }
        //           respanse.data.data[0].f_devices.forEach((item) => {
        //             for (let de in that.devices) {
        //               if (that.devices[de].device == item.f_device_type) {
        //                 that.$set('data.device' + that.devices[de].n, [])
        //                 that.data['device' + that.devices[de].n].push({
        //                   f_device_type: item.f_device_type,
        //                   f_items: item.f_items
        //                 })
        //               }
        //             }
        //           })
        //         }
        //         Util.booleanFilter(that.data)
        //         console.log("that.data:", that.data)
        //       } else {
        //         alert("该安检单可能已不在本地!")
        //         this.init()
        //       }
        //       // this.$goto('paper-message-blank', {userinfo:this.data,devices:this.devices,config:this.config,role:this.role}, 'self')
        //       this.isshow = true
        //     }
        //   ).catch(
        //     (respanse) => {
        //       alert('查找安检单失败')
        //     })
        // }
      } else {
        this.init()
      }
    },
    watch:{
      //   'isUpload'(val){
      //     console.log('isUpload发生变化===>'+val)
      //   }
    },
    destroyed() {
      console.log('退出当前页Set')
      this.disableTimer()
    }
  }

</script>
