<template>
  <b-page @bPageLoaded="voiceCallback"></b-page>
  <count-down times=300 bottomOffset="10" rightOffset="10" fontSize="24" ref="child"></count-down>
  <template v-if="schedule == 0">
  <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="!BtnIsShow"  src="../../assets/images/btn/backGray.png">
        <img class="imgButton" v-if="BtnIsShow" @click="back" src="../../assets/images/btn/btnCancel.png">&nbsp;&nbsp;&nbsp;&nbsp;
        <!-- 下一步按钮 -->
        <img class="imgButton" v-if="!isBtnNextShow" src="../../assets/images/btn/btnPrint_Not.png">
        <img class="imgButton" v-if="isBtnNextShow" @click="nextStep('print')" src="../../assets/images/btn/btnPrint.png">
        <!-- 扫描按钮 -->
        <img class="imgButton" v-if="!BtnIsShow"  src="../../assets/images/btn/scanGray.png" style="margin-left: 25px">
        <img class="imgButton" v-if="BtnIsShow && scanBtnIsShow" @click="scanBtn" src="../../assets/images/btn/btnScan.png" style="margin-left: 25px">
        <!--核验-->
        <img class="imgButton" v-if="BtnIsShow && verBtnIsShow" @click="verBtn" src="../../assets/images/btn/verBtn.png" style="margin-left: 25px">
      </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>

  <template v-if="schedule == 1" >
    <div class="printMaterial">
      <div style="padding-top: 5%;">
        <div style="margin-top: 120px;">
          <img style="width: 374px;height: 294px" src="../../assets/images/print.gif" >
        </div>
        <div style="margin-top: 50px;">
          <font size="6" color="#FFFFFF">请稍等，系统正在为您打印！</font>
        </div>
      </div>
    </div>
  </template>

  <template v-if="schedule == 2" >
    <div class="printMaterial">
      <div style="padding-top: 5%;">
        <div style="margin-top: 120px;">
          <img style="width: 190px;height: 190px" src="../../assets/images/ico/ico_ok.png" >
        </div>
        <div style="margin-top: 150px;">
          <font size="6" color="#FFFFFF">已为您打印成功,稍后系统将返回首页！</font>
        </div>
      </div>
    </div>
  </template>
  <template v-if="schedule == 3" >
    <div class="printMaterial">
      <div style="padding-top: 5%;">
        <div style="margin-top: 120px;">
          <img style="width: 280px;height: 190px" src="../../assets/images/ico/ico_normal.png" >
        </div>
        <div style="margin-top: 150px;">
          <font size="6" color="#FFFFFF">您的身份证验证已通过！</font>
        </div>
      </div>
    </div>
  </template>
  <template v-if="schedule == 4" >
    <div class="printMaterial">
      <div style="padding-top: 5%;">
        <div style="margin-top: 120px;">
          <img style="width: 280px;height: 190px" src="../../assets/images/ico/ico_abnormal.png" >
        </div>
        <div style="margin-top: 150px;">
          <font size="6" color="#FFFFFF">您的身份证验证不通过！稍后将返回系统首页！</font>
        </div>
      </div>
    </div>
  </template>
</template>

<script>
import material from "@/views/material";
import BPage from "@/components/registerVoice";

