<template>
  <b-page @bPageLoaded="voiceCallback"></b-page>
  <count-down times=300 bottomOffset="10" rightOffset="10" fontSize="24" ref="child"></count-down>
  <div class="scanMaterial" style="height:100%">

    <!-- 左区域 -->
    <div class="left">
        <div class="example"></div>
        <div style="padding-right: 1%;padding-top: 32px;">
          <!-- 取消按钮 -->
          <img class="imgButton" v-if="!scanBtnIsShow"  src="../assets/images/btn/backGray.png">
          <img class="imgButton" v-if="scanBtnIsShow" @click="back" src="../assets/images/btn/btnCancel.png">&nbsp;&nbsp;
          <!-- 扫描按钮 -->
          <img class="imgButton" v-if="!scanBtnIsShow"  src="../assets/images/btn/scanGray.png">
          <img class="imgButton" v-if="scanBtnIsShow" @click="scanBtn" src="../assets/images/btn/btnScan.png">&nbsp;&nbsp;
          <!-- 下一步按钮 -->
          <img class="imgButton" v-if="!isBtnNextShow" src="../assets/images/btn/btnNext_Not.png">
          <img class="imgButton" v-if="isBtnNextShow" @click="nextStep" src="../assets/images/btn/btnNext.png">
        </div>
    </div>

    <!-- 图片区域 -->
    <div class="imgList">
      <div class="imgBetween"  v-for="(material, index) in materialList">
          <img class="imgSize"  v-if="material.fileUrl!=''" :src="material.fileUrl">
          <div class="fileName" v-if="material.fileUrl!=''" >
            {{material.name}}
          </div>
          <div class="fileName" v-if="material.fileUrl==''" style="width: 74%;padding-left: 28%;color: #FFFFFF;padding-top: 22%;">
            {{material.name}}
          </div>
      </div>
    </div>

    <!-- 删除按钮 -->
    <div class="imgDel">
      <div class="imgDelBetween" v-for="(del, index) in imgDelList">
         <img @click="delImg(index,del.fileId)" v-if="del.name==''">
         <img @click="delImg(index,del.fileId)" v-if="del.name!=''" :src="del.imgSrc">
      </div>
    </div>

    <!-- 图片框 -->
    <div class="right">
        <div  class="rightFrame" v-for="(freme, index) in imgFrames">
          <img class="imgFrame" :src="freme.imgSrc">
        </div>
    </div>

  </div>
</template>
<script>

import BPage from "@/components/registerVoice";

