<template>
  <div class="auto">
      <div style="width: 100%;height: 36px;background-color: #f1f8ff">
        <div style="width: 8px;height: 100%;background-color: #6aa6e2;margin-right: 20px;float: left"></div>
        <div style="width: auto;height:100%;float: left;"><p class="title-font" style="margin-top: 5px">拍照选项：</p></div>
      </div>
      <form novalidate class="form-horizontal" style="width: 100%;margin: auto">
        <div class="form-group col-sm-12 col-xs-12 col-md-12 info" style="width:100%;">
          <div class="text-center">
            <label class="font">检查说明：</label>
          </div>
          <div class="col-md-12 col-sm-12 col-xs-12" style="width: 90%;margin-left: 5px">
            <ol class="showInput" style="width: 90%;margin-left: 40px">
              <li>已对客户燃气设施进行了安全检查</li>
              <li>已对客户进行了安全知识宣传，并发放宣传资料</li>
              <li>已对客户的资料进行了登记</li>
              <li>已对违章及隐患之客户下发隐患整改告知书</li>
            </ol>
          </div>
        </div>
        <div class="form-group col-xs-12 col-sm-12">
          <span class="col-md-3 col-sm-4 col-xs-4">安检告知书单号:</span>
          <div class="col-md-9 col-sm-8 col-xs-8">
            <input  style="width: 100%" type="number" v-model="paper.f_notification_number" class=" form-control text-center time-input" disabled/>
          </div>
        </div>
        <div class="form-group col-xs-12 col-sm-12">
          <span class="col-md-3 col-sm-4 col-xs-4">备注:</span>
          <div class="col-md-9 col-sm-8 col-xs-8">
            <input  style="width: 100%" type="text" v-model="paper.f_remark" class=" form-control text-center time-input" disabled/>
          </div>
        </div>
        <div class="col-md-12 col-sm-12 col-xs-12" v-if="paper.f_no_checkplan ==  '重点用户跟进单'">
          <label class="text-left font col-md-12 col-sm-12 col-xs-12">户内情况</label>
          <div class="col-md-12 col-sm-12 col-xs-12">
            <textarea  style="width: 100%" v-model="paper.f_indoor_circumstance" class=" form-control time-input"></textarea>
          </div>
        </div>
        <div style="width: 95%;margin: auto" >
          <div class="flex panel panel-default well" style="width: 100%;display: inline-block">
            <div class="panel-body bg-info">
              <div class="text-center">
                <label class="control-label" style="font-weight: bold">隐患结果统计</label>
              </div>
              <ul class="list-unstyled panel-ul">
                <li >
                  <div partial class="panel panel-default well" style="padding: 0px">
                    <div class="panel-body inbg">
                      <p style="margin-bottom: 5px">
                   <span class="li-font">
                       安检结果:{{deviceresult}}
                      </span>
                      </p>
                      <div class="row col-xs-12 col-sm-12 col-md-12 form-group" v-for="deviceCollect in deviceCollects">
                        <div class="row col-xs-12 col-sm-12 col-md-12" >
                          <p class="li-font">
                            {{deviceCollect.name}}:{{deviceCollect.deviceInfos}}&nbsp;&nbsp;&nbsp;
                          </p>
                        </div>
                        <!--<div class="row col-xs-12 col-sm-6 col-md-6" v-if="deviceCollect.value == '有隐患'">-->
                        <!--<lable>-->
                        <!--隐患:-->
                        <!--</lable>-->
                        <!--<span class="li-font" v-for="val in deviceCollect.devices">-->
                        <!--{{val}}&nbsp;&nbsp;&nbsp;-->
                        <!--</span>-->
                        <!--</div>-->
                      </div>
                    </div>
                  </div>
                  <partial name="default"></partial>
                </li>
              </ul>

            </div>
          </div>


        </div>
        <div class="form-group col-xs-12 col-sm-12">
          <label class="text-left font">隐患照片</label>

          <div class="auto">
            <div class="panel" style="padding: 10px 10px 5px 10px;">
              <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                <div class="row" style="height: 240px;overflow: scroll;top: 1px" >
                  <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 35px" v-for="img in picture">
                    <img-self :src="img.f_path" :alt="img.name" :width="140" :height="170"> </img-self>
<!--                    <img :src="img.f_path" :alt="img.name" :width="140" :height="170" @click="open_f('picture')"></img>-->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="form-group col-xs-12 col-sm-12" style="margin-top: 10px" v-if="showNew">
          <div class="auto" style="width: 100%;float: left;" >
            <label class="text-left font">总体安检照片</label>
            <div class="auto">
              <div class="panel">
                <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                  <div class="row" style="height: 240px;overflow: scroll;top: 1px">
                    <div class="row">
                      <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 10px;margin-right: 30px" v-for="(index,img) in paper.f_all_imgs">
<!--                        <img :src="img.f_overall_path" alt="总体安检照片" @click="open_f('paperAllImgs')" :width="150" :height="200"></img>-->
                        <img-self :src="img.f_overall_path" alt="总体安检照片" :width="150" :height="200"></img-self>
                        <!--<img src="../../assets/remove.png" @click="delfile('f_overall_path', img.f_overall_path,index)" class="imgs" style="width: 30px;" alt="">-->
                      </div>
                    </div>
                  </div>
                  <div class="row text-right div-photo">
                    <!--<button type="button" name="button" class="btn btn-primary btn-photo" @click="takePic('f_overall_path', '总体安检照片1')">拍照</button>-->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-group col-xs-12 col-sm-12" style="margin-top: 10px" v-if="showOld">
          <div class="auto" style="width: 100%;float: left;" >
            <label class="text-left font">总体安检照片</label>
            <div class="auto">
              <div class="panel">
                <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                  <div class="row" style="height: 240px;overflow: scroll;top: 1px">
                    <div class="row">
                      <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 10px;margin-right: 30px" v-for="(index,img) in paper.f_all_imgs">
                        <img-self :src='"rs/getImg/readBlob?id="+img.f_blob_id' alt="总体安检照片"  :width="150" :height="200"></img-self>
