<template>
  <view>
    <u-popup
      v-model="isShow"
      mode="bottom"
      border-radius="40"
      :mask-close-able="false"
    >
      <!-- 播放前拍照start -->
      <!-- :mask-close-able="false" -->
      <!-- style="bottom: 0; position: fixed; width: 100%; z-index: 999" -->
      <view v-if="isShow">
        <view class="photoBox">
          <view class="photoTop">
            <view class="centersq">请正视手机屏幕</view>
          </view>
          <view class="photoCenter">
            <view class="center_camera" v-if="isTaking">
              <!-- #ifdef MP-WEIXIN -->
              <camera
                device-position="front"
                flash="off"
                @error="error"
                style="width: 100%; height: 100%"
              >
                <!-- 加人脸框 -->
                <cover-view class="head_take">
                  <cover-view class="headTake_up color"></cover-view>
                  <cover-view class="headTake_minddle">
                    <cover-view class="min_left color"></cover-view>
                    <cover-view class="min_img"></cover-view>
                    <cover-view class="min_right color"></cover-view>
                  </cover-view>
                  <cover-view class="headTake_down color"></cover-view>
                </cover-view>
              </camera>
              <!-- #endif -->
              <!-- #ifdef H5 -->
              <video
                :controls="false"
                id="video"
                width="400"
                height="300"
                class="photo_v"
              ></video>
              <view class="mask"></view>
              <!-- #endif -->
            </view>
            <view class="custom" v-if="!isTaking">
              <!-- #ifdef MP-WEIXIN -->
              <image :src="avatarUrl" mode=""></image>
              <!-- #endif -->
              <!-- #ifdef H5 -->
              <image :src="faceUrl" mode=""></image>
              <!-- #endif -->
            </view>
          </view>
          <view class="btns">
            <!-- <view class="btnResult" v-if="isTaking" @click="takePhoto"
              >拍照</view
            > -->
            <view v-if="isTaking" class="takePhoto_btn">
              <view style="width: 100rpx; height: 2rpx"></view>
              <view class="middle_btn" @click="takePhoto">
                <view class="square"></view>
              </view>
              <view class="rights" @click="takePhTips()">
                <text>拍照提示</text>
                <u-icon name="arrow-right" color="#FFFFFF" size="30"></u-icon>
              </view>
            </view>
            <view class="btnResult" v-if="!isTaking" @click="reTake">重拍</view>
            <view class="btnResult" v-if="!isTaking" @click="submit">确认</view>
          </view>
        </view>
      </view>
    </u-popup>
    <!-- 播放前拍照end -->
    <u-popup
      v-model="showSet"
      :mask-close-able="false"
      mode="center"
      border-radius="24"
    >
      <view
        style="
          align-items: center;
          padding: 0 40rpx;
          display: flex;
          flex-direction: column;
          justify-content: center;
        "
      >
        <view
          style="
            font-weight: bold;
            color: #333333;
            font-size: 30rpx;
            margin-top: 30rpx;
          "
          >温馨提示</view
        >
        <view
          style="
            width: 457rpx;
            color: #666666;
            font-size: 30rpx;
            margin-top: 30rpx;
          "
          >学习过程中需要拍照验证学员身份， 拍照功能需要使用您的相机。
          是否授权使用？</view
        >
        <view style="margin: 40rpx 0">
          <button
            open-type="openSetting"
            @bindopensetting="openSetting"
            class="btnSet"
          >
            去授权
          </button>
        </view>
      </view>
    </u-popup>
    <!-- 拍照提示 -->
    <popup-photo
      :popupPhotoShow.sync="popupPhotoShow"
      @takePhoto="openCamera"
    ></popup-photo>
  </view>
</template>

