<template>
  <div class="upload-license-container">
    <!-- 职业照片 -->
    <van-field name="uploader"
               label="职业照片">
      <template #input>
        <p>请上传清晰的个人正面头像</p>
        <van-uploader v-model="uploaderAvatar"
                      max-count="1"
                      :after-read="handleUploadAvatar"
                      @delete="handleDelete('headurl')" />
      </template>
    </van-field>

    <h5-cropper ref="cropper"
                :option="option"
                @getbase64Data="getbase64Data"
                @getblobData="getblobData"
                @getFile="getFile"
                hide-input></h5-cropper>

    <!-- 医师资格证 -->
    <van-field name="uploader"
               label="医师资格证">
      <template #input>
        <div class="example-wrap">
          <span class="example"
                @click="show=true;licenseType=0">查看样例</span>
        </div>
        <van-uploader v-model="uploader"
                      max-count="1"
                      :after-read="handleUploadAvatar2"
                      @delete="handleDelete('qualificationImgurl')" />
      </template>
    </van-field>

    <!-- 医师资格证 查看样例弹窗 -->
    <van-popup v-model="show"
               closeable
               position="bottom"
               :style="{ height: '65%' }">
      <div class="license-container">
        <template v-if="licenseType===0">
          <p class="title">医师资格证上传参考</p>
          <div class="content">
            <p>第一步：找到《医师资格证书》</p>
            <img src="../../static/imgs/doctorRegister/upload-demo3.png"
                 alt="">
            <p>第二步：打开证书照片页面,拍照上传</p>
            <img src="../../static/imgs/doctorRegister/upload-demo4.png"
                 alt="">
          </div>
        </template>
        <template v-if="licenseType===1">
          <p class="title">执业医师证书上传参考</p>
          <div class="content">
            <p>第一步：找到《医师执业证书》</p>
            <img src="../../static/imgs/doctorRegister/upload-demo.png"
                 alt="">
            <p>第二步：打开证书照片页面,拍照上传</p>
            <img src="../../static/imgs/doctorRegister/upload-demo2.png"
                 alt="">
          </div>
        </template>
      </div>
    </van-popup>

    <!-- 执业医生证 -->
    <van-field name="uploader"
               label="执业医生证">
      <template #input>
        <div class="example-wrap">
          <span class="example"
                @click="show=true;licenseType=1">查看样例</span>
        </div>
        <van-uploader v-model="uploader2"
                      max-count="1"
                      :after-read="handleUploadAvatar3"
                      @delete="handleDelete('practiceImgurl')" />
      </template>
    </van-field>

    <!-- 手写签名部分 -->
    <van-cell value="手写签名" required />
    <div class="esign-container">
      <vue-esign ref="esign"
                 :width="800"
                 :height="300"
                 :isCrop="isCrop"
                 :lineWidth="lineWidth"
                 :lineColor="lineColor"
                 :bgColor.sync="bgColor"
                 v-show="!licenseForm.caPersonUrl" />

      <div v-show="licenseForm.caPersonUrl"
           class="caperson-img-wrap">
        <img :src="licenseForm.caPersonUrl"
             alt="">
      </div>
    </div>
    <div class="reset-drawing"
         @click="handleReset">重写</div>

    <van-button class="next-step-btn"
                type="info"
                size="large"
                @click="hadnleNextStep">下一步
    </van-button>
  </div>
</template>