export default{
  components: {
    BPage,
  },

  data() {
    return {
      scanType:'',//委托人身份代办类型
      curPage: 1,//当前页码
      num: 5,//每页展示数量
      materials: [],//材料集合
      materialList:[],//当前页面图片展示
      imgDel:[],//删除按钮集合
      imgDelList:[],//当前页面删除按钮展示
      scanBtnIsShow:false,//控制取消,扫描按钮是否显示
      isBtnNextShow:false,//控制下一步按钮是否亮起
      projectId: '',//事项ID
      serviceId: '',//机器人ID
      projectName:'',//事项名称
      isRepetition:false,//是否重复材料
      type:0,//0:默认不覆盖,1:覆盖委托书,2:覆盖身份证,3:覆盖委托书及身份证,4:只删除当前上传材料
      temporary:[],//临时集合,用于是否覆盖材料使用
      imgFrames:[],//图片框集合
      highCameraParameter:{//高拍仪参数
          x: 68,//预览界面x坐标
          y: 47,//预览界面y坐标
          width: 900,//预览界面宽度
          height: 676,//预览界面高度
      },
      userInfoParameter:{//办事人信息
        callback: "getUserInfo"
      },
      highCameraImgParameter:{//获取高拍仪照片
        callback: "HighCameraCallback"
      },
      count:0,
    }
  },
  created() {
       this.projectId = this.$LocalStorage.SessionGet("projectId");
       this.serviceId = this.$LocalStorage.SessionGet("serviceId");
       this.projectName=this.$LocalStorage.SessionGet("projectName");

       this.scanType=this.$route.query.scanType;
       if (this.scanType=='1'){//委托人身份代办类型 1:手持身份证照片页面 2:法人+委托书原件或复印件页面
           this.materials.push({'name':'手持身份证','fileUrl':'','fileId':'','artificialType':'','type':''});
           this.imgDel.push({'name':'','imgSrc':require('../assets/images/ico/delete.png')});
           this.imgFrames.push({'imgSrc':require('../assets/images/filebox.png')}),
           this.pageInfo(this.curPage,this.num);
           if(robotType)
             this.openVoice( "请提交手持身份证");//语音播放
        }else{
           this.materials.push({'name':'委托书','fileUrl':'','fileId':'','artificialType':'','type':''});
           this.materials.push({'name':'委托人身份证','fileUrl':'','fileId':'','artificialType':'','type':''});
           this.imgDel.push({'name':'','imgSrc':require('../assets/images/ico/delete.png')});
           this.imgDel.push({'name':'','imgSrc':require('../assets/images/ico/delete.png')});
           this.imgFrames.push({'imgSrc':require('../assets/images/filebox.png')}),
           this.imgFrames.push({'imgSrc':require('../assets/images/filebox.png')}),
           this.pageInfo(this.curPage,this.num);
           if(robotType)
             this.openVoice( "请提交委托书和委托人身份证");//语音播放
        }

       if (robotType)robotsdk.getUserInfo(this.userInfoParameter);//获取办事人信息

       //将方法绑定到window下面，提供给外部调用
       window.PlayAudioCallback = (res)=> this.PlayAudioCallback(res);//语音播放
       window.HighCameraCallback = (success, obj)=> this.HighCameraCallback(success, obj);//获取高拍仪照片
       window.ConfirmCallback = (res)=> this.ConfirmCallback(res);//提示确认，取消对话框
       window.getUserInfo = (obj)=> this.getUserInfo(obj);//获取身份证信息
       this.initializeOcrUrl();//初始化ocr地址
  },
  methods:{
    initializeOcrUrl(){
        if (window.config.isUpRocrUrl){//更新ocr地址  true=更新 false=不更新
            this.$axios.get(window.config.api + 'lilo/v1/robot/getRocrUrl', {
              params: {
                serviceId : this.serviceId,
                projectId : this.projectId
              }
            }).then(item => {
              if (item.data.success) {
                  window.config.rocrUrl=item.data.msg;
                  window.config.isUpRocrUrl=false;
              }else{
                this.message(true,"服务器异常,初始化失败！");//提示框
              }
            }).catch(err => {
                 this.message(true,"服务器异常,初始化失败！");//提示框
            })
        }
    },

    back() {
        if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
        if(robotType){
          robotsdk.closeExternalApp({//退出跳转咨询页面
            mode:0
          });
        }
    },

    nextStep() {
        if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
        if (!this.isRepetition) this.$LocalStorage.SessionPut("entrustMaterials",this.materials);
        if (this.isRepetition) this.$LocalStorage.SessionPut("entrustMaterials",this.materials[0]);
        this.$LocalStorage.SessionPut("scanType",this.scanType);
        this.$router.push({ path: '/material',query:{isCancel:true}});
    },

    scanBtn(){
        this.$refs.child.counter=300; //刷新时间
        this.masks(true);//遮罩层 true 打开 false 关闭
        if (robotType)robotsdk.getHighCamera(this.highCameraImgParameter);//获取高拍仪照片
    },

    pageInfo (curPage,num) {
        var curPage = (curPage - 1) * num;
        this.materialList = this.materials.slice(curPage,parseInt(curPage) + parseInt(num));
        this.imgDelList = this.imgDel.slice(curPage,parseInt(curPage) + parseInt(num));
    },

    delImg(index,fileId){
        this.$refs.child.counter=300; //刷新时间
        if (this.isRepetition){
          this.showConfirmMessage("当前材料还包含其它材料是否确认一起删除?");
        }else{
           this.delMaterialByFileId(index,fileId);//删除数据库材料数据
        }
    },

    openVoice(content){
        robotsdk.playAudio({//语音播放参数
                  cmd: "cmd",//语音指令，可参考属性voiceInstruct
                  animation: 0,//虚拟任务动作编号可参考属性animationEnum
                  videocontent:content,//语音内容
                  callback: "PlayAudioCallback"//接口回调函数
            });//虚拟人物播放语音及动作
    },

    PlayAudioCallback (res){
          if (res=="cmdOK"){
              if (robotType){
                robotsdk.openHighCamera(this.highCameraParameter);//打开高拍仪预览界面
                this.scanBtnIsShow=true;
                robotsdk.playAudio({//语音播放参数
                  cmd: "sm",//语音指令，可参考属性voiceInstruct
                  animation: 0,//虚拟任务动作编号可参考属性animationEnum
                  videocontent: "请将需要提交的资料放置到扫描区，等资料预览清晰后点击'扫描'按钮进行扫描",//语音内容
                  callback: "PlayAudioCallback"//接口回调函数
                });//虚拟人物播放语音及动作
              }
          }
    },

    HighCameraCallback(success, obj){
        if (success) {
            let special="";
            if (this.scanType==1)special="isInhandImage";
            let res = eval('(' + obj + ')');//高拍仪回调的数据集
            $.post( window.config.rocrUrl+'lilo/aiCase/uploadFileNew', {
                fileName : res.filename,
                base64 : res.file,
                projectId: this.projectId,
                special:special,
            }).then(item => {
                if (item.success) {
                    this.masks(false);//遮罩层 true 打开 false 关闭
                  if (robotType){
                    robotsdk.playAudio({
                      cmd: "cmd",
                      animation: 0,
                      videocontent: "识别成功，请放下一页。",
                      callback: ""
                    })
                  }
                    let fileName=item.obj.fileName;
                    if (this.scanType==1){
                      if (fileName=="手持"){
                        this.upMaterials(0,item);//更新手持身份证信息
                      }else{
                        this.message("请提交手持身份证信息！");//提示框
                      }
                      if (this.materials[0].fileUrl!='')this.isBtnNextShow=true;
                    }else{

                          let bool=false;
                          if (item.obj.jsonData!=''){
                            let identity =eval('(' + item.obj.jsonData + ')');//身份证信息
                            try {
                              identity.forEach((obj,index)=>{
                                if (this.name==obj.name){
                                  bool=true;
                                  throw("当前委托人身份证正确================");
                                }
                              })
                            }catch (e){
                              console.info(e);
                            }
                          }

                          let oneFileUrl=this.materials[0].fileUrl;
                          let twoFileUrl=this.materials[1].fileUrl;
                          if (fileName!=''){
                            if (fileName.lastIndexOf(",")!=-1){//判断材料是否多份
                              if (fileName.lastIndexOf("委托书")!=-1&&fileName.lastIndexOf("身份证")!=-1){
                                if (oneFileUrl==""&&twoFileUrl==""){
                                  this.upMaterials(0,item);//更新委托书材料信息
                                  if (bool){
                                    this.upMaterials(1,item);//更新委托人身份证材料信息
                                    this.temporary=item;
                                    this.isRepetition=true;
                                  } else{
                                    this.message("当前办理人和委托人名称不一致,请提交委托人身份证！");//提示框
                                  }
                                }else if(oneFileUrl!=""&&twoFileUrl!=""){
                                  this.type=3;
                                  this.temporary=item;
                                  this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                                }else if(oneFileUrl==""&&twoFileUrl!=""){
                                  this.upMaterials(0,item);//更新委托书材料信息
                                }else if(oneFileUrl!=""&&twoFileUrl==""){
                                  if (bool)this.upMaterials(1,item);//更新委托人身份证材料信息
                                  if (!bool)this.message("请提交委托人身份证！");//提示框
                                }
                              }else{
                                this.indexOfFileName(item,bool);
                              }
                            }else{
                              if (fileName.lastIndexOf("委托书")!=-1||fileName.lastIndexOf("身份证")!=-1){
                                this.indexOfFileName(item,bool);
                              }else{
                                this.message("请勿提交其它文件！");//提示框
                              }
                            }
                          }else{
                            this.message("服务器异常,扫描失败！");//提示框
                          }
                          if (this.materials[0].fileUrl!=''&&this.materials[1].fileUrl!='')this.isBtnNextShow=true;
                        }
                    }else{
                      this.masks(false);//遮罩层 true 打开 false 关闭
                      this.message("服务器异常,扫描失败！");//提示框
                }
            }).catch(err => {
                this.masks(false);//遮罩层 true 打开 false 关闭
                this.message("服务器异常,扫描失败！");//提示框
            })
        } else {
            this.masks(false);//遮罩层 true 打开 false 关闭
            this.message("服务器异常,扫描失败！");//提示框
        }
    },

    ConfirmCallback(bool){
      if (bool){//确认
        if (this.isRepetition){
            this.type=3;
            this.delMaterialByFileId(null,this.materials[0].fileId);
        }else{
          if (this.type==1){
            this.delMaterialByFileId(0,this.materials[0].fileId);
          }else if (this.type==2){
            this.delMaterialByFileId(1,this.materials[1].fileId);
          } else{
            this.delMaterialByFileId(null,this.materials[0].fileId);
          }
        }
      }else{//取消
        if (!this.isRepetition){
          this.type=4;//4:删除当前上传材料，不做其它操作
          this.delMaterialByFileId(null,this.temporary.obj.fileId);
        }
      }
    },

    masks(bool){
        if (robotType) {
          robotsdk.showMasks({//遮罩层
            isOpen: bool //true 打开 false 关闭
          });
        }
    },

    message(content){
        if (robotType) {
            robotsdk.showMessage({//提示框
              isOpen: true,//true 打开 false 关闭
              content: content,//消息内容
              isAutoClose: true//true 5秒自动关闭 false 用户点确认关闭
            });
        }
    },

    getUserInfo(obj){
      let res = eval('(' + obj + ')');
      this.name=res.name;
      this.mobile=res.mobile;
      this.idcard=res.idcard;
    },

    showConfirmMessage(content){
      if (robotType) {
        robotsdk.showConfirmMessage({
            isOpen: true,
            content: content,
            isAutoClose: false,
            callback: "ConfirmCallback"
        });
      }
    },

    upMaterials(number,item){
      this.materials[number].fileUrl=item.obj.fileUrl;
      this.materials[number].fileId=item.obj.fileId;
      this.materials[number].artificialType=item.obj.artificialType;
      this.materials[number].type=item.obj.type;
      this.imgDel[number].fileId=item.obj.fileId;
      this.imgDel[number].name=item.obj.fileName;
      this.imgDel[number].imgSrc=require('../assets/images/ico/delete.png');
    },

    indexOfFileName(item,bool){
      let ofEntrustName=item.obj.fileName.lastIndexOf("委托书");
      let ofCardName=item.obj.fileName.lastIndexOf("身份证");
      let entrustFileUrl=this.materials[0].fileUrl;
      let cardFileUrl=this.materials[1].fileUrl;
      if (ofEntrustName!=-1&&entrustFileUrl==''){
        this.upMaterials(0,item,false);//更新委托书材料信息
      } else if (ofCardName!=-1&&cardFileUrl==''){
        if (bool) this.upMaterials(1,item,false);//更新委托人身份证材料信息
        if (!bool)this.message("请提交委托人身份证！");//提示框
      } else if (ofEntrustName!=-1&&entrustFileUrl!=''){
        this.type=1;
        this.temporary=item;
        this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
      } else if (ofCardName!=-1&&cardFileUrl!=''){
        if (bool) {
          this.type=2;
          this.temporary=item;
          this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
        }
        if (!bool)this.message("请提交委托人身份证！");//提示框
      }
    },

    delMaterialByFileId(index,fileId){
      $.post( window.config.rocrUrl+'lilo/aiCase/deleteFile', {
        fileId : fileId
      }).then(item => {
        if (item.success) {
          //删除材料
          if (this.type==0||this.type==1||this.type==2){
            this.imgDel[index].name='';
            this.materials[index].fileUrl='';
            this.isBtnNextShow=false;
          }
          //覆盖材料更新
          if (this.type==1)//更新委托书材料信息
            this.upMaterials(0,this.temporary);
          else if (this.type==2)//更新身份证材料信息
            this.upMaterials(1,this.temporary);
          else if (this.type==3){//更新委托书及身份证材料信息
            this.materials.forEach((obj,index)=>{
              this.imgDel[index].name='';
              obj.fileUrl='';
              obj.isBtnNextShow=false;
            });
            if (!this.isRepetition){
              this.upMaterials(0,this.temporary);//更新委托书材料信息
              this.upMaterials(1,this.temporary);//更新委托书材料信息
            }
          }
          this.type=0;
          this.temporary=[];
          this.isRepetition=false;
        }else{
          this.message("服务器异常,删除失败！");//提示框
        }
      }).catch(err => {
        this.message("服务器异常,删除失败！");//提示框
      })
    },

    //语音回调（只处理扫描,下一步,退出）
    voiceCallback(res){
      if (res=="scanning"){
        if (this.scanBtnIsShow){
          this.scanBtn();
        }
      }

      if (res=="nextStep"){
        if (this.isBtnNextShow){
          this.nextStep();
        }
      }

      if (res=="quit"){
        this.back();
      }
    }

  }
}
</script>
<style scoped>

.scanMaterial{
  background-image: url('../assets/images/background.png');
  background-repeat:no-repeat;
  background-size:100% 100%;
  background-size: cover;
  overflow:auto;
}
.imgButton {
  width: 31%;
}
.example{
  background-image: url('../assets/images/scanExample.gif');
  background-repeat:no-repeat;
  height: 676px;
  margin-left: 1.2%;
  margin-top: 1.4%
}
.left{
  height: 100%;
  float: left
}
.right{
  padding-left: 72%;
  padding-top: 20px;
  height: 82%;
}
.rightFrame{
  height: 140px;
}
.fileName{
  width: 74%;
  padding-left: 28%;
  color:#FFFFFF;
  padding-top: 2%;
}
.imgFrame{
   height: 92px;
   width: 45%;
}
.imgSize{
  height: 75px;
  width: 38%;
}
.imgList{
  position: absolute;
  left: 70.92%;
  padding-top: 2.2%;
  width: 30%;
}
.imgBetween{
   height: 140px;
 }
.imgDel{
  position: absolute;
  padding-top: 1.5%;
  left: 87%;
  z-index: 99;
}
.imgDelBetween{
  height: 137px;
  z-index: 99;
}
</style>