<template>
  <div id="savebut" class="no-close row android-repair-order" style="background-color: #f9f9f9">
    <div class="col-sm-12 col-xs-12" >
      <ul class="nav nav-tabs" style="background:#ffffff;overflow-y: hidden">
        <li v-for="row in tabs" @click="tabSelect(row,$index)" :class="{active1: row.complete === componentName}"
            v-if="$index < number+1 && $index < faultshow.number" >
          <a href="#" style="background-color: #ffffff;color: #666666;font-size: 16px;font-family:SimSun" :class="row.class">
            <span class="spanboder">{{row.header}}</span>
            <img class="butt2" :src="imgback(row.complete === componentName,row.header === header)"></a>
          <p></p>
        </li>
        <div class="col-sm-12 col-xs-12 repair-bg"  v-show="routeShow">
          <route name='repair' :reuse="false"></route>
        </div>
        <li v-for="row in tabs" @click="tabSelect(row,$index)" :class="{active1: row.complete === componentName}"
            v-if="$index > number && $index < faultshow.number ">
          <a href="#" style="background-color: #ffffff;color: #666666;font-size: 16px;font-family:SimSun" :class="row.class">
            <span class="spanboder">{{row.header}}</span>
            <img class="butt2" :src="imgback(row.complete === componentName,row.header === header)"></a>
          <p></p>
        </li>
        <div class="col-sm-12 col-xs-12 repair-bg">
          <div class="auto select-overspread form-horizontal repair-bg " style="padding-bottom:5px;">
            <div class="bq-parent">
              <blockquote class="blockquote">
                <p>安检上传</p>
              </blockquote>
            </div>
            <div class="panel panel-default auto repair-info-content">
              <div class="panel-body ">
                <div class="row auto">
                  <div  class="col-xs-12 col-sm-12 col-md-12 flex-between" style="margin-top: 20px;">
                    <div class="col-xs-3 col-sm-3 col-md-3">
                      <button type="button" name="button" class="col-sm-3 btn btn-primary" @click="uploadCheckPaper">
                        上传
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </ul>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import * as Util from '../Util'
import { HttpResetClass } from 'vue-client'
import co from 'co'
import $ from "jquery";
let loadParamGem = async function (self) {
  await self.$LoadParams.loadParam()
}

