<template>
  <b-page @bPageLoaded="voiceCallback"></b-page>
  <count-down times=300 bottomOffset="30" rightOffset="10" fontSize="30" 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}}<span v-if="material.isMust==1" style="color: red">(必要材料)</span>
        </div>
        <div class="fileName" v-if="material.fileUrl==''" style="width: 74%;padding-left: 28%;color: #FFFFFF;padding-top: 22%;">
          {{material.name}}<span v-if="material.isMust==1" style="color: red">(必要材料)</span>
        </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="btnUp">
      <img src="../../assets/images/btn/btnLeft2.png">
    </div>
    <div class="btnUp" v-if="curPage!=1">
      <img @click="imgUp" src="../../assets/images/btn/btnLeft.png">
    </div>

    <!-- 图片下一页 -->
    <div class="btnNext" >
      <img src="../../assets/images/btn/btnRight2.png">
    </div>
    <div class="btnNext" v-if="materials.length>(curPage*num)">
      <img @click="imgNext" src="../../assets/images/btn/btnRight.png">
    </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 {
      formIndex:0,//表列表下标
      isOpenHighCamera:true,//是否打开高拍仪
      scanType:'',//委托人身份代办类型
      curPage: 1,//当前页码
      num: 5,//每页展示数量
      materials: [],//材料集合
      materialList:[],//当前页面图片展示
      imgDel:[],//删除按钮集合
      imgDelList:[],//当前页面删除按钮展示
      scanBtnIsShow:false,//控制取消,扫描按钮是否显示
      isBtnNextShow:false,//控制下一步按钮是否亮起
      serviceId: '',//机器人ID
      projectName:'',//事项名称
      isRepetition:false,//是否重复材料
      type:0,//0:默认不覆盖,1:覆盖不动产,2:覆盖身份证,3:只删除当前上传材料
      temporary:[],//临时集合,用于是否覆盖材料使用
      imgFrames:[],//图片框集合
      propertyList:[],//不动产集合
      identityList:[],//身份证扫描之后集合
      idCardList:[],//最终跳转表单所传递的集合
      manyCount:0,//重复材料数量
      addIndex:-1,//添加材料坐标
      highCameraParameter:{//高拍仪参数
        x: 68,//预览界面x坐标
        y: 47,//预览界面y坐标
        width: 900,//预览界面宽度
        height: 676,//预览界面高度
      },
      voiceParameter:{//语音播放参数
        cmd: "cmd",//语音指令，可参考属性voiceInstruct
        animation: 0,//虚拟任务动作编号可参考属性animationEnum
        videocontent: "请您根据扫描要求，逐页将资料放置到材料识别区。",//语音内容
        callback: "PlayAudioCallback"//接口回调函数
      },
      userInfoParameter:{//办事人信息
        callback: "getUserInfo"
      },
      highCameraImgParameter:{//获取高拍仪照片
        callback: "HighCameraCallback"
      },
      count:0,
    }
  },
  created() {
        this.formIndex = this.$route.query.formIndex;

        //初始化右区域图片框,材料名称,删除图标
        this.materials.push({'name':'不动产证','fileUrl':'','fileId':'','type':'','isMust':'1','jsonData':''});
        this.materials.push({'name':'身份证','fileUrl':'','fileId':'','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.imgFrames.push({'imgSrc':require('../../assets/images/filebox.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();//语音播放

        //将方法绑定到window下面，提供给外部调用
        window.PlayAudioCallback = (res)=> this.PlayAudioCallback(res);//语音播放
        window.HighCameraCallback = (success, obj)=> this.HighCameraCallback(success, obj);//获取高拍仪照片
        window.ConfirmCallback = (res)=> this.ConfirmCallback(res);//提示确认，取消对话框
  },
  methods:{

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

    nextStep() {//下一步
      this.idCardList.push(JSON.parse(this.materials[0].jsonData)[0]);
      var powerNmae=JSON.parse(this.materials[0].jsonData)[0].name;

      if (powerNmae!=null&&powerNmae!=""){
        this.identityList.forEach((identity,i)=> {
          identity.forEach((obj,i)=> {
              let name=obj.name;
              if (name!=null&&name!=''){
                if (powerNmae.lastIndexOf(name)!=-1){
                  this.idCardList.push(obj);
                }
              }
          })
        })
      }

      this.isOpenHighCamera=false;
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      if (this.formIndex==5){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=apply/BDCMMHT",materials:JSON.stringify(this.idCardList)}});
      }
      if (this.formIndex==6){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=apply/FWZYHT",materials:JSON.stringify(this.idCardList)}});
      }
    },

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

    delImg(index,fileId){
        this.updateTimes()//刷新时间
        let newIndex=this.curPage*this.num-(this.num-index);//材料坐标位置
        this.indexFileId=this.materials[newIndex].fileId;//获取当前fileId
        this.delMaterialByFileId(newIndex,fileId);
    },

    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));
    },

    openVoice(){
      robotsdk.playAudio(this.voiceParameter);//虚拟人物播放语音及动作
    },

    PlayAudioCallback (res){//语音回调
      console.info("PlayAudioCallback===="+res)
        if (res=="cmdOK"&&this.isOpenHighCamera){
          robotsdk.openHighCamera(this.highCameraParameter);//打开高拍仪预览界面

          this.message("请提交所有权利人身份证文件");//提示框
          this.scanBtnIsShow=true;//扫描按钮赋值可点
          robotsdk.playAudio({//语音播放参数
            cmd: "sm",//语音指令，可参考属性voiceInstruct
            animation: 0,//虚拟任务动作编号可参考属性animationEnum
            videocontent: "请将需要提交的资料放置到扫描区，等资料预览清晰后点击'扫描'按钮进行扫描",//语音内容
            callback: "PlayAudioCallback"//接口回调函数
          });//虚拟人物播放语音及动作
        }
    },

    HighCameraCallback(success, obj){////获取高拍仪照片
      if (success) {
        let res = eval('(' + obj + ')');//高拍仪回调的数据集
        $.post( window.config.rocrUrl+'lilo/apply/uploadFile', {
          fileName : res.filename,
          base64 : res.file,
          bdc: "false",//是否处理不动产证权利人名称逗号符号
          applyType:'2',
        }).then(item => {
            if (item.success) {
                  this.masks(false);//遮罩层 true 打开 false 关闭
                  let fileName=item.obj.fileName;

                  var resData=eval('(' + item.obj.jsonData + ')');
                  let oneFileUrl=this.materials[0].fileUrl;
                  if (fileName!=''){
                    if (fileName.lastIndexOf("不动产")!=-1) {
                      this.propertyList =resData;//不动产信息
                      if (oneFileUrl==""){
                        this.upMaterials(0,item);//更新不动产材料信息
                      }else{
                        this.type=1;
                        this.temporary=item;
                        this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                      }
                    }else  if (fileName.lastIndexOf("身份证")!=-1){
                        let isExist=false;
                        try {
                          resData.forEach((res,i)=> {
                            if (res.name!=null){
                              this.identityList.forEach((identity,i)=> {
                                identity.forEach((obj,i)=> {
                                  if ( obj.name==res.name) {
                                    isExist=true;
                                    throw("身份证信息已上传过================");
                                  }
                                })
                              })
                            }
                          })
                        }catch (e){
                          console.info(e);
                        }

                        if (isExist){//判断该身份是否已经提交过
                          this.message("请勿重复提交身份证信息！");//提示框
                        }else{
                          this.isMore("身份证",item);
                          this.addMaterials("身份证",item);
                          this.manyCount=0;
                          this.identityList.push(resData);
                        }

                    }else{
                      this.message("请勿提交其它文件！");//提示框
                    }
                  }else {
                    this.message("服务器异常,扫描失败！");//提示框
                  }

                  if (this.addIndex<5){
                    this.curPage=1;
                  }else{
                    let integer=parseInt((this.addIndex/this.num).toString());//取整
                    if (this.addIndex/this.num.toFixed(2)>=integer){
                      this.curPage=integer+1
                    }else{
                      this.curPage=integer;
                    }
                  }
                  if (this.materials[0].fileUrl!=''){
                    this.isBtnNextShow=true;
                  }
                this.pageInfo(this.curPage,this.num);
          }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.type==1){//不动产
              this.delMaterialByFileId(0,this.materials[0].fileId);
            }
        }
    },

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

    imgUp(){
      this.updateTimes()//刷新时间
      this.curPage = this.curPage-1;
      this.pageInfo(this.curPage,this.num);
    },

    imgNext(){
      this.updateTimes()//刷新时间
      this.curPage = this.curPage+1;
      this.pageInfo(this.curPage,this.num);
    },

    updateTimes(){
      this.$refs.child.counter=300;
    },

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

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

    delMaterialByFileId(index,fileId){
        $.post( window.config.rocrUrl+'lilo/apply/deleteFile', {
          fileId : fileId
        }).then(item => {
          if (item.success) {
              if (this.type==1){
                this.imgDel[index].name='';
                this.materials[index].fileUrl='';
                this.materials[index].fileId='';
              }
              //覆盖材料更新
              if (this.type==1){//更新不动产信息
                this.upMaterials(0,this.temporary);
                this.temporary=[];
              } else{
                this.up(index);
              }
          }else{
            this.message("服务器异常,删除失败！");//提示框
          }
        }).catch(err => {
          this.message("服务器异常,删除失败！");//提示框
        })
      },

    up(index){
        let nameNumber=this.materials[index].name.replace(/[^0-9]/ig,"");//材料名称后面数字
        let indexName=this.materials[index].name;

        if (nameNumber!=''){
          indexName=indexName.substring(0,indexName.length-nameNumber.length);
        }else{
          indexName=this.materials[index].name;
        }

        if (index==0){
            this.imgDel[index].name='';
            this.materials[index].fileUrl='';
            this.isBtnNextShow=false;
        }else{
            this.materials.forEach((obj,i)=> {
              let subName=obj.name.substring(0,indexName.length);
              let subInt=obj.name.substring(indexName.length);
              if (indexName==subName){
                if (nameNumber==''&&parseInt(subInt)==1){
                  obj.name= subName
                }else if (parseInt(subInt)>1){
                  let count=parseInt(subInt)-1;
                  obj.name= subName+count;
                }
              }
            })
            this.materials.splice(index,1)
            this.imgDel.splice(index,1);
            if (this.identityList.length>1){
              this.identityList.splice((index-1),1);
            }else{
              this.identityList=[];
            }
        }
        console.info("this.identityList===="+JSON.stringify(this.identityList))
        this.manyCount=0;
        if (this.materialList.length==1&&this.curPage!=1)
          this.curPage = this.curPage-1;
        this.pageInfo(this.curPage,this.num);

    },

    isMore(fileName,item){
      this.materials.forEach((obj,index)=>{
        let subName = obj.name.substring(0, fileName.length);
        if (fileName.lastIndexOf(subName)!=-1&&obj.fileUrl!=''){
          this.manyCount=this.manyCount+1;
        }else if (fileName.lastIndexOf(subName)!=-1&&obj.fileUrl==''){
          obj.fileUrl=item.obj.fileUrl;
          obj.fileId=item.obj.fileId;
          obj.type=item.obj.type;
          this.imgDel[index].name=item.obj.fileName;
          this.imgDel[index].fileId=item.obj.fileId;
          this.manyCount=-1;
          this.addIndex=index;
        }
      })
    },

    addMaterials(fileName,item){
      if (this.manyCount>=1){
        this.materials.push({'name':fileName+this.manyCount,'fileUrl':item.obj.fileUrl,'fileId':item.obj.fileId,
          'artificialType':item.obj.artificialType,'type':item.obj.type});
        this.imgDel.push({'name':fileName+this.manyCount,fileId:item.obj.fileId,'imgSrc':require('../../assets/images/ico/delete.png')});
        this.addIndex=this.materials.length-1;
      }
      if (this.manyCount==0){
        this.materials.push({'name':fileName,'fileUrl':item.obj.fileUrl,'fileId':item.obj.fileId,
          'artificialType':item.obj.artificialType,'type':item.obj.type});
        this.imgDel.push({'name':fileName,fileId:item.obj.fileId,'imgSrc':require('../../assets/images/ico/delete.png')});
        this.addIndex=this.materials.length-1;
      }
    },

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

    //语音回调（只处理扫描,下一步,退出）
    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;
}
.btnUp{
  position: absolute;
  left: 75%;
  margin-top: 22%;
  z-index: 99;
}
.btnNext{
  position: absolute;
  left: 95%;
  margin-top: 22%;
  z-index: 97;
}
</style>