<template>
  <!-- 人脸识别页面 -->
  <view class="content">
    <!-- 拍照区域 -->
    <view class="cameraField">
      <!-- 上传的人脸图片 -->
      <canvas
        canvas-id="canvas"
        id="canvas"
        type="2d"
        style="width: 100%; height: 100%"
      ></canvas>
      <!-- 提示框 -->
      <view class="hint" v-if="isShow3">
        <image :src="hintImage" />
        {{ hintWord }}
      </view>
      <!-- 头像限制框    -->
      <image
        class="head"
        src="../../static/images/head1.png"
        mode="scaleToFill"
      />
    </view>
    <!-- 控件区域 -->
    <view class="controlField">
      <!-- 拍照控件 -->
      <view class="control1" v-if="isShow1">
        <view class="light">
          <!-- <image class="light" src="../../static/images/light.png" /> -->
        </view>
        <view @click="takePhoto()">
          <image class="take" src="../../static/images/take.png" />
        </view>
        <view class="change">
          <!-- <image class="change" src="../../static/images/change.png" /> -->
        </view>
      </view>
      <!-- 重拍/上传控件 -->
      <view class="control2" v-if="isShow2">
        <view @click="resetPhoto">重拍</view>
        <view @click="upload">使用照片</view>
      </view>
    </view>
  </view>
</template>

