<template>
  <b-page @bPageLoaded="voiceCallback"></b-page>
  <count-down times=300 bottomOffset="2" rightOffset="100" 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" @click="lookImg(material.fileUrl,index,material.fileId)" 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 class="wire"></div>
    <div style="color: #FFFFFF;font-size: 20px;">
      点击按钮可查看详细说明 <img @click="lookDetails" src="../assets/images/ico/help.png">
    </div>

  </div>
</template>
<script>
import BPage from "@/components/registerVoice";

export default{
  components: {
    BPage,
  },

  data() {
    return {
      curPage: 1,//当前页码
      num: 5,//每页展示数量
      materials: [],//材料集合
      materialList:[],//当前页面图片展示
      imgDel:[],//删除按钮集合
      imgDelList:[],//当前页面删除按钮展示
      scanBtnIsShow:false,//控制取消,扫描按钮是否显示
      isBtnNextShow:false,//控制下一步按钮是否亮起
      projectId: '',//事项ID
      serviceId: '',//机器人ID
      projectName:'',//事项名称
      userType:'',//用户类型 60:本人 1:委托人
      scanType:'',//委托人办理类型 1:法人手持身份证照片 2:法人+委托书原件或复印件
      initMaterialList:[],//必传材料
      name : '',//办事人名称
      mobile : '',//手机号
      idcard : '',//身份证号
      manyCount:0,//重复材料数量
      indexFileId:'',//当前fileId,用于多份删除
      addIndex:-1,//添加材料坐标
      isHint:true,//是否提示多份材料删除
      imgFrames:[//图片框集合
          {'imgSrc':require('../assets/images/filebox.png')},
          {'imgSrc':require('../assets/images/filebox.png')},
          {'imgSrc':require('../assets/images/filebox.png')},
          {'imgSrc':require('../assets/images/filebox.png')},
          {'imgSrc':require('../assets/images/filebox.png')}
      ],
      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.projectId = this.$LocalStorage.SessionGet("projectId");
      this.serviceId = this.$LocalStorage.SessionGet("serviceId");
      this.projectName=this.$LocalStorage.SessionGet("projectName");
      this.userType=this.$LocalStorage.SessionGet("userType");
      this.scanType=this.$LocalStorage.SessionGet("scanType");

      let materialsInfo=this.$LocalStorage.SessionGet("materialsInfo");//材料列表页面材料信息

      materialsInfo.forEach((obj,i)=>{
          if (this.scanType==1){
            this.initMaterialList.push(obj);//必传材料集合
            this.materials.push({'name':obj.name,'fileUrl':'',isMust:'1'});
          }else{
            if (obj.isMust=='1'){//是否必传，0:否  1:是
              this.initMaterialList.push(obj);//必传材料集合
              this.materials.push({'name':obj.name,'fileUrl':'',isMust:obj.isMust});
            }else{
              this.materials.push({'name':obj.name,'fileUrl':'',isMust:obj.isMust});
            }
          }
          this.imgDel.push({'name':'','imgSrc':require('../assets/images/ico/delete.png')});
      })
      this.pageInfo(this.curPage,this.num);

      if (robotType) robotsdk.getUserInfo(this.userInfoParameter);//获取办事人信息
      let materials = this.$LocalStorage.SessionGet("scanMaterials");//当前页面扫描缓存图片
      if (materials==null&&robotType)this.openVoice();//语音播放
      if (materials!=null){
          this.scanBtnIsShow=true;
          this.upStorageDate(1);
          if (this.$route.query.imgIndex!=null){//imgIndex图片查看页面所传参数  取消按钮不会传,删除按钮会传
            this.isHint=false;
            this.manyCount=0;
            this.delImg(this.$route.query.imgIndex,this.$route.query.fileId);
          }
          this.isTrue();//下一步按钮是否可点
          if (robotType)robotsdk.openHighCamera(this.highCameraParameter);//打开高拍仪预览界面
      }

      //将方法绑定到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:{
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.fileId) && res.set(arr.fileId, arr.fileId));
    },

    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("服务器异常,初始化失败！");//提示框
          }
        }).catch(err => {
          this.message("服务器异常,初始化失败！");//提示框
        })
      }
    },

    back() {
      if(robotType){
        robotsdk.closeExternalApp({
          mode:0
        });
      }
    },

    nextStep() {
        if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
        if (this.userType=='1') {//委托人类型办理
          let entrustMaterials = this.$LocalStorage.SessionGet("entrustMaterials");//委托人缓存材料
          this.materials=this.materials.concat(entrustMaterials);//委托人材料合并
        }

      this.materials = this.materials.filter(item => {//过滤过未上传材料
        return item.fileUrl!='';
      });

        let newArr = []; //存新数组
        this.materials.forEach((obj,i)=>{//去重材料,名字合并
           if (newArr.length==0){
             newArr.push(obj)
           }else{
             try {
               let isExist=false;
               newArr.forEach((arr,j)=>{
                 if (obj.fileId==arr.fileId){
                   isExist=true;
                   arr.name=arr.name+","+obj.name
                   throw("名称合并成功================");
                 }
               })
               if (!isExist){
                 newArr.push(obj)
               }
             }catch (e){
               console.info(e);
             }
           }
        })
        this.materials=newArr;
        this.upStorageDate(2);
        this.upStorageDate(4);
        this.$router.push({ path: '/auditing'});
    },

    scanBtn(){
      this.updateTimes();//刷新时间
      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));
    },

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

    lookImg(fileUrl,index,fileId){
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      this.upStorageDate(3);

      this.getManyCount(fileId);//判断当前材料是否包含其它材料
      let isMore=0;
      if (this.manyCount>1)
        isMore=this.manyCount;
      this.$router.push({path:'/scanMaterialLook',query:{fileUrl:fileUrl,index:index,fileId:fileId,isMore:isMore}});//查看当前图片页面
    },

    delImg(index,fileId){
        this.updateTimes()//刷新时间
        let newIndex=this.curPage*this.num-(this.num-index);//材料坐标位置
        this.indexFileId=this.materials[newIndex].fileId;//获取当前fileId
        if (this.isHint){
          this.getManyCount(fileId);//判断当前材料是否包含其它材料
          if (this.manyCount>1){//大于1为多份,与其它材料一起删除
            this.showConfirmMessage("当前材料还包含其它材料是否确认一起删除?");
          }else{
            this.delMaterialByFileId(newIndex,fileId);
          }
        }else{
          this.del(fileId);
        }
    },

    lookDetails(){
        if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
        this.upStorageDate(3);
        this.$router.push({path:'/material',query:{isCancel:false}});//查看材料详情页面
    },

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

    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"//接口回调函数
                });//虚拟人物播放语音及动作
              }
          }
    },

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

    HighCameraCallback(success, obj){
        if (success) {
            let res = eval('(' + obj + ')');//高拍仪回调的数据集
            $.post( window.config.rocrUrl+'lilo/aiCase/uploadFileNew', {
                fileName : res.filename,
                base64 : res.file,
                projectId: this.projectId,
            }).then(item => {
                if (item.success) {
                    this.masks(false);//遮罩层 true 打开 false 关闭
                    let fileName=item.obj.fileName;
                    if (fileName!=''){
                      if (fileName.lastIndexOf(",")!=-1) {//判断材料是否多份
                        let str_split=fileName.split(',');
                        str_split.forEach((str,index)=>{
                          this.isMore(str,item);
                          this.addMaterials(str,item);
                          this.manyCount=0;
                        })
                      }else{
                        this.isMore(fileName,item);
                        this.addMaterials(fileName,item);
                        this.manyCount=0;
                      }
                    }else {
                      this.message("服务器异常,扫描失败！");//提示框
                    }

                   this.isTrue();//下一步按钮是否可点

                    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.masks(false);//遮罩层 true 打开 false 关闭
                    this.message("服务器异常,扫描失败！");//提示框
                }
            }).catch(err => {
                this.masks(false);//遮罩层 true 打开 false 关闭
                this.message("服务器异常,扫描失败！");//提示框
            })
        } else {
            this.masks(false);//遮罩层 true 打开 false 关闭
            this.message("服务器异常,扫描失败！");//提示框
        }
    },

    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 用户点确认关闭
            });
        }
    },

    upStorageDate(type){
        //当前页面所需数据
        let scanDates=[{"name":"scanMaterials","value":this.materials},
                      {"name":"scanMaterialList","value":this.materialList},
                      {"name":"scanImgDel","value":this.imgDel},
                      {"name":"scanImgDelList","value":this.imgDelList},
                      {"name":"scanCurPage","value":this.curPage}];

        //后面页面所需的数据
        let dates={"projectId":this.projectId,
                   "serviceId":this.serviceId,
                   "projectName":this.projectName,
                   "name":this.name,
                   "idcard":this.idcard,
                   "mobile":this.mobile,
                   "fileData":this.materials}

        if (type==1)//获取缓存数据(详细说明返回回来接收)
            this.materials= this.$LocalStorage.SessionGet("scanMaterials");
            this.materialList= this.$LocalStorage.SessionGet("scanMaterialList");
            this.imgDel= this.$LocalStorage.SessionGet("scanImgDel");
            this.imgDelList= this.$LocalStorage.SessionGet("scanImgDelList");
            this.curPage= this.$LocalStorage.SessionGet("scanCurPage");
        if (type==2)//删除缓存数据(返回)
            scanDates.forEach(obj=>{this.$LocalStorage.SessionRemove(obj.name)});
        if (type==3)//存入缓存数据(详细说明)
            scanDates.forEach(obj=>{this.$LocalStorage.SessionPut(obj.name,obj.value)});
        if (type==4)//存入缓存数据(下一步)
            this.$LocalStorage.SessionPut("caseData",dates);
    },

    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.artificialType=item.obj.artificialType;
          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;
      }
    },

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

    ConfirmCallback(bool) {
      if (bool) {//确认
        if (this.manyCount>1) {
          this.del(this.indexFileId);
        }
      }else{
         this.manyCount=0;
      }
    },

    delMaterialByFileId(index,fileId){
         if (fileId!=null){
           $.post( window.config.rocrUrl+'lilo/aiCase/deleteFile', {
             fileId : fileId
           }).then(item => {
              if (item.success) {
                this.upMaterials(index);
              }else{
                this.message("服务器异常,删除失败！");//提示框
              }
           }).catch(err => {
             this.message("服务器异常,删除失败！");//提示框
           })
         }else{
           this.upMaterials(index);
         }
         this.isHint=true;
    },

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

        let isExist=false;
        try {
          this.initMaterialList.forEach((obj,i)=> {
            if (this.materials[index].name== obj.name) {
              isExist=true;
              throw("当前材料属于必传材料================");
            }
          })
        }catch (e){
          console.info(e);
        }

        let manyCount=0;//材料是否存在多份
        this.materials.forEach((obj,i)=>{
          if (indexName==obj.name.substring(0,indexName.length))
            manyCount=manyCount+1;
        })

        if (manyCount>1){
          if (isExist) {
            let mIndex = 0;
            this.materials.forEach((obj, i) => {
              let subName = obj.name.substring(0, indexName.length);
              let subInt=obj.name.substring(indexName.length);
              if (indexName == subName){
                if (parseInt(subInt) == 1)mIndex = i;
                if (parseInt(subInt) > 1) {
                  let count = parseInt(subInt) - 1;
                  obj.name = subName + count;
                }
              }
            })
            this.materials[index] = this.materials[mIndex];
            this.materials[index].name = indexName;
            this.materials.splice(mIndex, 1)
            this.imgDel.splice(mIndex, 1);
          } 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);
          }
        }else{
          if (isExist){
            this.imgDel[index].name='';
            this.materials[index].fileUrl='';
            this.isBtnNextShow=false;
          }else{
            this.materials.splice(index,1)
            this.imgDel.splice(index,1);
          }
        }
        this.manyCount=0;
        if (this.materialList.length==1&&this.curPage!=1)
          this.curPage = this.curPage-1;
        this.pageInfo(this.curPage,this.num);
    },

    getManyCount(fileId){
      this.materials.forEach((obj,i)=>{
        if (fileId==obj.fileId){
          this.manyCount=this.manyCount+1;
        }
      })
    },

    del(fileId){
        let count=0;
        this.materials.forEach((obj,index)=>{
          if (fileId==obj.fileId){
            count=count+1;
            if (count>1){
              this.delMaterialByFileId(index,null);
            }else{
              this.delMaterialByFileId(index,fileId);
            }
          }
        })
    },

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

    isTrue(){
      let bool=true;
      try {
        this.initMaterialList.forEach((o,i)=>{
          if (!bool)throw("材料未上传全结束外层循环================");
          try {
            this.materials.forEach((m,j)=>{
              if (o.name.indexOf(m.name)!=-1&&m.fileUrl==''){
                bool=false;
                throw("材料未上传全结束里层循环================");
              }
            })
          }catch (e){
            console.info(e);
          }
        })
      }catch (e){
        console.info(e);
      }
      if (bool) this.isBtnNextShow=true;
    },

    //语音回调（只处理扫描,下一步,退出）
    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: 25%;
  color:#FFFFFF;
  padding-top: 2%;
}
.imgFrame{
   height: 92px;
   width: 45%;
}
.wire{
  padding-top: 5%;
  border-bottom:solid #FFFFFF 1px;
  width: 26%;
  margin-left: 72%
 }
.btnUp{
  position: absolute;
  left: 75%;
  margin-top: 22%;
  z-index: 99;
}
.btnNext{
  position: absolute;
  left: 95%;
  margin-top: 22%;
  z-index: 97;
}
.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>