export default {
  title: '安检单',
  props: ['f_plan_id', 'item', 'role','parentPage','source'],
  // props: ['f_plan_id', 'role'],
  data() {
    return {
      data: {
        f_noanswer_path:'',
        f_nongasuser_path:'',
        f_devices: [],
        f_defect_content:'',
        f_recording1_path:'',
        f_visit_number:'',
        f_remark:''
      },
      imgsnum:this.$appdata.getSingleValue('安检总体照片数量') ? this.$appdata.getSingleValue('安检总体照片数量'):1, // 安检整体照片默认必须拍1张
      updateuserphone:false, //安检时是否更新用户电话
      updatemetermodel:false, //安检时是否更新表型号
      updatemeternumber:false, //安检时是否更新表号
      beforephone:'',
      isUpload:false,
      show_torepair: false,
      onlySave:true, //判断保存还是保存并上传
      livedispose:'',
      refuseinspection:'', // 拒捡拍照是否提示
      notencountered:'',  // 到访不遇拍照是否提示
      startClick:false, //开始安检按钮是否可点击
      isStrat: false, //是否开始安检
      checkResult:{},//查询结果
      newcheckResult:{},
      repairDefect : {
        result: '正常',
        data: []
      },
      rowCodata:{},
      repairers: [],
      timer: null,
      showModal: false,
      showModal2:false,
      pic_to_be_viewed: '',
      showBack:true,
      devices: [],
      f_devices : [],
      isToRepair:false,
      clickBack:true, //是否点击返回按钮
      isSafeCheckToRepair:false,//是否转维修
      Url:this.$androidUtil.getProxyUrl(),
      detail:{},
      defectDevice:{},
      user:{},
      is_has_jingweidu: this.$appdata.getSingleValue('照片水印加经纬度') || 'false',
      dispatchTypeOptions: [{label: '派发给维修员', value: '派发给维修员'},{label: '派发给站点', value: '派发给站点'}],
      selectData:{
        dispatchType:'派发给维修员',
        f_repairman:'',
        f_remarks:'',
        f_repairtype:'整改'
      },
      model: {  //转维修数据
        // 一次派单
        serviceacitivity: [{
          f_service_acitivity_type: '派单'
        }],
        f_source:'安检',
        f_service_id: '',
        f_contact_phone: '',
        f_meetunit: '',
        f_phone: '',
        f_user_name: '',
        f_address: '',
        f_repair_date: Util.toStandardTimeString(),
        f_card_id: '',
        // f_department: '', 站点选择
        f_reciever:'',
        f_remarks: '',
        f_user_type: '',
        f_area: '',
        f_unit_name:'',
        f_street: '',
        f_residential_area: '',
        f_building: '',
        f_unit: '',
        f_floor: '',
        f_room: '',
        aState: null,
        f_repairtype: '',
        f_repairitems:{},
      },
      repairitems:[],
      meading:'转站点',
      config: {
        "信息填写":{
          "checkmust":true,
          "index":1,
          "items":{
            "地址信息":{"index":1,"type":"string","readonly":false,"checkmust": true},
            "入户状态":{"index":2,"multiple":false,"type":"selector","options":[{"data":"入户","isdefault":true},{"data":"到访不遇"},{"data":"拒检"}],"checkmust":true},
            "到访不遇/拒检照片":{"index":3,"type":"picture","readonly":false,"checkmust": false,"isshow":false},
            "气表品牌":{"index":4,"type":"string","readonly":false,"checkmust": true},
            "表号":{"index":5,"type":"string","readonly":false,"checkmust": true},
            "用户姓名":{"index":6,"type":"string","readonly":false,"checkmust": false},
            "用户电话":{"index":7,"type":"string","readonly":false,"checkmust": false},
            "表具照片":{"index":8,"type":"picture","readonly":false,"checkmust": true}
          }
        },
        "其他隐患":{
          "checkmust":true,
          "index":2,
          "items":{
            "有无其他隐患":{"index":1,"multiple":false,"type":"radio","options":[{"data":"无隐患","isdefault":true},{"data":"有其他隐患","isdefault":false,"isdefect":true}],"checkmust":true}
          }
        },
        "点火":{
          "checkmust":true,
          "index":3,
          "items":{
            "检查类型":{"index":1,"multiple":false,"type":"selector","options":[{"data":"普通检查","isdefault":true},{"data":"点火检查"}],"checkmust":true},
          }
        }
      },
      isneedDate:'',
      routeShow:true,
      number:0,
      shupingshow:false,
      pipeline: {},
      details: [],
      ids: '',
      savevalid: {
        uservalid: false,
        doorvalid: true,
        changetable: false
      },
      doordetails: {},
      devicedetails: {},
      cookdetails: {},
      componentName: 'safecheck-devices-temp',
      header:'客户信息',
      tabs: [],
      faultshow:{
        number : 8
      }     // 控制 故障汇总 在 菜单里显示与否,
    }
  },
  computed: {
    actionEnabled: {
      get() {
        return this.role == 'inspect'
      }
    }
  },
  methods: {
    showmod(){
      // this.saveNoclick()
      let errString = this.errorVerify()
      if (errString) {
        console.log(errString)
        console.log('Vue.android',Vue.android)
        console.log('this.isUpload',this.isUpload)
        if (Vue.android){
          this.$showMessage(errString)
        }
        return
      }
      //清空转维修列表重新进行数据组织
      this.repairDefect = {
        result: '正常',
        data: []
      }
      this.data.f_complete = '已完成'
      this.$set('data.f_offsite_time', Util.toStandardTimeString())
      this.assemblyCodata()
      if(this.repairDefect.result=='正常'){
        this.$showMessage("未发现有选择需要转维修的隐患,请检查填写的数据。如需转维修请在处理方式中选择 '转维修' !")
        return
      }
      console.log("准备保存！")
      this.disableTimer()
      this.getEmp()
      this.showModal2=true
    },
    cancel1(){
      this.showModal2=false
      this.selectData={
        dispatchType:'派发给维修员',
        f_repairman:'',
        f_remarks:'',
        f_repairtype:'整改'
      }
    },
    getSiteRes(obj) {
      console.log('siteRes ---> ')
      console.log(obj)
      if(obj.resids[0]){
        this.selectData.f_meetunit = obj.res.join('.')
        this.selectData.f_reciever = obj.resids.join('.')
        this.selectData.f_outlets = obj.res[obj.res.length - 1]
      }else {
        this.selectData.f_meetunit = ''
        this.selectData.f_reciever = ''
        this.selectData.f_outlets = ''
      }
    },
    rectification(){
      if(this.selectData.dispatchType){
        if(this.selectData.dispatchType=='派发给站点'){
          if(!this.selectData.f_reciever){
            this.$showMessage('请选择部门！')
            return
          }
        }else{
          if(!this.selectData.f_repairman){
            this.$showMessage('请选择维修员！')
            return
          }
        }
      }else {
        this.$showMessage('请选择派发类型！')
        return
      }
      /*if(!this.selectData.f_repairtype){
        this.$showMessage('请选择报修类型！')
        return
      }*/
      //关闭录音
      this.closely(false) // 保存本地，不删除录音文件暂停录音
      let act={}
      let toRepair=''
      if(this.selectData.dispatchType=='派发给站点'){
        act={f_meetunit:this.selectData.f_meetunit,f_reciever:this.selectData.f_reciever,f_service_acitivity_type:'派单'}
        toRepair=null
      }else{
        console.log('派发给维修员---------'+this.selectData.f_repairman)
        act={f_meetunit:'',f_reciever:this.selectData.f_repairman,f_service_acitivity_type:'派单'}
        toRepair='一级派单'
      }
      let repData={
        toRepair:toRepair,
        activity:act,
        deps:Vue.user.deps,
        depids:Vue.user.depids,
        f_remarks:this.selectData.f_remarks,
        f_repairtype:this.selectData.f_repairtype,
        f_attendant: Vue.user.name,
        loginUser:{name:Vue.user.name,ename:Vue.user.id,id:Vue.user.id},
      }
      this.rowCodata.istoRepair='转维修'
      this.rowCodata.repData=repData
      console.log("当前组装好的转维修数据--"+JSON.stringify(repData))
      this.onlySave = false
      this.save()
    },
    // 获取维修员
    getEmp() {
      this.repairers=[]
      let per = {source: 'this.getRights().where(row.getType()==$user$).where(row.getAttributes().get($rolestr$).indexOf($维修员$) != -1))', userid: `${Vue.user.id}`}
      let http = new HttpResetClass()
      http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/search`, {data: per}, {resolveMsg: null, rejectMsg: null}).then((res) => {
        res.data.forEach((user)=>{
          this.repairers.push({label:user.name, value: user.name})
        })
      })
    },
    closely(isdelete){
      try {
        var startOrStopAudioClipStr;
        if (isdelete===true) {
          //tag
          startOrStopAudioClipStr= HostApp.startOrStopAudioClip("----",'停止并删除录音') //停止并删除录音
        }else {
          //tag
          startOrStopAudioClipStr= HostApp.startOrStopAudioClip("----",'停止录音') //停止录音
        }
        if (startOrStopAudioClipStr.code == 200) {
          //tag
          return true;
        }else {
          return  false;
        }
      } catch (e) {
        console.error("关闭录音方法异常")
        console.error(e)
        return false;
      }
    },
    // 录音方法
    record() {
      //tag
      let fileName
      if (!this.data.f_recording1_path) {
        fileName = Util.guid() + '.amr'
      } else {
        fileName = Util.getFileName(this.data.f_recording1_path)
      }
      //HostApp.__this__ = this
      /*调用无限制录音模块*/
      let startOrStopState = HostApp.startOrStopAudioClip(fileName,"开始录音")
      //tag
      if (startOrStopState.code == 200) {
        this.data.f_recording1_path =  "file:///storage/emulated/0/safecheck/" + fileName
        //tag
        return true;
      }else {
        return false;
      }

    },
    saveNoclick() {
      // 禁用点击事件
      $("#savebut").addClass("noclickbut");
      //tag

      // 5秒后启用点击事件
      setTimeout(function(){
        $("#savebut").removeClass("noclickbut");
      },5000);
    },
    timeSet(val){
      if (!val){
        return
      }
      let time =new Date(val).getTime()
      let time2=new Date().getTime()
      if (time2>time) {
        return true
      }
    },
    imgback(val,isheader){
      if(val && this.routeShow && isheader){
        return require('../../assets/xiangxia1.png')
      }else{
        return require('../../assets/xiangyou1.png')
      }
    },
    changediv(val){
      //tag
      return val
    },
    // 选择tab
    tabSelect (item,number) {
      this.header = item.header
      if(this.number == number && !this.routeShow ){
        this.routeShow = true
      }else if(this.number == number && this.routeShow){
        this.routeShow = false
      }else if(this.number != item.complete){
        this.routeShow = true
      }
      this.number = number
      this.componentName = item.complete
      if(item.complete == 'safecheck-devices-temp'){
        if(this.data['device'+item.number].length == 0){
          this.data['device' + item.number].push({})
        }
        let idx=this.data['device' + item.number].length - 1
        let itemprops = {
          config:this.config,
          device:this.devices[item.number-1],
          idx:idx,
          role:'inspect'
        }
        if(this.routeShow){
          this.$goto(item.complete, itemprops, 'repair')
        }
      }else{
        if(this.routeShow){
          this.$goto(item.complete, {userinfo:this.data}, 'repair')
        }
      }
      this.shupingshow = true
    },
    sortDetails(){
      for (let i = 0; i < this.details.length; i++) {
        if (this.details[i].details.length) {
          for (let j = 0; j < this.details[i].details.length; j++) {
            if (this.details[i].details[j].f_type === 'a') {
              this.doordetails = {details: this.details[i].details}
              break
            }
            if (this.details[i].details[j].f_type === 'b') {
              this.devicedetails = {details: this.details[i].details}
              break
            }
            if (this.details[i].details[j].f_type === 'c') {
              this.cookdetails = {details: this.details[i].details}
              break
            }
          }
        }
      }
    },
    // 复制数据
    back () {
      let _this = this
      if(this.issee){
        _this.$back()
        return
      }
      this.$showMessage('所填写内容将不可恢复！', ['confirm', 'cancel']).then((res) => {
        if (res === 'confirm') {
          this.closely()
          _this.$back()
        }
      })
    },
    confirm(){
      this.$dispatch('confirm')
    },
    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() ? '已修' : '在修'
    },
    errorVerify() {
      if(this.data.f_entry_status){
        if(['到访不遇', '拒检'].includes(this.data.f_entry_status)) {
          if(!this.data.f_noanswer_path && !this.data.f_nongasuser_path){
            return "到访不遇/拒检照片未拍摄"
          }
          return
        }
      }else{
        return "入户状态未选择"
      }
      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 (it == this.data[device][item].f_items[i].f_item_name) {
                      let check=false
                      if (!this.data[device][item].f_items[i].f_item_value){
                        check=true
                      }else if (Array.isArray(this.data[device][item].f_items[i].f_item_value)){
                        if (this.data[device][item].f_items[i].f_item_value.length==0){
                          check=true
                        }
                      }

                      if(this.config[dev].items[it].type=='picture' && this.config[dev].items[it].checkmust == true && !this.data[device][item].f_items[i].f_path){
                        return dev + (this.data[device].indexOf(this.data[device][item]) + 1) + this.data[device][item].f_items[i].f_item_name + "未检查"
                      }
                      if (this.config[dev].items[it].type !='picture' && this.config[dev].items[it].checkmust == true && check) {
                        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' || this.data[device][item].f_items[i].type == 'radio') {
                    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 + "选中必须拍照"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    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")) {
          //tag)
          let hasOther = ''
          let otherValue = null
          for (let item in codata[device]) {
            if(typeof codata[device][item]=='function'){
              continue
            }
            codata[device][item].f_create_time = Util.toStandardTimeString()
            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
            //tag
            //tag)
            //tag)
            if(item == 'sum' || item == 'removeEmpty'){
              continue
            }
            for (let i = 0; i < codata[device][item].f_items.length ; i++) {
              //tag
              if(i == 'sum' || i == 'removeEmpty'){
                continue
              }
              //tag)
              var items = codata[device][item].f_items[i]
              items.f_create_time = Util.toStandardTimeString()
              //tag)
              items.f_item_lists = []
              //tag)
              // //tag)
              // //tag} name => ${JSON.stringify(items.f_item_name)} value => ${JSON.stringify(items.f_item_value)}`)
              // console.log(`f_is_defect => ${this.config[codata[device][item]
              //     .f_device_type]
              //     .items[items.f_item_name]
              //     .options
              //     .find((option)=>option.data === items.f_item_value)
              //     .map((option)=>option.f_is_defect)}`)
              // if (items.f_is_defect && (items.f_is_defect == true || items.f_is_defect == 'true')) {
              //     //tag
              //     checkResults.result = '有隐患'
              //     //tag)
              //     //tag)
              //     // this.$set('checkResult.' + items.f_item_name, items.f_item_value)
              //       this.checkResult[items.f_item_name] = items.f_item_value
              //     //tag)
              //     // this.$set('checkResultsss.' + items.f_item_name, `${f_device_type}${items.f_item_value}`)
              //     // //tag)
              // }
              if (items.type == 'selector') {
                items.selected = []
              } else if (items.type == 'inputSelector') {
                items.selected = ''
              }
              //遍历配置项 将所选隐患项的配置信息放入保存的数据中
              let f_is_defect   //是否是隐患
              let f_defect_level   //是否是隐患
              let f_item_name = items.f_item_name
              let f_item_value
              let f_is_eliminate //隐患是否消除
              let f_meternumber = ''
              let f_user_defects = [] // 用户所有隐患
              //tag
              //tag
              if (items.type == 'selector' || items.type == 'checkbox' || items.type == 'radio') {
                for (let i in items.f_item_value) {
                  if(typeof items.f_item_value[i]=='function'){
                    continue
                  }
                  let configItems = this.config[codata[device][item].f_device_type].items[f_item_name]
                  //tag)
                  for (let k in configItems.options) {
                    if(typeof configItems.options[k]=='function'){
                      continue
                    }
                    //tag)
                    if (items.f_item_value[i] === configItems.options[k].data) {

                      f_is_defect = configItems.options[k].isdefect
                      f_item_value = items.f_item_value[i]
                      f_defect_level = configItems.options[k].level

                      //tag
                      //tag
                      //tag

                      if (f_is_defect) {
                        if (checkResults.result !== '有隐患') {
                          checkResults.result = '有隐患'
                        }
                        console.log('items'+items)
                        if(items.f_deal_dispose=='报修'){
                          console.log("检测到需要转维修++++++++++++")
                          this.repairDefect.result='未处理'
                          this.repairDefect.data.push(`${f_item_name} : ${f_item_value}`)
                        }
                        if (!this.checkResult.hasOwnProperty(f_device_type+'-'+f_item_name)) {
                          //tag
                          this.checkResult[f_device_type+'-'+f_item_name] = []
                        }

                        //tag
                        this.checkResult[f_device_type+'-'+f_item_name].push(f_item_value)

                      }

                      let items_list = {
                        f_is_defect: f_is_defect,
                        f_item_value: f_item_value,
                        f_defect_level: f_defect_level,
                        f_is_eliminate: null,
                        f_create_time: Util.toStandardTimeString()
                      }
                      if (!items.f_item_lists) {
                        //tag
                        items.f_item_lists = []
                        //tag)
                        if (JSON.stringify(items_list) !== '{}') {
                          //tag
                          items.f_item_lists.push(items_list)
                        }
                      } else {
                        //tag)
                        if (JSON.stringify(items_list) !== '{}') {
                          //tag
                          items.f_item_lists.push(items_list)
                        }
                      }
                    }
                  }
                }
              } else {
                let configItems = this.config[codata[device][item].f_device_type].items[items.f_item_name]
                f_is_defect = items.f_is_defect
                f_defect_level = items.level
                f_item_value = items.f_item_value
                let items_list = {
                  f_is_defect: f_is_defect,
                  f_item_value: f_item_value,
                  f_defect_level: f_defect_level,
                  f_create_time: Util.toStandardTimeString()
                }
                if (f_is_defect && f_item_value) {
                  items.f_is_defect = true
                  if (checkResults.result !== '有隐患') {
                    checkResults.result = '有隐患'
                  }
                  if (!this.checkResult.hasOwnProperty(items.f_item_name)) {
                    //tag
                    this.checkResult[items.f_item_name] = []
                  }

                  //tag
                  this.checkResult[items.f_item_name].push(f_item_value)

                }
                //tag)
                //tag)
                if (!items.f_item_lists) {
                  //tag
                  items.f_item_lists = []
                  if (JSON.stringify(items_list) != '{}') {
                    //tag
                    items.f_item_lists.push(items_list)
                  }
                } else {
                  // items.f_item_lists[0].f_item_value = f_item_value
                  if (JSON.stringify(items_list) != '{}') {
                    //tag
                    //tag)
                    //tag)
                    //tag
                    items.f_item_lists.push(items_list)
                  }
                }
              }
              if (hasOther !== '' && otherValue !== null) {
                //tag
                this.checkResult[hasOther].push(otherValue)
                hasOther = ''
                otherValue = null
              }
              items.f_item_value = ''
            }
            //tag)
            this.f_devices.push(codata[device][item])
          }
        }
      }
      if (this.checkResult) {
        for (let key in this.checkResult) {
          if(typeof this.checkResult[key]=='function'){
            continue
          }
          // 上次安检结果数据组织
          //tag
          //tag
          let temp = {}
          temp[key] = this.checkResult[key].join(',')
          checkResults.data.push(temp)
          // this.newcheckResult[key] = this.checkResult[key]
          // checkResults.data.push(this.newcheckResult)
          //tag)
          // this.newcheckResult = {}
        }
        this.checkResult = {}
      }
      if (checkResults.data.length > 0) {
        let msg = ''
        for (let a = 0; a < checkResults.data.length; a++) {
          for (let datumKey in checkResults.data[a]) {
            msg += datumKey + ':' + checkResults.data[a][datumKey] + ';'
          }
        }
        this.data.f_defect_text = msg
        codata.f_defect_text = msg
      }
      codata.f_defect_content = JSON.stringify(checkResults)
      this.data.f_defect_content = JSON.stringify(checkResults)
      //tag
      return codata
    },
    uploadCheckPaper(){
      this.saveNoclick()
      this.closely(false) // 保存本地，不删除录音文件停止录音
      let errString = this.errorVerify()
      if (errString) {
        this.disableTimer()
        this.$showMessage(errString)
        return
      } else {
        this.$set('data.f_offsite_time', Util.toStandardTimeString())
        this.$set('data.f_upload_time', Util.toStandardTimeString())
        this.$set('data.f_upload_date', Util.toStandardTimeString())
        this.data.f_complete = '已完成'
        this.disableTimer()
      }
      this.onlySave = false
      this.assemblyCodata()
      let res =  this.save()
    },
    //将数据组装提出
    assemblyCodata(){
      let codata = this.getAllDefect()
      console.log(`codata类型 开始组装codeta数据-->${typeof codata}`)
      console.log(`codata内容-->${JSON.stringify(codata)}`)
      for (let key in codata) {
        if (key.startsWith("device")) {
          console.log('this.data.' + key + JSON.stringify(codata[key]))
          codata[key] = []
        }
      }
      codata.f_devices = this.f_devices
      this.rowCodata=codata
    },
    save() {
      let codata = this.getAllDefect()
      for (let key in codata){
        if(key.startsWith("device")){
          codata[key] = []
        }
      }
      codata.f_devices = this.f_devices
      this.rowCodata = codata
      let param = {
        f_check_item_id: this.data.f_check_item_id,
        f_checker_id: this.data.f_checker_id,
        // row: codata
        row: this.rowCodata
      }
      //tag)
      let paramStr = JSON.stringify(param)
      // 多长截断一次
      let subLength = 800
      for (let i = 0; i < paramStr.length; i += subLength) {
        HostApp.param_cache(paramStr.substr(i, subLength))
      }
      HostApp.__this__ = this
      HostApp.syncLogic({
        // logic别名，key必须为logic
        'logic': '上传安检信息',
        // 回调执行方法名，key必须为callback
        'callback': 'javascript:HostApp.__this__.uploadCallBack()',
        // 固定key，代表是否将logic执行结果作为参数传入回调方法，1代表true，0代表false，
        // 执行回调方法传入key为backresult
        // 如需额外拼接参数，写在logic返回值的params，例如xxlogic返回:{"params": "success"}
        'backresult': 1
      })
    },
    runSyncLogic(logic,callback,backresult){
      HostApp.runSyncLogic({
        'logic': logic,
        'callback': callback,
        'backresult':backresult
      })
    },
    logicWithHint(logic,data,callback,backresult){
      HostApp.logicWithHint({
        'logic': logic,
        'callback': callback,
        'data': data,
        'backresult':backresult
      })
    },
    uploadCallBack(jo){
      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
          }
        }
      }
      if(jo.state == 'ok'){
        let res = JSON.parse(jo.result)
        //tag)
        //tag)
        if(res.code == 200){
          this.$set('data.f_paper_id', res.id)
          this.isStrat=false
          if(url != ""){
            this.$resetpost(`${url}`,{data:WxResult})
          }
          if(this.isToRepair){
            for (let device in this.data){
              if(device.startsWith("device")){
                this.data[device] = []
                if(res.data.length > 0){
                  for(let i in res.data[0].f_devices){
                    if(this.data[device].length > 0){
                      if(this.data[device][0].f_device_type == res.data[0].f_devices[i].f_device_type){
                        this.data[device].push(res.data[0].f_devices[i])
                        res.data[0].f_devices.splice(i,1)
                      }
                    }else{
                      this.data[device].push(res.data[0].f_devices[i])
                      res.data[0].f_devices.splice(i,1)
                    }
                  }
                }
              }
            }
            this.todo()
          }else{
            this.$showMessage('上传成功!')
            //tag
            this.$dispatch('confirm')
            // this.$back()
          }
        }else if(res.code == 309){
          this.$showMessage('该安检单已作废!')
          //tag
          this.$dispatch('confirm')
        }else if(res.code == 710){
          this.$showMessage('上传照片失败,请检查网络是否正常！'+res.msg)
          return
        }else if(res.code == 711){
          this.$showMessage('该安检单已被管理员调整，请联系管理员!')
          return
        }else if(res.code == 712){
          this.$showMessage('网络异常，请重新上传，多次上传失败请联系管理员!')
          return
        }
        else{
          this.$showMessage('上传失败！')
        }
      }else {
        this.$showMessage('网络异常,上传失败！')
      }
      this.onlySave = true
    },
    safecheckToRepairCallBack(jo){
      //获取微信推送路径
      if(jo.state == 'ok'){
        let res = JSON.parse(jo.result)
        //tag)
        if(res.code == 200){
          //tag
          if(res.data.code == 200){
            this.$showMessage('上传并转维修成功！')
          }else{
            this.$showMessage('上传并转维修成功，回写安检单失败！')
          }
          this.$dispatch('confirm')
          // this.$back()
        }else{
          this.$showMessage('上传失败！')
          this.onlySave = true
        }
      }else{
        this.$showMessage('网络异常,上传失败！')
        this.onlySave = true
      }
    },
    todo(){
      let gen = getRepairParam(this)
      co(gen)
    },
    undo(){
      this.showCheckToRepair = !this.showCheckToRepair
      this.model.serviceacitivity[0].f_reciever = ''
      this.model.serviceacitivity[0].f_meetunit = ''
      this.model.f_repairtype = ''
      this.meading = '转站点'
    },
    disableTimer() {
      if(this.timer) {
        window.clearTimeout(this.timer)
        this.timer = null
      }
    },
    S4() {
      return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    },
    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;
    },
    init () {
      this.data.isupdateplanitem = this.$appdata.getSingleValue('在线安检回更有计划') ? this.$appdata.getSingleValue('在线安检回更有计划') : 'false'
      this.data.f_SafeToRepair_id = ''
      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.data.f_check_plan_id = this.f_plan_id
      this.data.f_checker_id = Vue.user.id
      this.data.f_checker_name = Vue.user.name
      this.data.f_check_type = ''
      this.data.f_safecheck_type = ''
      this.data.f_subcompany = ''
      this.data.f_approved = ''
      this.data.f_repair_approved = ''
      this.data.f_no_checkplan = '无计划安检'
      this.data.f_approved = ''
      this.data.f_filialeid = Vue.user.orgid
      this.data.f_orgstr = ''
      this.data.version = ''
      this.data.f_check_version=''
      this.$set('data.f_meters', '')
      this.$set('data.f_userinfo_code', '')
      this.$set('data.f_entry_status', '入户')
      this.$set('data.f_safe_type', '已挂表未办卡安检')
      this.$set('data.f_usegas', '未使用')
      this.$set('data.f_state','')
      this.$set('data.f_source', this.source?this.source:'安检')
      this.$set('data.f_other_checker_name', '')
      this.$set('data.f_user_name', '')
      this.$set('data.f_onsite_time', Util.toStandardTimeString())
      this.$set('data.f_rent_phone', '')
      this.$set('data.f_user_phone', '')
      this.$set('data.f_userinfoid', '')
      this.$set('data.f_address', '')
      this.$set('data.f_card_id', '')
      this.$set('data.f_slice_area', '')
      this.$set('data.f_recheck_id', '')
      this.$set('rowCodata.f_recheck_id', '')
      this.$set('data.f_street','')
      this.$set('data.f_room', '')
      this.$set('data.f_building', '')
      this.$set('data.f_unit', '')
      this.$set('data.f_floor', '')
      this.$set('data.f_residential_area' , '')
      this.$set('data.f_idnumber', '')
      this.$set('data.f_comments', '')
      this.$set('data.f_userproperties', '')
      this.$set('data.f_client_evaluation', '满意')
      this.$set('data.f_userfiles_id', '')
      this.$set('data.f_valve_state', '')
      this.$set('data.f_off_valve_reason', '')
      this.$set('data.f_gas_guidelines', true)
      this.$set('data.f_safety_warning', true)
      this.$set('data.f_gas_manual', true)
      this.$set('data.f_no_gas_device', false)
      this.$set('data.f_close_valve', false)
      this.$set('data.f_unload_battery', false)
      this.data.f_check_item_id = this.S4() + "" + this.S4() + "" + this.S4() + "" + this.S4() + "" + this.S4() + "" + this.S4() + "" + this.S4() + "" + this.S4()
    }
  },
  watch: {
    'row' () {
      //tag
      this.copy()
    }
  },
  ready () {
    HostApp.startOrStopAudioClip("----",'停止并删除录音')
    this.tab=[]
    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, [])
      this.tabs[n-1] = {
        header: i,
        complete: 'safecheck-devices-temp',
        class: 'repair-details-class',
        number: n
      }
    }
    this.tabs.push({
      header: '拍照签名',complete:'paper-feedback-temp', class: 'outlay-class', props: null
    })
    this.faultshow.number = this.tabs.length
    this.init()
    this.$showMessage("为了保证服务质量，将会被全程录音！")
    let resse = this.record()
    this.tabSelect({
      "header": "信息填写",
      "complete": "safecheck-devices-temp",
      "class": "repair-details-class",
      "number": 1
    },0)
  },
  events: {
    'tijiao': function () {
      this.confirm()
    }
  }
}
</script>
<style lang="less">
@import "../../../src/bootstrap/less/variables.less";
.noclickbut {
  pointer-events: none;
}
.tab-befor-img (@url) {
  content: '';
  background-image: url("@{url}");
  background-size: 20px;
  display: inline-block;
  margin-right: 8px;
  margin-top: 0.3em;
  height: 1.3em;
  width: 1.3em;
  vertical-align: -35%;
}