<script>
import myCompressImage from "@/common/compressPhoto.js";
import PopupPhoto from "./index.vue";
export default {
  name: "SaasMiniprogramCamera",
  inject: ["paramsFn"],
  data() {
    return {
      isShow: false,
      isTaking: true,
      avatarUrl: false,
      isCameraAuth: false,
      showSet: false,
      popupPhotoShow: false,
      faceUrl: "",
    };
  },

  mounted() {
    console.log(this.params, "params");
  },

  methods: {
    async submit() {
      if (this.uploadLock) {
        return;
      }
      this.uploadLock = true;
      let compareFaceData = await this.faceRecognition();
      if (compareFaceData >= 80) {
        this.$emit(
          "submitPhoto",
          await this.imageInfos(),
          compareFaceData,
          this.reTakeOrClose
        );
      } else {
        uni.showToast({
          title: "人脸匹配不通过，请重新拍照上传",
          icon: "none",
          duration: 2000,
        });

        setTimeout(() => {
          if (!this.isTaking) {
            this.reTake();
          }
        }, 2000);
      }
    },
    async imageInfos() {
      let resPath = await myCompressImage(this.avatarUrl || this.faceUrl, 50);
      const waitUpload = await this.$method.uploadFile(resPath, 0);
      return waitUpload;
    },
    reTakeOrClose(type = 0) {
      type ? this.reTake() : this.closeCamera();
    },
    exitFullscreen() {
      if (
        !!(
          document.webkitIsFullScreen ||
          document.mozFullScreen ||
          document.msFullscreenElement ||
          document.fullscreenElement
        )
      ) {
        try {
          var de = document;
          if (de.exitFullscreen) {
            de.exitFullscreen();
          } else if (de.mozCancelFullScreen) {
            de.mozCancelFullScreen();
          } else if (de.webkitCancelFullScreen) {
            de.webkitCancelFullScreen();
          }
        } catch (err) {}
      }
    },
    closeCamera() {
      this.isShow = false;
      this.showSet = false;
      this.popupPhotoShow = false;
    },

    openCamera() {
      this.uploadLock = false;
      // 退出全屏
      this.exitFullscreen();
      // 同一个商品只谈一次提示
      let popupList = uni.getStorageSync("popupList") || [];
      if (!popupList.includes(this.goodsId)) {
        popupList.push(this.goodsId);
        uni.setStorageSync("popupList", popupList);
        this.popupPhotoShow = true;
        return;
      }
      // #ifdef MP-WEIXIN
      // 屏幕亮度
      uni.setKeepScreenOn({
        keepScreenOn: true,
      });
      uni.getSetting({
        success: (res) => {
          if (res.authSetting["scope.camera"]) {
            this.isCameraAuth = true;
          } else {
            wx.authorize({
              scope: "scope.camera",
              success: () => {
                this.isCameraAuth = true;
                this.showCamera();
              },
              fail: () => {
                this.isCameraAuth = false;
                this.showSet = true;
              },
            });
          }
        },
        fail: (res) => {},
      });
      // #endif
      // #ifdef H5
      if (
        (window.navigator.mediaDevices &&
          window.navigator.mediaDevices.getUserMedia) ||
        window.navigator.getUserMedia ||
        window.navigator.webkitGetUserMedia ||
        window.navigator.mozGetUserMedia
      ) {
        console.log("getUserMedia----");
        // 调用用户媒体设备, 访问摄像头
        this.getUserMedia(
          {
            video: {
              width: 400,
              height: 300,
              facingMode: "user",
            },
          },
          this.photographSuccess,
          this.photographError
        );
      } else {
        console.log("1111没有摄像");
        this.photographError();
      }
      // #endif
    },
    showCamera() {
      this.isTaking = true;
      this.isShow = true;
    },
    //确认拍照
    takePhoto() {
      // #ifdef MP-WEIXIN
      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: "high",
        success: (res) => {
          this.avatarUrl = res.tempImagePath;
          console.log("开始拍照this.avatarUrl:", this.avatarUrl);
          this.isTaking = false;
        },
        fail: (err) => {},
      });
      // #endif
      // #ifdef H5
      const canvas = document.createElement("canvas");
      canvas.width = 400;
      canvas.height = 400;
      const context = canvas.getContext("2d");
      const box = document.querySelector(".photo_v");
      const video = box.querySelector("video");
      context.drawImage(video, 0, 0, 400, 400);
      this.faceUrl = canvas.toDataURL("image/png");
      this.isTaking = false;
      // #endif
    },
    reTake() {
      console.log("🚀 ~ file: camera.vue:287 ~ reTake ~ reTake:", "reTake");
      this.uploadLock = false;
      this.isTaking = true;
      // #ifdef H5
      this.faceUrl = "";
      this.getUserMedia(
        {
          video: {
            width: 400,
            height: 300,
            facingMode: "user",
          },
        },
        this.photographSuccess,
        this.photographError
      );
      // #endif
    },

    /**
     * 人脸匹配
     */
    faceRecognition() {
      return new Promise((resolve) => {
        // #ifdef MP-WEIXIN
        let fileSystem = uni.getFileSystemManager();
        fileSystem.readFile({
          filePath: `${this.avatarUrl}`,
          encoding: "base64",
          position: 0,
          success: (res) => {
            let base64 = "data:image/jpg;base64," + res.data;
            this.CompareFace(base64, resolve);
          },
          fail(err) {
            // this.$u.toast('人脸识别错误!')
            console.error(err, "err-----人脸识别错误");
          },
        });
        // #endif
        // #ifdef H5
        this.CompareFace(this.faceUrl, resolve);
        // #endif
      });
    },
    CompareFace(url, resolve) {
      let timer = setTimeout(() => {
        uni.showToast({
          icon: "none",
          title: "拍照超时，请重新拍照",
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          },
        });
      }, 10 * 1000);

      this.$api
        .faceCertificationCompareFace({
          imageA: url,
          orderGoodsId: this.params.orderGoodsId,
          gradeId: this.params.gradeId,
        })
        .then((res) => {
          clearTimeout(timer);
          console.log(res, "人脸识别成功res");
          resolve(res.data.data);
        })
        .catch((err) => {
          clearTimeout(timer);
          // 当前网络延迟，
          console.log("人脸识别错误:", err);
          uni.showModal({
            content: "当前网络延迟",
            showCancel: false,
            success: (resultst) => {
              if (resultst.confirm) {
                uni.navigateBack();
              }
            },
          });
        });
    },
    photographSuccess(stream) {
      console.log("有摄像头---", stream);
      this.isCameraAuth = true;
      this.showCamera();
      this.$nextTick(() => {
        const box = document.querySelector(".photo_v");
        console.log("🚀 ~ file: camera.vue:375 ~ this.$nextTick ~ box:", box);
        const video = box.querySelector("video");
        video.srcObject = stream;
        video.play();
      });
    },
    photographError(err) {
      console.log("没有摄像头：", err);
      uni.showModal({
        title: "提示",
        content:
          "课程学习需要开启摄像头进行拍照，经检测您的设备无摄像头可使用，请检测环境是否支持。",

        cancelText: "取消",
        confirmText: "确定",
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          } else if (res.cancel) {
          }
        },
      });
    },
    getUserMedia(constraints, success, error) {
      console.log("getUserMedia===", constraints);
      if (window.navigator.mediaDevices.getUserMedia) {
        // 最新的标准API
        window.navigator.mediaDevices
          .getUserMedia(constraints)
          .then(success)
          .catch(error);
      } else if (window.navigator.webkitGetUserMedia) {
        // webkit核心浏览器
        window.navigator.webkitGetUserMedia(constraints, success, error);
      } else if (window.navigator.mozGetUserMedia) {
        // firfox浏览器
        window.navigator.mozGetUserMedia(constraints, success, error);
      } else if (window.navigator.getUserMedia) {
        // 旧版API
        window.navigator.getUserMedia(constraints, success, error);
      }
    },
  },
  computed: {
    params() {
      return this.paramsFn();
    },
    goodsId() {
      return this.params.goodsId;
    },
  },
  components: {
    PopupPhoto,
  },
};
</script>