<!--                        <img :src='"rs/getImg/readBlob?id="+img.f_blob_id' alt="总体安检照片" @click="open_f('paperAllImgs')"  :width="150" :height="200"></img>-->
                        <!--<img src="../../assets/remove.png" @click="delfile('f_overall_path', img.f_overall_path,index)" class="imgs" style="width: 30px;" alt="">-->
                      </div>
                    </div>
                  </div>
                  <div class="row text-right div-photo">
                    <!--<button type="button" name="button" class="btn btn-primary btn-photo" @click="takePic('f_overall_path', '总体安检照片1')">拍照</button>-->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-group col-sm-12" v-if="showNewest">
          <label class="text-left font">总体安检照片</label>
          <div class="auto">
            <div class="panel">
              <div class="panel-body panel-self col-xs-12 col-sm-12" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                <div class="row col-xs-12 col-sm-12 col-md-12" style="height: 240px;overflow: scroll;top: 1px" >
                  <div class="col-xs-4 col-sm-3 col-md-2 " v-for="(index,img) in paper.f_all_imgs">
                    <div class="panel-self" style="margin-bottom: 35px" v-if="img.title != '其他'" >
                      <div id='img'>
<!--                        <img :src="img.f_overall_path" :alt="总体安检照片" @click="open_f('paperAllImgs')" :width="140" :height="170"></img>-->
                        <img-self :src="img.f_overall_path" :alt="总体安检照片" :width="140" :height="170"></img-self>
                      </div>
                      <!--<img src="../assets/cs0.png" @click="delfile('f_overall_path', img.f_overall_pa                 th,index)" style="width: 140px;height:170px" alt="">-->
                      <div class="row col-xs-12 col-sm-12 col-md-12 text-center div-photo1">
                        <span>{{img.title}}</span>
                        <!--<button type="button" name="button" class="btn btn-primary btn-photo" @click="takePic('f_overall_path', '总体安检照片1')">拍照</button>-->
                        <!--&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../../assets/remove.png" :class="style__" @click="delfile('f_overall_path', img.f_overall_path)" style="width: 25%;"></img>-->
                      </div>
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="form-group col-sm-12" v-if="showNewest">
          <label class="text-left font">总体安检其他照片</label>
          <div class="auto">
            <div class="panel" style="padding: 10px 10px 5px 10px;">
              <div class="panel-body panel-self col-xs-12 col-sm-12" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                <div class="row col-xs-12 col-sm-12 col-md-6" style="height: 240px;overflow: scroll;top: 1px" >
                  <div style="height: auto" v-for="(index,img) in paper.f_all_imgs">
                    <div class="col-xs-4 col-sm-3 col-md-2" v-if="img.title == '其他'" style="margin-bottom: 35px" >
                      <img-self :src="img.f_overall_path" alt="总体安检照片" :width="140" :height="170"></img-self>
<!--                      <img :src="img.f_overall_path" @click="open_f('paperAllImgs')" alt="总体安检照片" :width="140" :height="170"></img>-->
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      <div class="form-group col-xs-12 col-sm-12" style="margin-top: 20px">
        <label class="text-left font">用户签名</label>
        <div class="auto">
          <div class="panel">
            <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
              <div class="row" style="height: 240px;overflow: scroll;top: 1px">
                <div class="col-sm-4">
                  <img-self :src="img.f_sign_path"  :width="200" :height="150"></img-self>
<!--                  <img :class="style__" :src="paper.f_sign_path"  :width="200" :height="150"  @click="open_f('paper.f_sign_path')" />-->
                </div>
              </div>
              <!--<div class="row text-right div-photo">-->
                <!--&lt;!&ndash;<button type="button" name="button" class="btn btn-primary btn-photo" @click="sign">签名</button>&ndash;&gt;-->
              <!--</div>-->
            </div>
          </div>
        </div>
      </div>

      <div class="form-group col-md-12 col-sm-12 col-xs-12">
        <div  class="form-group col-md-12 col-sm-12 col-xs-12">
          <input type="checkbox" v-model="paper.f_defect_notified" class="showInput" disabled />安检通知书/隐患整改通知书
        </div>
        <div class="form-group col-md-12 col-sm-12 col-xs-12" v-if="paper.f_defect_notified">
          <div  class="form-group col-md-12 col-sm-12 col-xs-12">
            <button type="button" @click="print()">打印隐患整改单</button>
          </div>
          <div  class="form-group col-md-12 col-sm-12 col-xs-12">
            <label class="text-left font">安检通知书/隐患整改通知书照片(要求能清晰反应安检通知单和用户签字内容)：</label>
            <div class="auto" >
              <div class="panel" style="padding: 10px 10px 5px 10px;">
                <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
                  <div class="row" style="height: 240px;overflow: scroll;top: 1px">
                    <div class="col-sm-4">
                      <img-self :src="paper.f_notified_path" alt="安检通知书/隐患整改通知书照片" width="150" height="200"></img-self>