@media screen and (min-width: 768px) {
  .android-repair-order > div > ul a {
    font-size: @font-size-h2;
    margin: 0.3em 0;
  }
}
.repair-details-class{
  &::before {
    .tab-befor-img("../../assets/huneiweixiu1.png");
  }
}
.repair-info-class {
  &::before {
    .tab-befor-img("../../assets/baoxiuxinxi1.png");
  }
}
.repair-user-info-class {
  &::before {
    .tab-befor-img("../../assets/jibenxinxi1.png")
  }
}

.door-service-class {
  &::before {
    .tab-befor-img("../../assets/huneiweixiu1.png")
  }
}

.pipeline-class {
  &::before {
    .tab-befor-img("../../assets/guandao1.png")
  }
}

.device-service-class {
  &::before {
    .tab-befor-img("../../assets/shebeiweixiu1.png")
  }
}

.trouble-removal-class {
  &::before {
    .tab-befor-img("../../assets/shiguchuli.png")
  }
}

.cooking-utensils-class {
  &::before {
    .tab-befor-img("../../assets/zaoju1.png")
  }
}

.outlay-class {
  &::before {
    .tab-befor-img("../../assets/feiyong1.png")
  }
}

.fault-all-class {
  &::before {
    .tab-befor-img("../../assets/guzhanghuizong1.png")
  }
}
.photo-write-class {
  &::before {
    .tab-befor-img("../../assets/zaoju.png")
  }
}
.delay-apply-class {
  &::before {
    .tab-befor-img("../../assets/yonghubaoxiu.png")
  }
}

.repair-back-class {
  &::before {
    .tab-befor-img("../../assets/fanhui.png")
  }
}
.butt2 {
  display: inline;
  float: right;
  width: 10px;
  text-align: center;
  align-items:center;
  position: absolute;
  top:50%;

  left:90%;
  transform: translate(-50%,-50%);
}
.linesty{
  display: inline-block;
  height:1px;
  width:100%;
  background:#d0d0d0;
  overflow:hidden;
  vertical-align: middle;
}
.spanboder{
  border-bottom:2px solid #499edf;
  padding-bottom: 8px
}
.app-botton {
  position:fixed;
  background: #87b2dd;
  right:8px;
  color: #FFF;
  padding: 8px;
  text-align: center;
  font-size: 1.2em;
  z-index: 10;
  opacity:0.5;
  bottom: 50px;
  margin-top: -10px;
  height: 40px;
}
.android-repair-order > div > ul a {
  font-size: 12px;
  color: #333333;
  padding: 13px 16px;
}
</style>