<style lang="scss" scoped>
.btnSet {
  width: 440rpx;
  height: 80rpx;
  background: #007aff;
  border-radius: 40rpx;
  color: #ffffff;
  font-size: 28rpx;
  line-height: 80rpx;
}
.photoBox {
  width: 100%;
  // background-color: #ffffff;
  // border-radius: 24px 24px 0px 0px;
  .photoTop {
    width: 100%;
    height: 74rpx;
    border-radius: 20px 20px 0px 0px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0rpx 38rpx;
    .centersq {
      color: #333;
      font-size: 30rpx;
      font-weight: 500;
    }
  }
  .photoCenter {
    width: 750rpx;
    height: 75vh;
    position: relative;
    .center_camera {
      width: 100%;
      height: 75vh;
      position: fixed;
      .head_take {
        width: 100%;
        height: 75vh;
        display: flex;
        flex-direction: column;
      }
      .headTake_up {
        width: 100%;
        height: 100rpx;
      }
      .headTake_minddle {
        display: flex;
        .min_img {
          width: 500rpx;
          height: 550rpx;
        }
        .min_left,
        .min_right {
          flex: 1;
          height: 550rpx;
        }
      }
      .headTake_down {
        width: 100%;
        flex: 1;
      }
      .color {
        background-color: #333;
        opacity: 0.5;
      }
      .photo_v {
        width: 100%;
        height: 100%;
      }
      .mask {
        width: 500rpx;
        height: 550rpx;
        position: absolute;
        top: 100rpx;
        left: 0;
        right: 0;
        bottom: 0;
        margin: 0 auto;
        box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.4);
      }
    }
    .custom {
      width: 750rpx;
      height: 75vh;
      position: absolute;
      z-index: 1000;
      top: 0;
      left: 0;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .btns {
    display: flex;
    .takePhoto_btn {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #a9a7a9;
      padding: 40rpx 26rpx;
      .middle_btn {
        width: 120rpx;
        height: 120rpx;
        border-radius: 40rpx;
        border: 4rpx solid #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .square {
        width: 96rpx;
        height: 96rpx;
        background: #ffffff;
        border-radius: 28rpx;
      }
      .rights {
        font-size: 32rpx;
        font-weight: 500;
        color: #ffffff;
      }
    }
    .btnResult {
      height: 100rpx;
      flex: 1;
      background-color: #07c160;
      text-align: center;
      line-height: 100rpx;
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }
  }
}
</style>
