<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 style="width: 50%;height: 620px; margin-left: 20px;margin-top: 0px;margin-bottom: 20px;float:left" id="one">
        <paper-userm></paper-userm>
      </div>
      <div style="width: 45%;height: 620px; margin-left: 20px;margin-top: 0px;margin-bottom: 20px;float:left">
        <paper-state-noncivilm></paper-state-noncivilm>
      </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>

      <modal :show.sync="showModal">
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">
            照片浏览
          </h4>
        </div>
        <div slot="modal-body" class="modal-body">
          <img :src="pic_to_be_viewed" width="420" height="560">
        </div>
        <div slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-default" @click="showModal = false">确认</button>
        </div>
      </modal>
      <div class="page-header app-header auto">
        <div @click="back()">
          <img src="../../assets/back.png"/>
        </div>
      </div>
    </div>
  </div>
  <!--<work-busy :is-busy="isUpload"></work-busy>-->
</template>

<script>
  import PaperUserm from '../android/PaperUserm'
  import PaperStateNoncivilm from '../rongcheng/PaperStateNoncivilm'
  import Devicesm from '../android/Devicesm'
  import PaperFeedbackm from '../android/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:[],
        },
        isshow:false,
        isUpload:false,
        livedispose:'',
        timer: null,
        isToRepair:false,
        startClick:false,//开始安检按钮是否可点击
        isStart:false, //是否开始安检
        checkResult:{},
        newcheckResult:{},
        showModal: false,
        pic_to_be_viewed: '',
        devices:[],
        f_devices:[],
        isSafeCheckToRepair:false,//是否转维修
        showBack:true,
        config:{
          "燃气表":{
            "checkmust":true,
            "index":1,
            "items":{
              //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
              "基表编号":{"index":1,"type":"string","readonly":false,"checkmust":true},
              "气表型号":{"index":2,"type":"string","readonly":true},
              "气表品牌":{"index":3,"type":"string","readonly":true},
              "进气方向":{"index":4,"type":"selector",
                "multiple": false,
                "options": [
                  {
                    "data": "左表",
                    "isdefect": false,
                    "isdefault": false
                  },
                  {
                    "data": "右表",
                    "isdefect": false,
                    "isdefault": false
                  }
                ]
              },
              "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
              "上期表读数":{"index":6,"type":"number","readonly":true,isshow:true},
              "本期表读数":{"index":7,"type":"number","checkmust":true},
              "累购气量":{"index":8,"type":"number","readonly":true},
              "累购金额":{"index":8,"type":"number","readonly":true},
              "已用气量":{"index":9,"type":"number","checkmust": true},//基表数
              "已用金额":{"index":9,"type":"number","checkmust": true},
              "剩余气量":{"index":10,"type":"number","checkmust": true},//累购-已用
              //显示屏数  --实际剩余气量
              "剩余金额":{"index":10,"type":"number","checkmust": true},
              "气量异常差值":{"index":11,"type":"number","readonly": true},
              "金额异常差值":{"index":11,"type":"number","readonly": true},
              "流量计表号":{
                "index": 12,
                "type": "string",
                "multiple": false
              },
              "流量计品牌":{
                "index": 13,
                "type": "string",
                "multiple": false
              },
              "流量计型号":{
                "index": 14,
                "type": "string",
                "multiple": false
              },
              "流量计出厂日期":{
                "index": 15,
                "type": "string",
                "multiple": false
              }
            }
            // 注意，配置项的index必须与上面的固定配置保持'顺序'
          },
        }
      }
    },
    components: {
      RadioGroup,
      Radio,
      "paper-userm":PaperUserm,
      "paper-state-noncivilm":PaperStateNoncivilm,
      "devicesm":Devicesm,
      "paper-feedbackm":PaperFeedbackm
    },
    computed: {
      selector: {
        get() {
          return 'paper-state-noncivil'
        },
        set(val) {
          if(this.isStrat){
            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()
        }
      },
      viewPic(fileName) {
        //tag
        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() ? '已修' : '在修'
      },
      async savePaper(saveOnly) {
        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.isStrat = false
              this.disableTimer()
              return this.save()
            } else {
              //tag
              if(!this.data.f_offsite_time){
                this.$set('data.f_offsite_time', Util.toStandardTimeString())
              }
              //tag
              this.data.f_complete = '已完成'
              this.disableTimer()
              return this.save()
            }
          } else {
            if (errString) {
              //tag
              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())
              }
              //tag
              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
        this.savePaper(false).then((res) => {
          //tag
          if(res !=true){
            console('失败')
            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
      },
      verifyAllDefect(){
        let prefix = '隐患汇总 '
        this.data.f_defects.forEach((item)=>{
          if(Util.required(item.f_resolve_type))
            return prefix + item.f_defect + '处理方式必填'
          if(Util.required(item.f_ratification))
            return prefix + item.f_defect + '整改结果必填'
        })
      },

      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_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
              }
              // //tag
              for(let i in codata[device][item].f_items){
                let items = codata[device][item].f_items[i]
                //tag
                if(items.f_is_defect == true || items.f_is_defect == 'true'){
                  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{
                    //tag
                    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 = ''
                }
              }
              //tag
              this.f_devices.push(codata[device][item])
            }
          }
        }
        if(this.checkResult){
          for (let key in this.checkResult){
            //tag
            this.$set('newcheckResult.'+key,this.checkResult[key])
            checkResults.data.push(this.newcheckResult)
            this.newcheckResult = {}
          }
          this.checkResult = {}
        }
        //tag
        codata.f_defect_content = JSON.stringify(checkResults)
        //tag
        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(){

        //获取微信推送路径
        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
          })
          if(!this.isToRepair){
            if(haslivedispose.data.length > 0 && (this.livedispose == 'true' || this.livedispose == true)){
              if(!this.isSafeCheckToRepair){
                this.$showMessage('有未处理的隐患，请前往拍照上传中将安检转为维修单！')
                return
              }
            }
          }
          // HostApp.uploadPaper({f_check_item_id: this.data.f_check_item_id, f_checker_id: this.data.f_checker_id, data: this.data})
          //tag
          for (let key in codata){
            if(key.startsWith("device")){
              codata[key] = []
            }
          }
          //tag}`)
          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) {
              //tag
              //tag
              //tag
              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)
              //tag
              //tag)
              //tag)
              for (let device in this.data){
                //tag
                //tag)
                if(device.startsWith("device")){
                  for(let devices of this.data[device]) {
                    devices.f_paper_id = f_paper_id
                    //tag
                    //tag)
                    let ret = this.$androidUtil.bzLogic('UpCheckPaperDevices', {
                      row: devices
                    })
                    //tag
                    if(ret.code == 200){
                      devices.f_device_id = JSON.parse(ret.data.f_device_id).id
                    }
                    if (ret.code != 200) {
                      // this.isUpload = false
                      //TODO 失败后处理
                      this.$showMessage("上传失败!")
                      return false
                    }
                  }
                }
              }
              // for (let device of this.f_devices) {
              //   device.f_paper_id = f_paper_id
              //   //tag
              //   //tag)
              //   let ret = this.$androidUtil.bzLogic('UpCheckPaperDevices', {
              //     row: device
              //   })
              //   //tag
              //   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.isUpload = false
                // 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) {
            //tag)
            // this.isUpload = false
            this.$showMessage("上传失败！")
          }
        }
      },

      save() {
        let codata = this.getAllDefect()
        //tag
        //tag}`)
        for (let key in codata){
          if(key.startsWith("device")){
            codata[key] = []
          }
        }
        //tag}`)
        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
              })
              //tag
              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
                  //tag
                  let ret = this.$androidUtil.bzLogic('saveDevice', {
                    row:device
                  })
                  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 {
            //保存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
              })
              //tag
              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
                  //tag
                  let ret = this.$androidUtil.bzLogic('saveDevice', {
                    row:device
                  })
                  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{
          //tag
          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)=>{
                  //tag
                  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
                      //tag
                      this.$androidUtil.bzLogic('saveDevice', {
                        row:device
                      }).then((ret)=>{
                        //tag
                        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)=> {
              //tag
              if (res.data.code == 200) {
                //保存devices
                this.$androidUtil.bzLogic('getPaperInfo', {
                  f_check_item_id: this.data.f_check_item_id
                }).then((res)=>{
                  //tag
                  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
                      //tag
                      this.$androidUtil.bzLogic('saveDevice', {
                        row:device
                      }).then((ret)=>{
                        //tag
                        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
              }
            })
          }}},

      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-noncivil', {}, 'paper-router')
          // 如果打回重检则重新计时
          //tag
          if(HostApp.__this__.role == 'inspect'
            && HostApp.__this__.data.f_approved
            && HostApp.__this__.data.f_approved == '打回') {
            //tag
            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 () {
        if(this.item.f_collection_type=='按金额'){
          this.config= {
            "燃气表":{
              "checkmust":true,
              "index":1,
              "items":{
                //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
                "基表编号":{"index":1,"type":"string","readonly":false,"checkmust":true},
                "气表型号":{"index":2,"type":"string","readonly":true},
                "气表品牌":{"index":3,"type":"string","readonly":true},
                "进气方向":{"index":4,"type":"selector",
                  "multiple": false,
                  "options": [
                    {
                      "data": "左表",
                      "isdefect": false,
                      "isdefault": false
                    },
                    {
                      "data": "右表",
                      "isdefect": false,
                      "isdefault": false
                    }
                  ]
                },
                "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
                "上期表读数":{"index":6,"type":"number","readonly":true,"isshow":true},
                "本期表读数":{"index":7,"type":"number","checkmust":true},
                "累购金额":{"index":8,"type":"number","readonly":true},
                "已用金额":{"index":9,"type":"number","checkmust": true},
                //显示屏数  --实际剩余气量
                "剩余金额":{"index":10,"type":"number","checkmust": true},
                "金额异常差值":{"index":11,"type":"number","readonly": true,"isshow":false},
                "流量计表号":{
                  "index": 12,
                  "type": "string",
                  "multiple": false
                },
                "流量计品牌":{
                  "index": 13,
                  "type": "string",
                  "multiple": false
                },
                "流量计型号":{
                  "index": 14,
                  "type": "string",
                  "multiple": false
                },
                "流量计出厂日期":{
                  "index": 15,
                  "type": "string",
                  "multiple": false
                }
              }
              // 注意，配置项的index必须与上面的固定配置保持'顺序'
            }
          }
        }else{
          this.config= {
            "燃气表":{
              "checkmust":true,
              "index":1,
              "items":{
                //"燃气表照片":{"index":1,"type":"picture","remark":"(拍摄清晰的表具编号、字轮数、剩余气量等)"},
                "基表编号":{"index":1,"type":"string","readonly":false,"checkmust":true},
                "气表型号":{"index":2,"type":"string","readonly":true},
                "气表品牌":{"index":3,"type":"string","readonly":true},
                "进气方向":{"index":4,"type":"selector",
                  "multiple": false,
                  "options": [
                    {
                      "data": "左表",
                      "isdefect": false,
                      "isdefault": false
                    },
                    {
                      "data": "右表",
                      "isdefect": false,
                      "isdefault": false
                    }
                  ]
                },
                "初始表底":{"index":5,"type":"number","isshow":false,"readonly":true},
                "上期表读数":{"index":6,"type":"number","readonly":true,isshow:true},
                "本期表读数":{"index":7,"type":"number","checkmust":true},
                "累购气量":{"index":8,"type":"number","readonly":true},
                "已用气量":{"index":9,"type":"number","checkmust": true},//基表数
                "剩余气量":{"index":10,"type":"number","checkmust": true},//累购-已用
                //显示屏数  --实际剩余气量
                "气量异常差值":{"index":11,"type":"number","readonly": true,"isshow":false},
                "流量计表号":{
                  "index": 12,
                  "type": "string",
                  "multiple": false
                },
                "流量计品牌":{
                  "index": 13,
                  "type": "string",
                  "multiple": false
                },
                "流量计型号":{
                  "index": 14,
                  "type": "string",
                  "multiple": false
                },
                "流量计出厂日期":{
                  "index": 15,
                  "type": "string",
                  "multiple": false
                }
              }
            }
          }
        }
      },
      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;
      },
      putDevices() {
        //tag
        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
          }
        }
        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.init()
      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) => {
              //tag
              if (respanse.data.length != 0) {
                // 包含 其它 特殊处理的数组
                // 对应位置

                //tag

                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) => {
                          //tag
                          //tag
                          let itemValues = []
                          f_item.f_item_lists.forEach((tempItem) => {
                            //tag
                            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())
                }
                //tag
              } 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) => {
              //tag
              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)
        //         //tag
        //       } 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()
      }
    },
    destroyed() {
      this.disableTimer()
      //tag
    },

  }
</script>