<script>
import { EXIF } from "../../node_modules/exif-js/exif"; //引入exif.js判断图片旋转方向
import { mapState, mapMutations } from "vuex"; //引入vuex
import {
  pathToBase64,
  base64ToPath,
} from "../../js_sdk/mmmm-image-tools/index.js";
export default {
  data() {
    return {
      isShow1: true, //拍照控件
      isShow2: false, //重拍/上传控件
      isShow3: true, //提示框
      // isShow4: false, //“上传中”提示框
      hintImage: "../../static/images/hint@2x.png", //提示图标
      hintWord: "请勿遮挡面部", //提示文字
      imgPath: "", //上传的人脸图片本地路径
      tipFlag: "", //手机机型
      maxWidth: "", //手机屏幕宽度
      maxHeight: "", //手机屏幕高度
    };
  },

  computed: mapState(["position", "userData"]),

  onLoad(options) {
    //判断设备机型
    let that = this;

    (function () {
      var u = navigator.userAgent;

      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //android终端或者uc浏览器

      var isiOS = u.indexOf("iPhone") > -1; //苹果手机

      if (isiOS) {
        that.tipFlag = "ios";
      }
      if (isAndroid) {
        that.tipFlag = "Android";
      }
    })();
  },

  methods: {
    ...mapMutations(["getPosition", "getUserData"]),

    //拍照控件变重拍上传控件
    takeToReset() {
      this.isShow1 = !this.isShow1;
      this.isShow2 = !this.isShow2;
    },
    //拍照
    takePhoto() {
      this.photo();
    },
    //重拍
    resetPhoto() {
      this.isShow1 = !this.isShow1;
      this.isShow2 = !this.isShow2;
      this.photo();
    },
    //照片
    photo() {
      let that = this;

      uni.chooseImage({
        count: 1,
        sourceType: ["camera"],
        sizeType: ["compressed"],
        success: (res) => {
          //获取设备屏幕尺寸
          uni.getSystemInfo({
            success: function (res2) {
              that.maxWidth = res2.screenWidth;

              let base = 4 / 3;

              that.maxHeight = that.maxWidth * base;
            },
          });

          that.imgPath = res.tempFilePaths[0]; //这就是要的blod

          that.toBase64(that.imgPath); //转base64图片

          //图片显示
          if (that.tipFlag == "ios") {
            let canvas = uni.createCanvasContext("canvas");

            canvas.drawImage(that.imgPath, 0, 0, that.maxWidth, that.maxHeight);

            canvas.draw();

            this.takeToReset(); //图片显示后显示重拍控件
          } else {
            that.detail(that.imgPath);
          }
        },
      });
    },

    //安卓机图片修正
    async detail(url) {
      let Orientation = 1;

      //获取图片META信息
      await this.getImageTag(url, "Orientation", function (e) {
        if (e != undefined) Orientation = e;
      });

      var img = null;

      var canvas = null;
      await this.comprossImage(url, function (e) {
        img = e.img;
        canvas = e.canvas;
      });

      //  console.log(Orientation,"Orientation")
      //如果方向角不为1，都需要进行旋转
      switch (Orientation) {
        case 6: //需要顺时针（向右）90度旋转
          this.rotateImg(img, "right", canvas);
          break;
        case 8: //需要逆时针（向左）90度旋转
          this.rotateImg(img, "left", canvas);
          break;
        case 3: //需要180度旋转 转两次
          this.rotateImg(img, "right", canvas, 2);
          break;
        default:
          this.rotateImg(img, "", canvas);
          break;
      }
    },

    async comprossImage(imgSrc, func) {
      if (!imgSrc) return 0;
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: imgSrc,
          success(res) {
            let img = new Image();
            img.src = res.path;
            // console.log(img);
            let canvas = uni.createCanvasContext("canvas");
            let obj = new Object();
            obj.img = img;
            obj.canvas = canvas;
            resolve(func(obj));
          },
        });
      });
    },

    getImageTag(file, tag, suc) {
      if (!file) return 0;
      return new Promise((resolve, reject) => {
        /* eslint-disable func-names */
        // 箭头函数会修改this，所以这里不能用箭头函数
        let imgObj = new Image();
        imgObj.src = file;
        // console.log(imgObj);
        uni.getImageInfo({
          src: file,
          success(res) {
            EXIF.getData(imgObj, function () {
              EXIF.getAllTags(this);
              let or = EXIF.getTag(this, "Orientation"); //这个Orientation 就是我们判断需不需要旋转的值了，有1、3、6、8
              resolve(suc(or));
            });
          },
        });
      });
    },

    rotateImg(img, direction, canvas, times = 1) {
      // console.log("开始旋转");
      //最小与最大旋转方向，图片旋转4次后回到原方向
      var min_step = 0;

      var max_step = 3;

      if (img == null) return;
      //img的高度和宽度不能在img元素隐藏后获取，否则会出错
      var height = img.height;
      var width = img.width;
      let maxWidth = this.maxWidth;
      let maxHeight = this.maxHeight;
      var step = 0;
      if (step == null) {
        step = min_step;
      }
      if (direction == "right") {
        step += times;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
      } else if (direction == "left") {
        step -= times;
        step < min_step && (step = max_step);
      } else {
        //不旋转
        step = 0;
      }
      //旋转角度以弧度值为参数
      var degree = (step * 90 * Math.PI) / 180;
      var ctx = uni.createCanvasContext("canvas");
      // console.log(degree);
      // console.log(step);
      switch (step) {
        case 1:
          // console.log("右旋转 90度");
          width = maxHeight;
          height = maxWidth;
          ctx.rotate(degree);
          ctx.drawImage(img.src, 0, -height, width, height);
          ctx.draw();
          this.takeToReset();
          break;
        case 2:
          //console.log('旋转 180度')
          width = maxWidth;
          height = maxHeight;
          ctx.rotate(degree);
          ctx.drawImage(img.src, -width, -height, width, height);
          ctx.draw();
          this.takeToReset();
          break;
        case 3:
          // console.log("左旋转 90度");
          width = maxHeight;
          height = maxWidth;
          ctx.rotate(degree);
          ctx.drawImage(img.src, -width, 0, width, height);
          ctx.draw();
          this.takeToReset();
          break;
        default:
          //不旋转
          width = maxWidth;
          height = maxHeight;
          ctx.drawImage(img.src, 0, 0, width, height);
          ctx.draw();
          this.takeToReset();
          break;
      }
    },
    //上传图片
    upload() {
      let idnum = this.$store.state.idnum;

      let image = this.$store.state.imageBase;

      this.isShow3 = !this.isShow3;

      uni.showToast({
        title: "人脸匹配中",
        icon: "loading",
        mask: true,
        duration: 2000,
      });
      if (idnum && image) {
        uni.request({
          url: "https://jtishfw.ncjti.edu.cn/yinxin/ncjtSecurityManagement/verifyBase64ImagesWithIDNumber",
          data: {
            idnum: idnum,
            image: image,
          },
          header: { "content-type": "application/x-www-form-urlencoded" },
          method: "POST",
          sslVerify: true,
          success: ({ data, statusCode, header }) => {
            if (data.error) {
              uni.showToast({
                title: "人脸匹配失败",
                icon: "error",
                mask: true,
                duration: 1000,
              });
              setTimeout(this.back, 1000);
            } else {
              this.$store.state.sex = data.sex;
              this.$store.state.examNumber = data.examNumber;
              setTimeout(this.uploadSucceed, 500);
            }
          },
          fail: () => {
            uni.showToast({
              title: "人脸提交失败",
              icon: "error",
              mask: true,
              duration: 1000,
            });
            setTimeout(this.back, 1000);
          },
        });
      } else {
        uni.showToast({
          title: "image或idnum不能为空",
          icon: "error",
          mask: true,
          duration: 1500,
        });
        this.isShow3 = !this.isShow3;
      }
    },
    //人脸采集成功
    uploadSucceed() {
      this.hintWord = "人脸匹配成功";
      this.hintImage = "../../static/images/success@2x.png";
      this.isShow3 = !this.isShow3;
      this.takeToReset();
      setTimeout(this.navigateToConfirm, 1500);
    },
    //图片转Base64
    toBase64(path) {
      pathToBase64(path)
        .then((base64) => {
          this.$store.state.imageBase = base64;
          console.log(this.$store.state.imageBase);
        })
        .catch((error) => {
          console.error(error);
        });
    },
    //跳转人脸采集确认页面
    navigateToConfirm() {
      uni.navigateTo({
        url: "/pages/confirm/confirm",
      });
    },
    //返回重新拍照
    back() {
      uni.reLaunch({
        url: "/pages/faceSearch/faceSea",
      });
    },
  },
};
</script>

<style lang="scss">
@import url("./css/faceSea.min.css");
</style>
