<template>
  <!-- 头像 -->
  <div v-if="show" class="w-full h-screen overflow-y-scroll relative z-2001 bg-black pb-4">
    <div class="header w-full px-4 bg-black fixed top-0 left-0 z-2001 h-12 flex items-center justify-between">
      <app-icon
        class-name="w-6.5 h-6.5"
        icon-name="left-arrow-white"
        @click="goBack"
      />
      <div class="text-white">团队头像</div>
      <div class="">
        <!-- <div class="px-4 py-3 text-center">拍照</div> -->
        <div @click="uploadFile">
          <app-icon
            class-name="w-6.5 h-6.5"
            icon-name="photo"
          />
          <input
            type="file"
            id="uploadFile"
            ref="uploadFile"
            accept="image/*"
            class="hidden"
            @input="fileHandler"
          />
        </div>
      </div>
      <!-- <app-icon
        class-name="w-5 h-1"
        icon-name="dot-h"
        @click="showActionSheet=true"
      /> -->
    </div>
    <div class="py-16 px-6">
      <!-- 默认头像 -->
      <div v-if="showDefault" class="mt-4">
        <div class="default-avator flex items-center justify-center rounde overflow-hidden mx-auto">
          <img v-if="defaultImg" :src="defaultImg" alt="">
          <div v-else class="text-gray-200">暂无头像</div>
        </div>
        <c-button v-if="defaultImg" class="mt-4" @click="saveImage">保存</c-button>
      </div>
      <!-- 裁剪图片 -->
      <div class='cropper-wrapper' v-if="showCropper">
        <div class="before"></div>
        <!-- <div class="w-screnn h-screnn bg-center" > -->
        <img :src="img" alt="" class="" ref="image">
        <div class="fixed z-2001 bottom-0 left-0 w-full py-1.5 px-4">
          <c-button @click="saveCropper">保存</c-button>
        </div>
      </div>
    
      <!-- 拍照 -->
      <div v-if="showCamera">
        <video class="video-view" ref="video" autoplay playsinline="true" webkit-playsinline="true" />
        <canvas ref="canvas" :width="cameraWidth" :height="cameraHeight" style="display: none"></canvas>
        <c-button class="mt-4" @click="saveImg">拍照</c-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Cropper from "cropperjs"
import "cropperjs/dist/cropper.css"

