<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"  @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="btnUp" v-if="formIndex=='12'">
      <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" v-if="formIndex=='12'">
      <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,//控制下一步按钮是否亮起
      manyCount:0,//重复材料数量
      addIndex:-1,//添加材料坐标
      identityList:[],//身份证扫描之后集合
      idCardList:[],//最终跳转表单所传递的集合
      serviceId: '',//机器人ID
      projectName:'',//事项名称
      isRepetition:false,//是否重复材料
      type:0,//0:默认不覆盖,1:覆盖身份证,2:覆盖营业执照,3:只删除当前上传材料
      temporary:[],//临时集合,用于是否覆盖材料使用
      imgFrames:[],//图片框集合
      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;

        //初始化右区域图片框,材料名称,删除图标
        if (this.formIndex == 1||this.formIndex == 11) {
          this.materials.push({'name': '身份证', 'fileUrl': '', 'fileId': '', 'type': ''});
          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')});
        } else if (this.formIndex == 7) {
          this.materials.push({'name': '身份证', 'fileUrl': '', 'fileId': '', 'type': ''});
          this.imgDel.push({'name': '', 'imgSrc': require('../../assets/images/ico/delete.png')});
          this.imgFrames.push({'imgSrc': require('../../assets/images/filebox.png')});
        } else if (this.formIndex == 12) {
          this.materials.push({'name': '营业执照', 'fileUrl': '', 'fileId': '', 'type': '11','jsonData':'11'});
          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')});
        } else if(this.formIndex == 13 || this.formIndex == 14 || this.formIndex == 15){  //只需要扫描身份证
            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')});
        } else {
          this.materials.push({'name': '营业执照', 'fileUrl': '', 'fileId': '', '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();//语音播放
        }

        //将方法绑定到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();//关闭高拍仪
      if(robotType){
        robotsdk.closeExternalApp({//退出跳转咨询页面
          mode:0
        });
      }
    },

    nextStep() {//下一步
      this.isOpenHighCamera=false;
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      if (this.formIndex==1){
        // this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=apply/XCYJYXKZ",materials:JSON.stringify(this.materials)}});
          this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.aiCaseUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/XCYJYXKZ",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==2){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/JXSYBZSPJYZBA",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==3){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/GGCSWSXKXB",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==4){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/GGCSWSXKCNS",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==7){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/ZGCBDJYB",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==8){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/GGCSWSXK",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==9){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/GGCSWSXKCNS",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==10){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/SPJYXKZZX",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==11){
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/XCYJYXKZ",materials:JSON.stringify(this.materials)}});
      }
      if (this.formIndex==12){
        if (this.materials[0].fileUrl!=''){
          this.identityList.push(JSON.parse(this.materials[0].jsonData)[0]);
        }
        this.$router.push({ path: '/iframePage',query:{pageUrl:window.config.rocrUrl+"lilo/aiCase/skipSanitationRegister?pageUrl=rpaForm/sichuan/yibin/web/JKZSQB",materials:JSON.stringify(this.identityList)}});
      }
    },

    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; //刷新时间
        this.type=0;
        let newIndex=this.curPage*this.num-(this.num-index);//材料坐标位置
        this.delMaterialByFileId(newIndex,fileId);//删除数据库材料数据
    },

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


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

        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,
        applyType:'2',
      }).then(item => {
          if (item.success) {
              this.masks(false);//遮罩层 true 打开 false 关闭
              let fileName=item.obj.fileName;

            if (this.formIndex==1||this.formIndex==11){
                let oneFileUrl=this.materials[0].fileUrl;
                let twoFileUrl=this.materials[1].fileUrl;
                if (fileName!=''){
                  if (fileName.lastIndexOf("身份证")!=-1) {
                    if (oneFileUrl==""){
                      this.upMaterials(0,item);//更新身份证材料信息
                    }else{
                      this.type=1;
                      this.temporary=item;
                      this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                    }
                  }else  if (fileName.lastIndexOf("营业执照")!=-1){
                    if (twoFileUrl==""){
                      this.upMaterials(1,item);//更新营业执照材料信息
                    }else{
                      this.type=2;
                      this.temporary=item;
                      this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                    }
                  }else{
                    this.message("请勿提交其它文件!");//提示框
                  }
                }

            }else if (this.formIndex==7){
              let oneFileUrl=this.materials[0].fileUrl;
              if (fileName.lastIndexOf("身份证")!=-1){
                if (oneFileUrl==""){
                  this.upMaterials(0,item);//更新身份证材料信息
                }else{
                  this.type=1;
                  this.temporary=item;
                  this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                }
              }else{
                this.message("请勿提交其它文件!");//提示框
              }
            }else if (this.formIndex==12){
              let oneFileUrl=this.materials[0].fileUrl;
              if (fileName.lastIndexOf("营业执照")!=-1){
                if (oneFileUrl==""){
                  this.materials[0].jsonData=item.obj.jsonData;
                  this.upMaterials(0,item);//更新营业执照材料信息
                }else{
                  this.type=2;
                  this.temporary=item;
                  this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                }
              }else  if (fileName.lastIndexOf("身份证")!=-1){
                if (this.materials.length>9){
                  this.message("只能上传8个身份证!");//提示框
                }else{
                  var resData=eval('(' + item.obj.jsonData + ')');
                  this.isMore("身份证",item);
                  this.addMaterials("身份证",item);
                  this.manyCount=0;
                  this.identityList.push(resData);

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

                  this.pageInfo(this.curPage,this.num);
                }

              }else{
                this.message("请勿提交其它文件!");//提示框
              }
            }else{
                let oneFileUrl=this.materials[0].fileUrl;
                if (fileName.lastIndexOf("营业执照")!=-1){
                  if (oneFileUrl==""){
                    this.upMaterials(0,item);//更新营业执照材料信息
                  }else{
                    this.type=1;
                    this.temporary=item;
                    this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                  }
                }else{
                  this.message("请勿提交其它文件!");//提示框
                }
            }
        }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);
        }else if (this.type==2){
          this.delMaterialByFileId(1,this.materials[1].fileId);
        }
    }else{//取消
      if (!this.isRepetition){
        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 用户点确认关闭
      });
    }
  },

  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.formIndex==12){
            if (this.type==2){
               this.upMaterials(0,this.temporary);
            }else{
               this.up(index);
            }
          }else{
            if (this.type==0||this.type==1||this.type==2){
              this.imgDel[index].name='';
              this.materials[index].fileUrl='';
              this.materials[index].fileId='';
            }
            //覆盖材料更新
            if (this.type==1){//更新身份证信息
              this.upMaterials(0,this.temporary);
            } else if (this.type==2){//更新营业执照
              this.upMaterials(1,this.temporary);
            }
          }

          this.temporary=[];
        }else{
          this.message("服务器异常,删除失败!");//提示框
        }
      }).catch(err => {
        this.message("服务器异常,删除失败!");//提示框
      })
    },

    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.imgDel[number].fileId=item.obj.fileId;
      this.imgDel[number].name=item.obj.fileName;
      this.imgDel[number].imgSrc=require('../../assets/images/ico/delete.png');
    },

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

    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.materials[index].fileId='';
      }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)>nameNumber){
              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=[];
        }

      }

      this.manyCount=0;
      if (this.materialList.length==1&&this.curPage!=1)
        this.curPage = this.curPage-1;
      this.pageInfo(this.curPage,this.num);

    },

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

      if (res=="nextStep"){
          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>