<style>
.divmask {
  pointer-events: none;
}
</style>

<template>
  <work-busy :is-busy="seaching" v-show="seaching"></work-busy>
  <div class="auto" style="height:auto;" id="safecheck" v-if="isshow">
    <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="data" :deviceresult="deviceresult"
                       :deviceCollects="deviceCollects"></paper-feedbackm>
    </div>
    <back-page :need-back='true' @flag="back()" v-show="showBack"></back-page>
  </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 {
      seaching: false,
      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: [],
      deviceCollects: [],
      f_devices: [],
      isToRepair: false,
      isSafeCheckToRepair: false,//是否转维修
      deviceresult: '正常',
      picture: [],
      config: {
        "燃气表": {
          "checkmust": true,
          "items": {
            "燃气表照片": {"index": 1, "type": "picture"},
            "表品牌": {"index": 2, "type": "string"},
            "表号": {"index": 3, "type": "string"},
            "表封号": {"index": 4, "type": "number"},
            "表型号": {
              "index": 5,
              "type": "selector",
              "options": [{"data": "G2.5", "isdefect": false}, {
                "data": "G4",
                "isdefect": false
              }, {"data": "G6", "isdefect": false}, {
                "data": "G10",
                "isdefect": false
              }, {"data": "G1.6", "isdefect": false}, {
                "data": "G20",
                "isdefect": false
              }, {"data": "G16", "isdefect": false}, {
                "data": "G25",
                "isdefect": false
              }, {"data": "G60", "isdefect": false}, {"data": "其他", "isdefect": false}]
            },
            "位置": {
              "index": 6,
              "type": "selector",
              "options": [{"data": "室内", "isdefect": false}, {"data": "室外", "isdefect": false}]
            },
            "表底数": {"index": 7, "type": "number"},
            "累计购气量": {"index": 7, "type": "number"},
          }
        }
      }
    }
  },
  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) {
          this.$goto(val, {userinfo: this.data}, 'paper-router')
        } else {
          this.$showMessage('未开始安检！')
        }
      }
    },
    actionEnabled: {
      get() {
        return this.role == 'inspect'
      }
    }
  },
  methods: {
    back() {
      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() ? '已修' : '在修'
    },
    genuineSave(saveOnly) {
      HostApp.__this__.save(saveOnly)
      if (!saveOnly)
        HostApp.__this__.disableTimer()
      HostApp.__callback__ = null
      HostApp.__this__ = null
    },
    uploadPaper() {
    },
    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.safecheck != undefined) {
        if (Vue.config.safecheck.safecheck.ApproveConfig != undefined) {
          if (Vue.config.safecheck.safecheck.ApproveConfig.weixinurl != undefined) {
            url = Vue.config.safecheck.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_user_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_filialeids = this.item.f_filialeids
      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_visit_state', this.item.f_visit_state)
      this.$set('data.f_state', this.item.f_state)
      // 用户信息
      this.$set('data.f_user_name', this.item.f_user_name)
      this.$set('data.f_rent_name', this.item.f_rent_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;
    },
    devicesCollect() {
      console.log('devicesCollect')
      console.log('data => ' + JSON.stringify(this.data))
      this.deviceCollects = []
      // this.result = '正常'
      let codata = JSON.parse(JSON.stringify(this.data))

      let levelOne = {name: '一级隐患', deviceInfos: ''}
      let levelTwo = {name: '二级隐患', deviceInfos: ''}
      let levelThree = {name: '三级隐患', deviceInfos: ''}
      let levelOther = {name: '其他', deviceInfos: ''}

      let levelOneDeviceInfos = []
      let levelTwoDeviceInfos = []
      let levelThreeDeviceInfos = []
      let levelOtherDeviceInfos = []

      let content = this.firstEnter ? 'device' : 'f_devices'
      console.log('content => ' + JSON.stringify(content))

      for (let device in this.data) {
        let f_device_type

        if (device.startsWith(content)) {
          for (let item in this.data[device]) {
            //   if (this.data[device].length > 1) {
            //     let j = Number.parseInt(item) + 1
            //     f_device_type = `${this.data[device][item].f_device_type}${j}`
            //   } else {
            f_device_type = this.data[device][item].f_device_type
            // }
            // console.log('codata[device][item]=>',codata[device][item])
            console.log('this.data[device][item].f_items => ' + JSON.stringify(this.data[device][item].f_items))


            let levelOneArr = []
            let levelTwoArr = []
            let levelThreeArr = []
            let levelOtherArr = []

            for (let i in this.data[device][item].f_items) {
              let items = this.data[device][item].f_items[i]
              if (items.type === 'selector' && items.f_item_value != null && items.f_item_value instanceof Array) {

                let levelOneInfos = `${items.f_item_name}:`
                let levelTwoInfos = `${items.f_item_name}:`
                let levelThreeInfos = `${items.f_item_name}:`
                let levelOtherInfos = `${items.f_item_name}:`

                for (let i in items.f_item_value) {
                  let f_item_value = items.f_item_value[i]

                  console.log('f_item_value => ' + JSON.stringify(f_item_value))
                  console.log('f_device_type => ' + JSON.stringify(f_device_type))
                  console.log('this.data[device][item] => ' + JSON.stringify(this.data[device][item]))
                  if ((this.data[device][item].f_device_type == '燃气表' && (items.f_item_name == '表具故障' || items.f_item_name == '表具隐患类型')) || this.data[device][item].f_device_type != '燃气表') {
                    if (this.config[this.data[device][item].f_device_type].items[items.f_item_name] && this.config[this.data[device][item].f_device_type].items[items.f_item_name].type == 'selector') {
                      console.log('进来了阿萨德啊啊')
                      let options = this.config[this.data[device][item].f_device_type].items[items.f_item_name].options
                      console.log('options', options)
                      for (let option in options) {
                        if (options[option].data == f_item_value) {
                          if (options[option].isdefect == 'true' || options[option].isdefect == true) {
                            this.deviceresult = '有隐患'
                            let level = options[option].level
                            switch (level) {
                              case '一级隐患':
                                levelOneInfos = `${levelOneInfos}${options[option].data}/`;
                                break
                              case '二级隐患':
                                levelTwoInfos = `${levelTwoInfos}${options[option].data}/`;
                                break
                              case '三级隐患':
                                levelThreeInfos = `${levelThreeInfos}${options[option].data}/`;
                                break
                              default:
                                levelOtherInfos = `${levelOtherInfos}${options[option].data}/`;
                                break
                            }
                          }

                        }

                      }
                    }
                  }
                }
                if (levelOneInfos.endsWith('/')) {
                  levelOneArr.push(levelOneInfos.substring(0, levelOneInfos.length - 1))
                }
                if (levelTwoInfos.endsWith('/')) {
                  levelTwoArr.push(levelTwoInfos.substring(0, levelTwoInfos.length - 1))
                }
                if (levelThreeInfos.endsWith('/')) {
                  levelThreeArr.push(levelThreeInfos.substring(0, levelThreeInfos.length - 1))
                }
                if (levelOtherInfos.endsWith('/')) {
                  levelOtherArr.push(levelOtherInfos.substring(0, levelOtherInfos.length - 1))
                }
              }
              if (items.type === 'selector') {
                items.selected = []
              } else if (items.type === 'inputSelector') {
                items.selected = ''
              }
            }

            if (levelOneArr.length > 0) {
              levelOneDeviceInfos.push(levelOneArr.join(','))
            }
            if (levelTwoArr.length > 0) {
              levelTwoDeviceInfos.push(levelTwoArr.join(','))
            }
            if (levelThreeArr.length > 0) {
              levelThreeDeviceInfos.push(levelThreeArr.join(','))
            }
            if (levelOtherArr.length > 0) {
              levelOtherDeviceInfos.push(levelOtherArr.join(','))
            }
          }
        }
      }

      if (levelOneDeviceInfos.length > 0) {
        levelOne.deviceInfos = levelOneDeviceInfos.join(',')
        this.deviceCollects.push(levelOne)
      }
      if (levelTwoDeviceInfos.length > 0) {
        levelTwo.deviceInfos = levelTwoDeviceInfos.join(',')
        this.deviceCollects.push(levelTwo)
      }
      if (levelThreeDeviceInfos.length > 0) {
        levelThree.deviceInfos = levelThreeDeviceInfos.join(',')
        this.deviceCollects.push(levelThree)
      }
      if (levelOtherDeviceInfos.length > 0) {
        levelOther.deviceInfos = levelOtherDeviceInfos.join(',')
        this.deviceCollects.push(levelOther)
      }
      console.log('levelOne => ' + JSON.stringify(levelOne))
      console.log('levelTwo => ' + JSON.stringify(levelTwo))
      console.log('levelThree => ' + JSON.stringify(levelThree))
      console.log('levelOther => ' + JSON.stringify(levelOther))
      if (this.deviceCollects.length > 0) {
        this.hasDevice = true
      }
    },
    putDevices() {
      console.log('Vue.config.safecheck', Vue.config.safecheck)
      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_no_checkplan === '点火通气单'){
        this.config = this.extend(this.config, Vue.config.safecheck.Ventilate)
      }else{
        this.config = this.extend(this.config, Vue.config.safecheck.DevicesConfig)
      }
      //遍历安检项配置
      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.seaching = true
    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(`/rs/logic/getCheckPaperInfo`, {data: {id: id}}).then((respanse) => {
          console.log('result=====>', respanse)
          if (respanse.data.length != 0) {
            // 包含 其它 特殊处理的数组
            // 对应位置
            let otherProcessType = ['表后管', '灶具连接管', '立管', '燃气表']
            let otherProcessName = ['表后管隐患类型', '灶具连接管隐患类型', '立管漏气位置', '表具故障']
            // 包含 漏气位置 特殊处理的数组
            let airLeakProcessType = ['表后管', '立管', '热水器', '壁挂锅炉']
            let airLeakProcessName = ['隐患类型']

            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) => {
                console.log('item==>', item)
                for (let de in that.devices) {
                  if (that.devices[de].device == item.f_device_type) {
                    // 标记是否需要特殊处理的类型
                    // 获取其它类别的索引
                    let otherIndex = otherProcessType.indexOf(item.f_device_type)
                    // 漏气位置的特殊处理不需要判断位置
                    let airLeakIndex = airLeakProcessType.indexOf(item.f_device_type)
                    // 标记是否包含 其它
                    let hasOther = false
                    // 标记是否包含 漏气位置
                    let hasAirLeak = false
                    item.f_items.forEach((f_item) => {
                      console.log('f_item====>', f_item)
                      console.log('f_item.f_path====>', f_item.f_path)
                      if (f_item.f_path != '' && f_item.f_path != null) {
                        console.log('123')
                        this.picture.push({f_path: f_item.f_path, name: f_item.f_item_name})
                      }
                      let itemValues = []
                      console.log('f_item.f_item_lists====>', f_item.f_item_lists)
                      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)
                        }
                        // 如果是对应的类型下对应的名称，并且隐患选择了其它，才去显示其它，标记变为 true
                        if (f_item.f_item_name === '其他') {
                          hasOther = true
                        }
                        if (otherIndex >= 0 && !hasOther) {
                          hasOther = otherProcessName[otherIndex] === f_item.f_item_name && tempItem.f_item_value === '其他'
                        }
                        // 如果是对应的类型下的隐患类型,并且隐患选择了漏气位置，才去显示漏气位置，标记变为 true
                        if (airLeakIndex >= 0 && !hasAirLeak) {
                          hasAirLeak = airLeakProcessName[0] === f_item.f_item_name && tempItem.f_item_value === '漏气'
                        }
                      })
                      f_item.f_item_value = itemValues
                    })
                    // 如果不包含其它或漏气位置，不显示，将对应的f_item_value变为['']
                    if (!hasOther || !hasAirLeak) {
                      item.f_items.forEach((f_item) => {
                        console.log((!hasOther && f_item.f_item_name === '其他') || (!hasAirLeak && f_item.f_item_name === '漏气位置'))
                        if ((!hasOther && f_item.f_item_name === '其他') || (!hasAirLeak && f_item.f_item_name === '漏气位置')) {
                          f_item.f_item_value = ['']
                        }
                      })
                    }
                    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).then(() => {
                Util.ratifyPics(that.picture).then(() => {
                  this.isshow = true
                  this.seaching = false
                }).catch(() => {
                  this.isshow = true
                  this.seaching = false
                })
              }).catch(() => {
                this.isshow = true
                this.seaching = false
              })
            } else {
              Util.androidRatifyPics(that.data, this.$androidUtil.getProxyUrl()).then(() => {
                this.isshow = true
                this.seaching = false
              }).catch(() => {
                this.isshow = true
                this.seaching = false
              })
            }

            console.log("that.data:", that.data)
          } else {
            alert("该安检单可能已不在本地!")
            this.init()
            this.isshow = true
            this.seaching = false
          }
        }
      ).catch(
        (respanse) => {
          console.log('respanse', respanse)
          alert('查找安检单失败')
          this.seaching = false
        })
    } 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
          this.seaching = false
        }
      ).catch(
        (respanse) => {
          alert('查找安检单失败')
          this.seaching = false
        })
    }
    // } else {
    //     this.init()
    // }
  },
  watch: {
    //   'isUpload'(val){
    //     console.log('isUpload发生变化===>'+val)
    //   }
  },
  events: {
    'getDevicesCollect'(val) {
      console.log('获取')
      this.devicesCollect()
    }
  },
  destroyed() {
    console.log('退出当前页Set')
    this.disableTimer()
  }
}

</script>