export default Vue.extend({
  name: 'AvatorEditor',
  components: {
    'app-icon':()=>import('@/components/common/Icon.vue'),
    'main-page': () => import('@/layout/main-page.vue'),
    'c-cell': () => import('@/components/common/c-cell.vue'),
    'c-button': () => import('@/components/common/c-button.vue'),
    'input-cell': () => import('@/components/common/input-cell.vue')
  },
  props: {
    imgSrc: String,
    show: Boolean
  },
  data() {
    return {
      cameraWidth: 0,
      cameraHeight: 0,
      stream: {} as any,
      myCropper: {} as Cropper,
      // showVideo: false,
      showCropper: false,
      showCamera: false,
      showDefault: true,
      img: '',
      defaultImg: ''
    }
  },
  watch: {
    imgSrc: {
      handler (val: string) {
        this.defaultImg = val
      },
      immediate: true
    }
  },
  methods: {
    fileHandler(e: InputEvent) {
      const target = e.target as HTMLInputElement
      if (target.files && target.files?.length !== 0) {
        console.log(target.files)
        const file = target.files[0]
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = () => {
          this.img = reader.result as string
          this.defaultImg = reader.result as string
          // this.showCropper = true
          // this.showDefault = false
          // this.$nextTick(() => {
          //   this.initCropper()
          // })
        }
      }
    },
    uploadFile() {
      const fileInput = this.$refs.uploadFile as HTMLInputElement
      fileInput.click()
    },
    goBack() {
      this.$emit('update:show', false)
    },
    // 保存头像
    saveImage() {
      this.showCropper = false
      this.$emit('update:img-src', this.defaultImg)
      this.$emit('update:show', false)
    },
    openCamera() {
      if (
        (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ||
        navigator.getUserMedia ||
        (navigator as any).webkitGetUserMedia ||
        (navigator as any).mozGetUserMedia
      ) {
        //调用用户媒体设备，访问摄像头
        this.initVideo({
          video: {
            height: 800,
            // facingMode: "user",
            facingMode: {
              // 强制后置摄像头
              exact: "user",
              // exact: "environment",
            },
          },
        })
      } else {
        alert("你的浏览器不支持访问用户媒体设备")
      }
    },
    // 图片裁剪
    initCropper() {
      this.myCropper.destroy && this.myCropper.destroy()
      this.myCropper = new Cropper(this.$refs.image as HTMLImageElement, {
        viewMode: 1,
        dragMode: 'none',
        initialAspectRatio: 1,
        aspectRatio: 1,
        // preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false,
      })
      console.log(this.myCropper, 'sds')
    },
    initVideo(constrains: any) {
      let _this = this
      if (navigator.mediaDevices.getUserMedia) {
        //最新标准API
        navigator.mediaDevices
          .getUserMedia(constrains)
          .then(_this.videoSuccess)
          .catch(_this.videoError)
      } else if ((navigator as any).webkitGetUserMedia) {
        //webkit内核浏览器
        (navigator as any)
          .webkitGetUserMedia(constrains)
          .then(_this.videoSuccess)
          .catch(_this.videoError)
      } else if ((navigator as any).mozGetUserMedia) {
        //Firefox浏览器
        (navigator as any)
          .mozGetUserMedia(constrains)
          .then(_this.videoSuccess)
          .catch(_this.videoError)
      } else if ((navigator as any).getUserMedia) {
        //旧版API
        (navigator as any)
          .getUserMedia(constrains)
          .then(_this.videoSuccess)
          .catch(_this.videoError)
      }
    },
    videoSuccess(stream: any) {
      let video = this.$refs.video as HTMLVideoElement,
        _this = this
      //将视频流设置为video元素的源
      video.srcObject = stream
      //播放视频
      video.play()
      video.oncanplay = function () {
        // 摄像头分辨率,手机480x640
        console.log("摄像头分辨率")
        console.log(video.videoWidth, video.videoHeight)
        _this.cameraWidth = video.videoWidth
        _this.cameraHeight = video.videoHeight
        // 发送图片进行识别
        // _this.readImg()
      }
      this.stream = stream
    },
    // 保存截图
    saveCropper() {
      const imgData = this.myCropper.getCroppedCanvas({
        imageSmoothingQuality: 'high'
      }).toDataURL('image/png')
      this.defaultImg = imgData
      this.showDefault = true
      this.showCropper = false
      this.myCropper.destroy()
    },
    // 保存摄像头读取头像
    saveImg() {
      this.readImg()
      this.stream.getTracks().forEach(function(track: any){
        track.stop()
      })
      this.showCamera = false
      this.showCropper = true
      this.$nextTick(() => {
        this.initCropper()
      })
    },
    // 摄像头拍照
    readImg() {
      let video = this.$refs.video as HTMLVideoElement,
      canvas = this.$refs.canvas as HTMLCanvasElement,
      // canvas.style
      context = canvas.getContext("2d") as CanvasRenderingContext2D,
      _this = this
    // let timer = setInterval(function () {
      context.drawImage(
        video,
        0,
        0,
        _this.cameraWidth,
        _this.cameraHeight,
        0,
        0,
        _this.cameraWidth,
        _this.cameraHeight,
      )
      // 扫码条形码
      let imgUri = canvas.toDataURL()
      this.img = imgUri
    },
    videoError(error: Error) {
      console.log("访问用户媒体设备失败：", error.name, error.message)
    }
  }
})
</script>

<style lang="less" scoped>
  // /deep/ .cropper-container {
    // width: 100% !important;
  // }
  .default-avator {
    min-width: 60vw;
    min-height: 60vw;
    // border: 1px solid red;
  }
  .cropper-wrapper {
    height: calc(100vh - 140px)
  }
</style>