<script>
  import H5Cropper from "vue-cropper-h5";
  import { uploadImg, reqUploadBase64 } from '../../api/doctorRegister/doctorRegister'
  // 图片压缩插件
  import Compressor from 'compressorjs';
  export default {
    components: { H5Cropper },
    data() {
      return {
        // 图片裁剪插件配置项
        option: {},
        // 上传头像部分
        uploaderAvatar: [],
        // 医师资格证
        uploader: [],
        // 执业医师证
        uploader2: [],
        /* 手写签名插件配置项 */
        lineWidth: 6,
        lineColor: '#000000',
        bgColor: '',
        resultImg: '',
        // 是否裁剪图片
        isCrop: true,
        // 医师资格证弹窗状态
        show: false,
        userAvatarFile: {},
        licenseForm: {      // 上传证件照页面表单
          headurl: "",    // 职业照片
          qualificationImgurl: "",    // 资格证
          practiceImgurl: "",   // 执业证
          caPersonUrl: "",    // 手写签名
        },
        licenseType: 0,    // 状态值为0显示医师资格证，为1时显示执业药师证书
        doctorName: "",
      }
    },
    methods: {
      // 删除图片预览
      handleDelete(name) {
        this.licenseForm[name] = ""
      },
      // Upload Image File Common Function, Image Compressor and Image Upload
      // 第一个形参接收一个file对象,第二个参数是接口的上传类型参数,用于区分上传职业照片/医师执业证书/医师资格证, 其他参数自己体会
      uploadCommonFn(file, ApiType, formProp, previewProp) {
        new Compressor(file, {
          quality: 0.6,
          success: result => {
            const formData = new window.FormData()
            formData.append('file', result, result.name)
            formData.append('doctorName', this.doctorName)
            this.$toast.loading({
              message: '加载中...',
              forbidClick: true,
              loadingType: 'spinner'
            })
            // 调用图片上传接口
            uploadImg(formData, ApiType).then(res => {
              if (res.status === 200) {
                this.licenseForm[formProp] = res.data
                this[previewProp] = [{ url: this.licenseForm[formProp] }]
                this.$toast.clear()
              } else {
                this.$toast.fail({
                  message: '上传失败,请重试!',
                  duration: 3000,
                  forbidClick: true
                })
                console.log(this[previewProp])
                this[previewProp] = []
              }
            }).catch(error => {
              console.log(error)
              this[previewProp].length = []
            })
          }
        })
      },

      // 点击下一步处理函数
      hadnleNextStep() {
        // 如果缓存中没有手写签名则直接调用生成接口
        if (!this.licenseForm.caPersonUrl) this.handleGenerate()
        setTimeout(async () => {
/*           if (!this.licenseForm.headurl) {
            this.$toast('请上传职业照片!')
          } else if (!this.licenseForm.qualificationImgurl) {
            this.$toast('请上传医师资格证!')
          } else if (!this.licenseForm.practiceImgurl) {
            this.$toast('请上传执业医生证!')
          }  */if (!this.resultImg && !this.licenseForm.caPersonUrl) {
            this.$toast('请完成手写签名!')
          } else {
            // 全部通过
            if (!this.licenseForm.caPersonUrl) {
              const formData = new window.FormData()
              formData.append('file', this.resultImg)
              formData.append('doctorName', this.doctorName)
              this.$toast.loading({
                message: '加载中...',
                forbidClick: true,
                loadingType: 'spinner'
              })
              const response = await reqUploadBase64(formData)
              this.$toast.clear()
              this.licenseForm.caPersonUrl = response.data
            }

            window.sessionStorage.setItem('licenseForm', JSON.stringify(this.licenseForm))
            this.$emit('handleLicenseForm', this.licenseForm)
          }
        }, 100);
      },
      // 上传执业医师证
      handleUploadAvatar3(file) {
        this.uploadCommonFn(file.file, 'practiceImg', 'practiceImgurl', 'uploader2')
      },

      // 上传医师资格证
      handleUploadAvatar2(file) {
        this.uploadCommonFn(file.file, 'qualificationImg', 'qualificationImgurl', 'uploader')
      },

      // 上传职业照片处理函数
      handleUploadAvatar(file) {
        this.$refs.cropper.loadFile(file.file)
      },
      // 获取base64编码的图片
      getbase64Data(value) {
        this.userAvatarFile.content = value
      },

      // 获取blob编码的图片
      getblobData(value) {
        // console.log("blob : ", value)
      },

      // 获取File格式的图片
      getFile(value) {
        // this.userAvatarFile.file = value
        this.uploadCommonFn(value, 'headImg', 'headurl', 'uploaderAvatar')
      },
      // 清除手写签名画布
      handleReset() {
        this.licenseForm.caPersonUrl = ''
        this.$refs.esign.reset()
      },

      // 生成图片
      handleGenerate() {
        this.$refs.esign.generate().then(res => {
          // 返回的是一个Base64数据
          this.resultImg = res
          console.log("this.resultImg: ", this.resultImg)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    created() {
    },
    mounted() {
      try {
        // 获取缓存中的医生名字,用于区分将图片上传到服务器对应医生姓名的文件夹下
        this.doctorName = JSON.parse(window.sessionStorage.getItem('doctorFillForm')).doctorName
      } catch (error) {
        console.log(error)
      }
      // 获取缓存中的图片信息
      this.licenseForm = JSON.parse(window.sessionStorage.getItem('licenseForm')) || {}
      if (this.licenseForm.headurl && this.licenseForm.qualificationImgurl && this.licenseForm.practiceImgurl) {
        this.uploaderAvatar = [{ url: this.licenseForm.headurl }]
        this.uploader = [{ url: this.licenseForm.qualificationImgurl }]
        this.uploader2 = [{ url: this.licenseForm.practiceImgurl }]
      }
      console.log(this.licenseForm)
    }
  }
</script>

<style lang="less" scoped>
  /deep/.van-field__control--custom {
    display: block;
    height: 2.38rem;
  }

  .example {
    position: absolute;
    top: 18%;
    left: -12%;
    // z-index: 999;
    z-index: 520;
    color: #1989fa;
    font-size: 0.3rem;
  }

  /deep/.van-field__label {
    text-align: left;
  }

  /* 手写签名容器 */
  .esign-container {
    max-width: 1000px;
    margin: 0 auto;
    margin: 0 0.3rem;
    background-color: #d3d3d3;
    border-radius: 0.2rem;
  }

  /deep/ .van-uploader__upload {
    background: url("../../static/imgs/doctorRegister/upload-default.png")
      no-repeat center / 100%;
    width: 2rem;
    height: 2rem;
  }

  .reset-drawing {
    margin-left: 0.32rem;
    margin-top: 0.2rem;
    width: 14%;
    font-size: 0.3rem;
    color: #fff;
    padding: 0.1rem 0.2rem;
    background-color: #478bfb;
    border-radius: 2px;
  }

  .license-container {
    font-size: 0.3rem;
    .title {
      position: absolute;
      top: 4%;
      left: 3%;
      font-size: 0.32rem;
    }

    .content {
      padding: 0 0.2rem;
      padding-top: 1rem;
      text-align: left;
      img {
        margin: 0.2rem 0;
        &:nth-child(2) {
          width: 30%;
        }
        &:nth-child(4) {
          width: 70%;
        }
      }
      p:first-child {
        border-top: 1px solid #ccc;
        padding-top: 0.5rem;
      }
    }
  }

  .example-wrap {
    position: absolute;
    width: 750px;
    height: 100%;
  }

  .next-step-btn {
    /*   position: absolute;
    bottom: 5%;
    transform: translate(-50%); */
    margin: 0.5rem 0;
    width: 90%;
  }

  .caperson-img-wrap {
    img {
      width: 100%;
      height: 100%;
    }
  }
</style>