<!--                      <img  :src="paper.f_notified_path" alt="安检通知书/隐患整改通知书照片"   @click="open_f('paper.f_notified_path')"  width="150" height="200"></img>-->
                    </div>
                  </div>
                  <!--<div class="row text-right div-photo">-->
                    <!--<button type="button" name="button" class="btn btn-primary btn-photo" @click="takePic('f_notified_path', '安检通知书/隐患整改通知书照片')">拍照</button>-->
                    <!--&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../assets/remove.png" :class="style__"  @click="delfile('f_notified_path', this.paper.f_notified_path)" style="width: 25%;"></img>-->
                  <!--</div>-->
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
          <span class="col-md-3 col-sm-4 col-xs-4">安检人员</span>
          <div class="col-md-9 col-sm-8 col-xs-8">
            <input style="width: 100%" v-model="paper.f_order_checker_name" class=" form-control text-center time-input" disabled>
          </div>
        </div>
        <div class="form-group" v-if="paper.f_reson"><!-- TODO 显示条件应为存在需要转维修的隐患 -->
          <span class="col-md-3 col-sm-4 col-xs-4">不转维修的理由:</span>
          <div class="col-md-9 col-sm-8 col-xs-8">
            <input  style="width: 100%" type="text" v-model="paper.f_reson" class=" form-control text-center time-input" disabled />
          </div>
        </div>
        <div class="form-group col-md-12 col-sm-12 col-xs-12">
          <div class="row">
            <label class="text-left">请对我们的服务做出评价：</label>
          </div>
          <div class="col-xs-4 col-sm-4"  v-for="item in radios">
            <input v-model="paper.f_client_evaluation" :value="item.label"  :checked='item.isChecked'  @click="check(item.value)" type="radio" disabled>{{item.label}}
          </div>
        </div>
<!--        <div class="form-group col-md-12 col-sm-12 col-xs-12" v-if="paper.f_recording1_path">
          <label class="text-left font">反馈录音: {{paper.f_recording1_path}}</label>
          <div class="col-md-12 col-sm-12 col-xs-12">
            <div v-if="isLoading" class="text-center">
              <p>正在加载音频，请稍候...</p>
              <div class="progress">
                <div class="progress-bar progress-bar-striped active" role="progressbar" :style="{ width: loadingProgress + '%' }"></div>
              </div>
            </div>
            <div v-else-if="isPlaying" class="audio-player">
              <div class="btn-group">
                <button class="btn btn-primary" @click="togglePlay">
                  <i class="glyphicon" :class="isPaused ? 'glyphicon-play' : 'glyphicon-pause'"></i>
                  {{isPaused ? '继续' : '暂停'}}
                </button>
                <button class="btn btn-default" @click="stopPlay">
                  <i class="glyphicon glyphicon-stop"></i> 停止
                </button>
              </div>
              <div class="progress" style="margin-top: 10px;">
                <div class="progress-bar" role="progressbar" :style="{ width: playProgress + '%' }"></div>
              </div>
              <div class="text-muted">
                <small>{{formatTime(currentTime)}} / {{formatTime(duration)}}</small>
              </div>
            </div>
            <div v-else>
              <button class="btn btn-primary" @click="playAMR" :disabled="isLoading">
                <i class="glyphicon glyphicon-play"></i> 播放录音
              </button>
            </div>
            <div v-if="playError" class="text-danger" style="margin-top: 10px;">
              <p>音频播放失败，请尝试下载后播放: <a :href="paper.f_recording1_path" download>下载录音</a></p>
            </div>
          </div>
        </div>-->
        <div class="form-group col-md-12 col-sm-12 col-xs-12" >
          <div class="row col-xs-12 col-sm-12 col-md-12">
            <label class="text-left" >是否偷盗气用户：</label>
          </div>
          <div class="col-xs-4 col-sm-4 col-sm-4"  v-for="item in openRadioss">
            <input v-model="paper.f_promise_user" :value="item.label"  :checked='item.isChecked'  @click="checkOpens(item.value)" type="radio" disabled>
            <label >{{item.label}}</label>
          </div>
        </div>
        <div class="form-group col-md-12 col-sm-12 col-xs-12" v-if="paper.f_no_checkplan == '预约开户单'">
          <div class="row col-xs-12 col-sm-12 col-md-12">
            <label class="text-left" style="color: red">是否同意开户：</label>
          </div>
          <div class="col-xs-4 col-sm-4 col-sm-4"  v-for="item in openRadios">
            <input v-model="paper.f_allow_open" :value="item.label"  :checked='item.isChecked'  @click="checkOpen(item.value)" type="radio" disabled>
            <label style="color: red">{{item.label}}</label>
          </div>
        </div>
      </div>
    </form>

  </div>
  <image-viewer :src="paperImgs" :show="showpaperImg" :linenumber="linenumber" @clone_f="clone_p" alt="安检总体图片"></image-viewer>
</template>