export default{
  components: {
    BPage,
  },

  data() {
    return {
      name: "",
      idcard: "",
      applyType: "",//1:身份证核验打印
      schedule: "",
      curPage: 1,//当前页码
      num: 5,//每页展示数量
      materials: [],//材料集合
      materialList:[],//当前页面图片展示
      imgDel:[],//删除按钮集合
      imgDelList:[],//当前页面删除按钮展示
      isRepetition:false,//是否重复材料
      type:0,//0:默认不覆盖,1:覆盖身份证正面,2:覆盖身份证反面,3:只删除当前上传材料
      temporary:[],//临时集合,用于是否覆盖材料使用
      BtnIsShow:false,//控制取消,按钮是否显示
      scanBtnIsShow:false,//扫描按钮是否亮起
      verBtnIsShow: false,//核验按钮是否显示
      isBtnNextShow:false,//控制打印按钮是否亮起
      imgFrames:[
        {'imgSrc':require('../../assets/images/filebox.png')},
        {'imgSrc':require('../../assets/images/filebox.png')},
      ],//图片框集合
      highCameraParameter:{//高拍仪参数
        x: 68,//预览界面x坐标
        y: 47,//预览界面y坐标
        width: 900,//预览界面宽度
        height: 676,//预览界面高度
      },
      userInfoParameter:{//办事人信息
        callback: "getUserInfo"
      },
      highCameraImgParameter:{//获取高拍仪照片
        callback: "HighCameraCallback"
      },
      IdentificationParameter:{//获取身份信息
        callback: "IdentificationCallback"
      },
      count:0,
    }
  },
  created() {
    this.schedule = 0;
    this.name = "",
    this.idcard = "",
    this.applyType = "1";//1:身份证核验打印
    this.materials.push({'name':'身份证正面','fileUrl':'','fileId':'','artificialType':'','type':''});
    this.materials.push({'name':'身份证反面','fileUrl':'','fileId':'','artificialType':'','type':''});

    this.imgDel.push({'name':'','fileUrl':'','fileId':'','artificialType':'','type':''});
    this.imgDel.push({'name':'','fileUrl':'','fileId':'','artificialType':'','type':''});

    this.pageInfo(this.curPage,this.num);
    if (robotType)this.openVoice( "请您将身份证正面放入扫描框进行扫描");
    if (robotType)robotsdk.getUserInfo(this.userInfoParameter);//获取办事人信息

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

    back() {
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      if(robotType){
        robotsdk.closeExternalApp({//退出跳转咨询页面
          mode:0
        });
      }
    },
    nextStep(type) {//打印
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      this.schedule = 1;
      $.post(window.config.rocrUrl + 'lilo/apply/idcardImg2word', {//打印
        type: type,
        name: this.name,
        idcard: this.idcard,
        materials:JSON.stringify(this.materials),
      }).then(item => {
        this.masks(false);
        robotsdk.printFile({
          filetype: 'doc',
          base64: item.obj.base64,
          remoteprintname: "",
          replyvoice: '请稍等，系统正在为您进行打印！',
          callback: "printCallBack"
        });
      })
    },

    printCallBack(bool){//打印回调
      if (bool){//打印成功返回true
        this.schedule = 2;
        this.masks(false);
        robotsdk.playAudio({
          cmd: "cmd",
          animation: 0,
          videocontent: "已为您打印成功,稍后系统将返回首页",
          callback: "PlayAudio_printCallback"
        })
      }else {
        this.$router.push({ path: '/errorPage',query: {msg: '打印失败'}});//转跳错误提示页面
      }
    },
    PlayAudio_printCallback(res){//打印语音回调
      if (res=="cmdOK") {
        let timer = setInterval(() => {
          //需要定时执行的代码
          if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
          this.back();//退出
        },1000)
      }
    },
    scanBtn(){//扫描
      this.$refs.child.counter=300; //刷新时间
      this.masks(true);//遮罩层 true 打开 false 关闭
      if (robotType)robotsdk.getHighCamera(this.highCameraImgParameter);//获取高拍仪照片
    },
    verBtn(){//核验
      this.$refs.child.counter=300; //刷新时间
      // this.masks(true);//遮罩层 true 打开 false 关闭
      if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
      if (robotType)robotsdk.openIdentification(this.IdentificationParameter);//开启身份验证
    },
    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;
      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.BtnIsShow=true;
          this.scanBtnIsShow = true;
          robotsdk.playAudio({//语音播放参数
            cmd: "sm",//语音指令，可参考属性voiceInstruct
            animation: 0,//虚拟任务动作编号可参考属性animationEnum
            videocontent: "",//语音内容
            callback: "PlayAudioCallback"//接口回调函数
          });//虚拟人物播放语音及动作
        }
      }
    },
    IdentificationCallback(obj){//身份核验
      if (obj==""){

      }else {
        let res = eval('(' + obj + ')');//人脸身份核验回调的数据集
        this.name = res.name;
        this.idcard = res.idcard;
        $.post( window.config.rocrUrl+'lilo/apply/idcardImg2word', {
          type: "verification",
          idcard : this.idcard,
          name : this.name,
          materials:JSON.stringify(this.materials),
        }).then(item => {
          if (item.obj.isPass){
            this.schedule = 3;
            robotsdk.playAudio({//语音播放参数
              cmd: "cmd",//语音指令，可参考属性voiceInstruct
              animation: 0,//虚拟任务动作编号可参考属性animationEnum
              videocontent: "您的身份已验证通过",//语音内容
              callback: "playAudioCallback1"//接口回调函数
            });//虚拟人物播放语音及动作
          }else {
            this.schedule = 4;
            robotsdk.playAudio({//语音播放参数
              cmd: "cmd",//语音指令，可参考属性voiceInstruct
              animation: 0,//虚拟任务动作编号可参考属性animationEnum
              videocontent: "您的身份验证不通过,稍后将返回系统首页",//语音内容
              callback: "playAudioCallback1"//接口回调函数
            });//虚拟人物播放语音及动作
          }
        })
      }
    },
    playAudioCallback1(res){
      if (res=="cmdOK"){
        if (robotType){
          if (this.schedule==4){
            let timer = setInterval(() => {
              //需要定时执行的代码
              if (robotType)robotsdk.closeHighCamera();//关闭高拍仪
              this.back();//退出
            },1000)
          }else {
            this.nextStep("verification");
          }
        }
      }
    },
    HighCameraCallback(success, obj){
      if (success) {
        let res = eval('(' + obj + ')');//高拍仪回调的数据集
        $.post( window.config.rocrUrl+'lilo/apply/uploadFile', {
          applyType: this.applyType,//1:身份证核验打印
          cutImage: "true",//需要切图
          fileName : res.filename,
          base64 : res.file,
        }).then(item => {
          if (item.success) {

            this.masks(false);//遮罩层 true 打开 false 关闭
            let fileName=item.obj.fileName;
            if (fileName!=''){
              if (fileName.lastIndexOf("身份证")!=-1) {
                let identity =eval('(' + item.obj.jsonData + ')');//身份证信息
                try {
                  identity.forEach((obj,index)=>{
                    // if (obj.isOriginal=="1"){
                      if (obj.name!="" && obj.name!=undefined && obj.name!=null){
                        this.masks(false);//遮罩层 true 打开 false 关闭;
                        if(this.materialList[0].fileId==''){
                          this.upMaterials(0,item);//更新身份证正面数据
                        }else{
                          this.type=1;
                          this.temporary=item;
                          this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                        }
                        robotsdk.playAudio({//语音播放参数
                          cmd: "sm",//语音指令，可参考属性voiceInstruct
                          animation: 0,//虚拟任务动作编号可参考属性animationEnum
                          videocontent: "身份证正面扫描成功",//语音内容
                          callback: ""//接口回调函数
                        });//虚拟人物播放语音及动作
                      }else {
                        this.masks(false);//遮罩层 true 打开 false 关闭;
                        if(this.materialList[1].fileId==''){
                          this.upMaterials(1,item);//更新身份证反面数据
                        }else{
                          this.type=2;
                          this.temporary=item;
                          this.showConfirmMessage("检测到材料已上传过是否覆盖最新?");
                        }
                        robotsdk.playAudio({//语音播放参数
                          cmd: "sm",//语音指令，可参考属性voiceInstruct
                          animation: 0,//虚拟任务动作编号可参考属性animationEnum
                          videocontent: "身份证反面扫描成功",//语音内容
                          callback: ""//接口回调函数
                        });//虚拟人物播放语音及动作
                      }
                    // }else {
                    //   this.message("请提交身份证原件！");//提示框
                    // }
                  })
                }catch (e){
                  console.info(e);
                }

                let oneFileUrl=this.materials[0].fileUrl;
                let twoFileUrl=this.materials[1].fileUrl;
                if (oneFileUrl!=''&&twoFileUrl!=''){
                  robotsdk.playAudio({//语音播放参数
                    cmd: "sm",//语音指令，可参考属性voiceInstruct
                    animation: 0,//虚拟任务动作编号可参考属性animationEnum
                    videocontent: "您可以点击打印按钮进行打印,或点击核验按钮进行身份核验并打印",//语音内容
                    callback: ""//接口回调函数
                  });//虚拟人物播放语音及动作
                  this.isBtnNextShow = true;
                  this.verBtnIsShow = true;
                  this.scanBtnIsShow = false;
                }
              }else{
                this.message("请勿提交其它文件！");//提示框
              }
            }
          }else {
            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 用户点确认关闭
        });
      }
    },
    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].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');

    },

    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.type=4;//4:删除当前上传材料，不做其它操作
          this.delMaterialByFileId(null,this.temporary.obj.fileId);
        }
      }
    },

    delMaterialByFileId(index,fileId){
      $.post( window.config.rocrUrl+'lilo/apply/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.materials[index].fileId='';
            this.isBtnNextShow=false;
            this.verBtnIsShow = false;
            this.scanBtnIsShow = true;
          }
          //覆盖材料更新
          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("服务器异常,删除失败！");//提示框
      })
    },

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

      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;
}
.printMaterial{
  background-image: url('../../assets/images/background.png');
  background-repeat: no-repeat;
  background-size: cover;
  overflow:auto;
  margin-bottom: 20px;
  padding: 0 70px;
  height:100%;

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