<script>
  import Vue from 'vue'
  import * as Util from '../Util'
  import { HttpResetClass } from 'vue-client'
  import RadioGroup from 'vue-client/src/vue-strap/src/radioGroup'
  import Radio from 'vue-client/src/vue-strap/src/radioBtn'
  import co from 'co'
  // 导入 BenzAMRRecorder
  import BenzAMRRecorder from 'benz-amr-recorder'

  let getRepairParam = function * (self){
    let data = {
      model: self.model, loginUser: {
        name: self.role == 'view'?self.$login.f.name:Vue.user.name,
        ename: self.role == 'view'?self.$login.f.ename:Vue.user.ename
      }, user: self.user, callObj: self.callObj
    }
    if(self.meading == '转维修员'){
      data.toRepair = '一级派单'
    }
    data.model.f_attendant = data.loginUser.name
    console.log('===================')
    console.log(data)
    let res
    let errString = self.$parent.errorVerify()
    if(errString){
      console.log(errString)
      if (Vue.android)
        self.undo()
      this.$showMessage(errString)
      return
    } else {
      if(self.role == 'inspect'){
        if(self.meading == '转维修员' && (self.model.serviceacitivity[0].f_reciever == '' || self.model.serviceacitivity[0].f_reciever == undefined)){
          this.$showMessage("请选择维修员!")
          return
        }
        if(self.meading == '转站点' && (self.model.serviceacitivity[0].f_reciever == '' || self.model.serviceacitivity[0].f_reciever == undefined)){
          this.$showMessage("请选择站点!")
          return
        }
        if(self.model.f_repairtype == ''){
          this.$showMessage("请选择报修类型!")
          return
        }
        console.log("转维修数据1：==》"+JSON.stringify(data))
        let checkResult = '正常'
        let options = [{"data": "已处理"},{"data": "未处理"}]
        let value = ''
        let codata = JSON.parse(JSON.stringify(self.paper))
        for(let device in codata){
          console.log('转维修codata[device]'+JSON.stringify(codata[device]))
          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])
              let details = []
              for(let i in codata[device][item].f_items){
                let items = codata[device][item].f_items[i]
                console.log('items',items)
                if(items.f_is_defect && (items.f_is_defect == true || items.f_is_defect == 'true')){
                  checkResult = '有隐患'
                  console.log('类型----',f_device_type)
                  let res = yield self.$resetpost(`${self.Url}/rs/sql/getDeviceItem`,{data:{f_device_id:codata[device][item].f_device_id,f_item_name:items.f_item_name}})
                  console.log('获取安检设备信息结果=》'+JSON.stringify(res))
                  self.$set('detail.f_defect_id', res.data[0].id)
                  self.$set('detail.f_project',`${items.f_item_name}：${items.f_item_value}`)
                  self.$set('detail.type',items.type)
                  self.$set('detail.options',options)
                  details.push(JSON.parse(JSON.stringify(self.detail)))
                }
                if(items.type == 'selector'){
                  items.selected = ''
                }
                self.detail = {}
              }
              console.log('details',details)
              self.$set('defectDevice.f_type',f_device_type)
              self.$set('defectDevice.details',details)
              if(self.defectDevice.details.length >0 ){
                self.repairitems.push(JSON.parse(JSON.stringify(self.defectDevice)))
              }
              self.defectDevice = {}
              console.log('repairitems===>'+self.repairitems)
            }
          }
        }
        self.$set('model.f_repairitems.data',self.repairitems)


        console.log("转维修数据2：==》"+JSON.stringify(data))
        res = self.$androidUtil.bzLogic('safecheckToRepair',data)
        console.log('res==========')
        console.log(res.code)
        console.log(res.data)
        if(res.code == 200){
          self.$parent.isSafeCheckToRepair = true
          self.undo()
          self.$set('paper.f_SafeToRepair_id',res.data.f_service_id)
          console.log('更新维修单id')
          self.$resetpost(`${self.Url}/rs/logic/updatePaperRepair`,{data:{f_paper_id:self.paper.f_paper_id,f_SafeToRepair_id:res.data.f_service_id}}).then((ret)=>{
            console.log('ret==>'+ret)
            if(ret.data.code ==200){
              console.log('维修单id修改成功')
              self.$parent.$back()
            }else{
              self.$showMessage('安检转维修失败！')
            }
          }).catch(v=>{
            console.log('v=>'+JSON.stringify(v))
            self.$showMessage('安检转维修失败！')
          })
        }else{
          self.$showMessage('安检转维修失败！')
        }
      }
    }
  }



  let getRepairs = async function(self,url) {
    // 获取配置信息
    try {
      let val = {source: 'this.getParentByType($department$).getChildByName($维修员$).getUsers()', userid: `${Vue.$login.jwt}`}
      let repairs =[]
      let res = await Vue.resetpost(`${url}/rs/search`,{data: val},{resolveMsg: null, rejectMsg: null})
      res.data.forEach((item) => {
        repairs.push({label: item.name, value: item})
      })
      self.f_repair_person = repairs
      if(self.$parent.role == 'inspect'){
        let res = self.$androidUtil.bzLogic('safecheckGetUserInfo',{id:self.paper.f_userinfoid})
        if(res.code == 200){
          self.user = res.data[0]
          self.model.f_area = self.user.f_area
        }
      }else{
        console.log('pc')
        self.$resetpost(`${self.Url}/rs/sql/safecheckGetUserInfo`,{data:{id:self.paper.f_userinfoid}},{resolveMsg: null, rejectMsg: null}).then((res)=>{
          console.log('res',res)
          if(res.data.length != 0){
            self.user = res.data[0]
            self.model.f_area = self.user.f_area
          }
        })
        // path({alias:'getUserInfo',data:{id:this.paper.f_userinfoid}})
      }
    } catch (error) {
      console.log('error',error)
    }
  }

  export default {
    title: '用户反馈',
    data() {
      return {
        paper:this.$parent.data,
        printContent:[],
        radios:[
          {
            label: '满意',
            value: 0,
            isChecked: false,
          },
          {
            label: '基本满意',
            value:1,
            isChecked: false,
          },
          {
            label: '不满意',
            value:2,
            isChecked: false,
          },
        ],
        openRadios:[
          {
            label: '同意',
            value: 0,
            isChecked: false,
          },
          {
            label: '不同意',
            value:1,
            isChecked: false,
          },
        ],
        openRadioss:[
          {
            label: '是',
            value: 0,
            isChecked: false,
          },
          {
            label: '否',
            value:1,
            isChecked: false,
          },
        ],
        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:[],
        f_repair_person: this.readRepair(),
        showrepair: false,
        safeCheckToRepair:'',
        showCheckToRepair:false,
        userid: '',
        source:
          'dep=this.getParentByType($organization$).getSpecialResByType($department$),' +
          'tool.getFullTree(dep.where(row.getChildByName($派单员$) != null))',
        isback:false,
        defectDevice:{},
        detail:{},
        callObj:null,
        user:{},
        role:this.$parent.role,
        handling:[{label:'转站点',value:'转站点'},{label:'转维修员',value:'转维修员'}],
        meading:'转站点',
        Url:this.$androidUtil.getProxyUrl(),
        deviceresult:this.$parent.deviceresult,
        deviceCollects:this.$parent.deviceCollects,
        hasDevice:this.$parent.hasDevice,
        picture:this.$parent.picture,
        config:this.$parent.config,
        showOld:false,
        showNew:false,
        showNewest:false,
        showpaperImg:false,
        linenumber:1,
        paperImgs:[],
        paperAllImgs:[],
        // 添加AMR播放相关数据
        amrPlayer: null,
        isLoading: false,
        isPlaying: false,
        isPaused: false,
        playProgress: 0,
        loadingProgress: 0,
        playInterval: null,
        currentTime: 0,
        duration: 0,
        playError: false,
      }
    },
    props: ['idx'],
    components: {
      RadioGroup,
      Radio
    },
    methods: {
      open_f (imgKey) {
        this.paperImgs = []
        // 打开组件
        if(imgKey.includes('.')){
          let keys = imgKey.split('.')
          let data = this
          keys.forEach((key)=>{
            console.log(key)
            data = data[key]
            console.log('data',data)
          })
          this.paperImgs.push({'url':data})
        }else{
          this.paperImgs = this[imgKey]
        }
        this.paperImgs.forEach((obj)=>{
          console.log('obj',obj)
          if (!('url' in obj)){
            obj['url'] = obj['f_path']
          }
        })
        if(this.paperImgs.length>0) {
          this.linenumber = Math.ceil(this.paperImgs.length / 3)
          console.log('行数--linenumber',this.linenumber)
        }
        this.showpaperImg = true
        console.log('打开图片查看器')
      },
      clone_p () {
        // 关闭组件
        this.showpaperImg = false
        console.log('关闭图片查看器')
      },
      check(index) {
        console.log('index',index)
        // 先取消所有选中项
        for (let item of this.radios){
          item.isChecked = false;
        }
        //再设置当前点击项选中
        this.paper.f_client_evaluation = this.radios[index].label;
        // 设置值，以供传递
        this.radios[index].isChecked = true;
        console.log('paper.f_client_evaluation==',this.paper.f_client_evaluation);
      },
      getSignValue(fileName) {
        this.f_signname = fileName
      },
      //获取当前时间
      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;
      },
      readRepair () {
        let url = this.$androidUtil.getProxyUrl()
        let gen = getRepairs(this,url)
        return co(gen)
      },
      showToRepair(){
        let res = this.hasDefect()
        console.log('==========检测结果========')
        console.log(res)
        if(res == '正常'){
          this.showrepair = false
        }else{
          this.showrepair = true
          this.assignObj()
        }
        this.showCheckToRepair = !this.showCheckToRepair
      },
      // 选中部门
      reres(val){
        if(val.res == undefined){
          return
        }
        this.model.serviceacitivity[0].f_meetunit = val.res
        this.model.f_meetunit = val.res
        this.model.f_orgstr = val.resids
        var arr = val.res.split('.')
        this.model.f_outlets = arr[arr.length - 1]
        this.model.serviceacitivity[0].f_reciever = val.resids
      },
      assignObj(){
        this.model.f_contact_phone = this.paper.f_user_phone
        this.model.f_user_name = this.paper.f_user_name
        this.model.f_address = this.paper.f_address
        this.model.f_user_type = this.paper.f_user_type
        this.model.f_street = this.paper.f_street
        this.model.f_residential_area = this.paper.f_residential_area
        this.model.f_building = this.paper.f_building
        this.model.f_unit = this.paper.f_unit
        this.model.f_floor = this.paper.f_floor
        this.model.f_room = this.paper.f_room
        this.model.f_floor = this.paper.f_floor
        this.model.f_userinfo_id = this.paper.f_userinfoid
        this.model.f_userinfo_code = this.paper.f_userinfo_code
      },
      hasDefect(){
        let checkResult = '正常'
        let codata = JSON.parse(JSON.stringify(this.paper))
        for(let device in this.paper){
          if(device.startsWith("device")){
            for(let item in this.paper[device]) {
              for(let i in this.paper[device][item].f_items){
                let items = this.paper[device][item].f_items[i]
                console.log('转维修判断items'+JSON.stringify(items))
                if((this.paper[device][item].f_device_type == '燃气表' && (items.f_item_name == '表具故障' || items.f_item_name == '表具隐患类型')) || this.paper[device][item].f_device_type != '燃气表'){
                  console.log('this.config[this.paper[device][item].f_device_type].items'+JSON.stringify(this.config[this.paper[device][item].f_device_type].items))
                  console.log('this.config[this.paper[device][item].f_device_type].items[items.f_item_name]'+JSON.stringify(this.config[this.paper[device][item].f_device_type].items[items.f_item_name]))
                  if(this.config[this.paper[device][item].f_device_type].items[items.f_item_name].type == 'selector'){
                    let options = this.config[this.paper[device][item].f_device_type].items[items.f_item_name].options
                    // console.log('options'+JSON.stringify(options))
                    for (let value in items.f_item_value){
                      for (let i in options){
                        let option = options[i]
                        if(option.data == items.f_item_value[value] && (option.level && (option.level.indexOf('安检维修') > -1 || option.level.indexOf('安装组维修') > -1))){
                          checkResult = '有需要转维修的隐患'
                          this.hasdefect = true
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        return checkResult
      },
      // AMR播放相关方法
      playAMR() {
        if (!this.paper.f_recording1_path) return;

        const audioPath = this.paper.f_recording1_path;

        this.isLoading = true;
        this.loadingProgress = 0;
        this.playError = false;

        console.log('尝试播放AMR文件:', audioPath);

        try {
          // 创建AMR播放器实例
          this.amrPlayer = new BenzAMRRecorder();

          // 模拟加载进度
          let progress = 0;
          const progressInterval = setInterval(() => {
            progress += 5;
            this.loadingProgress = Math.min(progress, 90);
            if (progress >= 90 || !this.isLoading) {
              clearInterval(progressInterval);
            }
          }, 100);

          // 通过XHR获取文件并明确设置responseType为arraybuffer
          const xhr = new XMLHttpRequest();
          xhr.open('GET', audioPath, true);
          xhr.responseType = 'arraybuffer';

          xhr.onprogress = (event) => {
            if (event.lengthComputable) {
              const progress = (event.loaded / event.total) * 50;
              this.loadingProgress = Math.min(progress, 50);
            }
          };

          xhr.onload = () => {
            if (xhr.status === 200) {
              const arrayBuffer = xhr.response;
              if (!arrayBuffer) {
                throw new Error('获取的文件数据为空');
              }

              // 打印文件大小信息
              console.log(`AMR文件大小: ${arrayBuffer.byteLength} 字节`);

              // 使用Uint8Array处理二进制数据
              const uint8Array = new Uint8Array(arrayBuffer);

              // 打印前几个字节，用于调试
              const headerBytes = Array.from(uint8Array.slice(0, 10))
                .map(b => b.toString(16).padStart(2, '0')).join(' ');
              console.log('文件头部字节:', headerBytes);

              // 检查文件头是否符合AMR格式 (#!AMR)
              let isValidAMR = false;

              if (uint8Array.length >= 6) {
                isValidAMR = uint8Array[0] === 35 && // #
                             uint8Array[1] === 33 && // !
                             uint8Array[2] === 65 && // A
                             uint8Array[3] === 77 && // M
                             uint8Array[4] === 82;   // R

                if (isValidAMR) {
                  console.log('检测到有效的AMR文件头');
                } else {
                  console.warn('未检测到标准AMR文件头，尝试直接解码');
                }
              }

              // 使用正确的方法初始化播放器 - 使用 initWithArrayBuffer 而不是 init
              this.amrPlayer.initWithArrayBuffer(arrayBuffer)
                .then(() => {
                  clearInterval(progressInterval);
                  this.loadingProgress = 100;
                  this.isLoading = false;
                  this.isPlaying = true;
                  this.isPaused = false;
                  this.duration = this.amrPlayer.getDuration();

                  // 开始播放
                  this.amrPlayer.play();

                  // 更新播放进度
                  this.startProgressUpdate();
                })
                .catch(error => {
                  console.error('AMR初始化失败:', error);
                  clearInterval(progressInterval);
                  this.playError = true;
                  this.isLoading = false;

                  // 尝试备选方案 - 直接使用URL播放
                  this.tryInitWithUrl(audioPath, progressInterval);
                });
            } else {
              clearInterval(progressInterval);
              throw new Error(`HTTP错误: ${xhr.status}`);
            }
          };

          xhr.onerror = () => {
            console.error('获取文件时发生网络错误');
            clearInterval(progressInterval);
            this.playError = true;
            this.isLoading = false;
            this.tryDirectDownloadAndPlay();
          };

          xhr.onabort = () => {
            console.warn('文件下载被中断');
            clearInterval(progressInterval);
            this.isLoading = false;
          };

          xhr.send();
        } catch (error) {
          console.error('初始化AMR播放器失败:', error);
          this.playError = true;
          this.isLoading = false;
          this.tryDirectDownloadAndPlay();
        }
      },

      // 尝试使用URL直接初始化
      tryInitWithUrl(audioPath, progressInterval) {
        console.log('尝试使用URL直接初始化...');

        try {
          // 使用 URL 初始化方法
          this.amrPlayer.initWithUrl(audioPath)
            .then(() => {
              if (progressInterval) clearInterval(progressInterval);
              this.loadingProgress = 100;
              this.isLoading = false;
              this.isPlaying = true;
              this.isPaused = false;
              this.duration = this.amrPlayer.getDuration();

              // 开始播放
              this.amrPlayer.play();

              // 更新播放进度
              this.startProgressUpdate();
            })
            .catch(error => {
              console.error('使用URL初始化AMR失败:', error);
              if (progressInterval) clearInterval(progressInterval);
              this.playError = true;
              this.isLoading = false;
              this.tryDirectDownloadAndPlay();
            });
        } catch (error) {
          console.error('尝试URL初始化时出错:', error);
          if (progressInterval) clearInterval(progressInterval);
          this.playError = true;
          this.isLoading = false;
          this.tryDirectDownloadAndPlay();
        }
      },

      // 直接提供下载链接并显示提示
      tryDirectDownloadAndPlay() {
        const container = document.querySelector('.col-md-12.col-sm-12.col-xs-12');
        if (!container) return;

        // 清空已有内容
        const audioPlayerDiv = container.querySelector('.audio-player');
        if (audioPlayerDiv) {
          audioPlayerDiv.innerHTML = '';
        } else {
          // 创建一个新的div元素
          const newAudioPlayerDiv = document.createElement('div');
          newAudioPlayerDiv.className = 'audio-player';
          container.appendChild(newAudioPlayerDiv);
        }

        const playerDiv = container.querySelector('.audio-player') || container;
        playerDiv.innerHTML = `
          <div class="alert alert-info">
            <strong>提示：</strong> AMR格式录音无法在浏览器中直接播放。请下载后使用支持AMR格式的播放器播放。
          </div>
        `;

        // 创建下载按钮区域
        const btnGroup = document.createElement('div');
        btnGroup.className = 'btn-group';
        btnGroup.style.marginBottom = '15px';

        // 添加下载按钮
        const downloadBtn = document.createElement('a');
        downloadBtn.href = this.paper.f_recording1_path;
        downloadBtn.className = 'btn btn-primary';
        downloadBtn.download = '录音.amr';
        downloadBtn.innerHTML = '<i class="glyphicon glyphicon-download"></i> 下载录音文件';
        downloadBtn.target = '_blank';
        btnGroup.appendChild(downloadBtn);

        playerDiv.appendChild(btnGroup);

        // 添加提示信息
        const helpText = document.createElement('div');
        helpText.className = 'well well-sm';
        helpText.style.marginTop = '10px';
        helpText.innerHTML = `
          <h4>播放AMR文件的方法：</h4>
          <ol>
            <li>大多数<strong>安卓手机</strong>可以直接播放AMR文件</li>
            <li>电脑上可以使用<strong>VLC媒体播放器</strong>（免费开源）</li>
            <li>iOS设备需要专门的应用程序来播放</li>
          </ol>
        `;
        playerDiv.appendChild(helpText);
      },

      startProgressUpdate() {
        // 清除之前的定时器
        if (this.playInterval) {
          clearInterval(this.playInterval);
        }

        // 创建新的定时器
        this.playInterval = setInterval(() => {
          if (this.amrPlayer && this.isPlaying && !this.isPaused) {
            this.currentTime = this.amrPlayer.getCurrentPosition();

            if (this.duration > 0) {
              this.playProgress = (this.currentTime / this.duration) * 100;
            }

            // 检查是否播放结束
            if (this.currentTime >= this.duration) {
              this.stopPlay();
            }
          }
        }, 100);
      },

      togglePlay() {
        if (!this.amrPlayer) return;

        if (this.isPaused) {
          // 继续播放
          this.amrPlayer.play();
          this.isPaused = false;
        } else {
          // 暂停播放
          this.amrPlayer.pause();
          this.isPaused = true;
        }
      },

      stopPlay() {
        if (!this.amrPlayer) return;

        this.amrPlayer.stop();
        this.isPlaying = false;
        this.isPaused = false;
        this.playProgress = 0;
        this.currentTime = 0;

        if (this.playInterval) {
          clearInterval(this.playInterval);
          this.playInterval = null;
        }
      },

      formatTime(seconds) {
        // 格式化时间为MM:SS格式
        seconds = Math.floor(seconds);
        const minutes = Math.floor(seconds / 60);
        seconds = seconds % 60;
        return minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
      },

      releaseResources() {
        // 释放AMR播放器资源
        if (this.amrPlayer) {
          this.stopPlay();
          this.amrPlayer = null;
        }

        // 清除定时器
        if (this.playInterval) {
          clearInterval(this.playInterval);
          this.playInterval = null;
        }

        // 重置状态
        this.isPlaying = false;
        this.isPaused = false;
        this.isLoading = false;
        this.playProgress = 0;
        this.loadingProgress = 0;
        this.currentTime = 0;
        this.duration = 0;

        // 清除可能存在的音频元素
        const container = document.querySelector('.audio-player');
        if (container) {
          const audioElements = container.querySelectorAll('audio');
          audioElements.forEach(audio => {
            audio.pause();
            audio.src = '';
            audio.load();
          });

          const iframeElements = container.querySelectorAll('iframe');
          iframeElements.forEach(iframe => {
            iframe.src = '';
          });
        }
      },
    },
    ready() {
      for (let item of this.radios){
        if(this.paper.f_client_evaluation == item.label){
          item.isChecked = true;
        }
      }
      for (let item of this.openRadios){
        if(this.paper.f_allow_open == item.label){
          item.isChecked = true;
        }
      }
      for (let item of this.openRadioss){
        if(this.paper.f_promise_user == item.label){
          item.isChecked = true;
        }
      }
      this.$dispatch('getDevicesCollect')
      // this.$parent.devicesCollect()
      // this.hasDefect()
      if (!this.paper.f_notified_path)
        this.$set('paper.f_notified_path', Vue.nopic)
      if (!this.paper.f_sign_path)
        this.$set('paper.f_sign_path', Vue.nopic)
      // if (!this.paper.f_all_imgs){
      //   let imgs = []
      //   // imgs.push({f_overall_path:Vue.nopic})
      //   this.$set('paper.f_all_imgs', imgs)
      //   console.log('进入setpaper.f_all_imgs')
      // }

      // for(let i in this.paper.f_all_imgs){
        console.log('this.paper.f_all_imgs',this.paper.f_all_imgs)
      if(this.paper.f_all_imgs && this.paper.f_all_imgs.length>0){
        if(this.paper.f_all_imgs[0].f_blob_id != null){
          this.showOld = true
          this.showNewest = false
          this.showNew = false
          for (let i in this.paper.f_all_imgs){
            this.paperAllImgs.push({url: ` rs/getImg/readBlob?id=${this.paper.f_all_imgs[i].f_blob_id}`})
          }

        }else if (this.paper.f_all_imgs[0].f_blob_id == null && this.paper.f_all_imgs[0].title == null && this.paper.f_all_imgs[0].type == null){
          this.showOld = false
          this.showNewest = false
          this.showNew = true
          for (let i in this.paper.f_all_imgs){
            this.paperAllImgs.push({url:this.paper.f_all_imgs[i].f_overall_path })
          }
        }else{
          this.showOld = false
          this.showNewest = true
          this.showNew = false
          for (let i in this.paper.f_all_imgs){
            this.paperAllImgs.push({url: this.paper.f_all_imgs[i].f_overall_path})
          }
        }
        // if(this.paperAllImgs.length>0) {
        //   this.allLinenumber = Math.ceil(this.paperAllImgs.length / 3)
        //   console.log('行数--linenumber',this.allLinenumber)
        // }
      }
      // }
      if (!this.paper.f_overall2_path)
        this.$set('paper.f_overall2_path', Vue.nopic)

      if(Vue.config.safecheck != undefined){
        if(Vue.config.safecheck.ApproveConfig != undefined){
          if(Vue.config.safecheck.ApproveConfig.safeCheckToRepair != undefined) {
            this.safeCheckToRepair = Vue.config.safecheck.ApproveConfig.safeCheckToRepair
          }
        }
      }
      console.log(`this.safeCheckToRepair==========${this.safeCheckToRepair}`)
      console.log(Vue.config)
    },
    watch:{
      // 'paper.f_all_imgs'(val){
      //   console.log('安检总体照片55555555发生变化===>',val)
      //   this.paperImgs = []
      //   if(val) {
      //     for (var i in val) {
      //       console.log(i)
      //       console.log(val[i])
      //       console.log(val[i].f_overall_path)
      //       if (val[i].f_overall_path)
      //         this.paperImgs.push({url: val[i].f_overall_path})
      //     }
      //   }
      //   console.log('照片URL+++++》》》',this.paperImgs)
      //   if(this.paperImgs.length>0) {
      //     this.linenumber = Math.ceil(this.paperImgs.length / 3)
      //     console.log('行数--linenumber',this.linenumber)
      //   }
      // },
      '$parent.isUpload'(val){
        console.log('isUpload发生变化===>'+val)
      },
      '$parent.deviceresult'(val){
        this.deviceresult =val
      },
      '$parent.deviceCollects'(val){
        this.deviceCollects =val
      },
      '$parent.hasDevice'(val){
        this.hasDevice =val
      }

    },
    beforeDestroy() {
      // 组件销毁前释放资源
      this.releaseResources();
    }
  }
</script>
<style>
  .text-left{
    text-align:left;
  }
  .font{
    font: 15px PingFang-SC-Medium;
    color: #333333;
  }
  .showInput{
    font: 14px PingFang-SC-Medium;
    color: #666666;
  }
  .info{
    margin-top: 15px;
    border-radius: 5px;
    background-color: #f3faff;
  }
  .btn-photo{
    border: 0;
    border-radius: 7px;
    background-color: #7dc1f4;
    font: 15px PingFang-SC-Bold;
    height: 20%;
  }
  .div-photo{
    width: auto;
    height: auto;
    /* margin-top: 10px; */
    position: absolute;
    bottom: 10px;
    right: 10px;
  }
  .btn-voice{
    border-radius: 7px;
    border: 1px solid #dedede;
    background-color: #f5fbff;
    font: 15px PingFang-SC-Bold;
    color: #499edf;
  }
  .save-btn{
    width: 25%;
    background-color:#499edf;
    border-radius: 6px;
    color: #FFFFFF;
    font: 15px PingFang-SC-Bold;
  }
  .upload-btn{
    width: 25%;
    background-color:#ffffff;
    border: 1px solid #499edf;
    border-radius: 6px;
    color: #499edf;
    font: 15px PingFang-SC-Bold;
  }
  .repair-btn{
    width: 25%;
    border: 1px solid #499edf;
    border-radius: 6px;
    font: 15px PingFang-SC-Bold;
  }
  .div-photo1{
    width: auto;
    height: auto;
    /* margin-top: 10px; */
    position: absolute;
    bottom: 5%;
    left: 13%;
  }
  /* 添加音频播放器样式 */
  .audio-player {
    margin: 10px 0;
  }

  .progress {
    height: 10px;
    margin-bottom: 10px;
  }
</style>
