
<template>
  <Layout-Child class="page-scroll text-center">
    <div class="text-font-white mt-20 text-center mb-6">{{uploadAccept.acceptTitle}}</div>
    <!-- <input type="file" class="upload hidden" @change="handleFileChange('inputFile')" ref="inputFile" :accept="uploadAccept.acceptType"/> -->
    <input type="file" class="upload hidden" @change="handleFileChange('inputFile')" ref="inputFile"/>
    <input type="file"  class="upload hidden" ref='localImgElem' @change="handleFileChange('localImgElem')"/>
    <input type="file"  capture="camera" class="upload hidden" ref='cameraElem' @change="handleFileChange('cameraElem')"/>
    <van-action-sheet v-model="show" :actions="actions" @select="onSelect" />

    <div
      ref="uploadBox"
      class="
        upload-box
        text-center
        text-font-white
      "
      :class="{hiddenBorder:((uploadType == '封面图片' && coverName) || (uploadType == '图片' && fileName))}"
    >
      <img
        @click="initUpload"
        v-if="uploadNull "
        src="@/assets/icons/upload.png"
        alt=""
        class="mx-auto mt-28"
      />
      <Loading type="spiner mt-16" v-else-if="uploadLoading" />
      <!-- 当上传的是图片或封面图片 -->
      <div v-else-if="showImgUploadImg" class="img-box">
        <img
          :src="showUploadFile"
          alt=""
          class="mx-auto"
          @click.stop="showFullImg"
        />
      </div>

      <!-- 当上传的不是图片或封面图片 -->
      <img
        v-else-if="status === uploadStatus.success && uploadType !== '图片' && uploadType !== '封面图片'"
        src="@/assets/img/file.png"
        alt=""
        class="mx-auto mt-16"
      />
      <div v-else-if="uploadFailed">上传失败</div>
      <div v-if="!(uploadType == '封面图片' && !coverName) || (uploadType !== '封面图片' && !fileName)" class=" w-40 mx-auto mt-2 text-xs">
        {{ (uploadType == '封面图片' && coverName)?coverName:fileName }}
      </div>
      <div v-if="uploadNull" class="mt-2 text-center mx-auto w-40" style="color: #0076ff" @click="initUpload">
        {{uploadType=='封面图片'?"请选择封面图片":`请选择${uploadType}附件`}}
      </div>
      <div v-if="showReUpload" class="mt-2 flex mx-auto w-40 justify-between" style="color: #0076ff"> 
        <div @click="clearUpload">
          删除选择
        </div>
        <div @click="initUpload">
          重新选择
        </div>
      </div>
    </div>
    <div class="mt-2 mx-auto w-56 text-center text-font-white text-xs">{{uploadAccept.acceptText}}</div>
    <div class=" text-xs mt-10 mx-auto w-80 text-left text-font-white" v-if="uploadType!='封面图片' && uploadType!='图片'">说明：一幕影链将为您的本地文件计算文件HASH。在该环节，您的{{uploadType}}不会上传到平台。</div>
    <div class=" text-xs mt-10 mx-auto w-80 text-left text-font-white" v-if="uploadType =='图片'">说明：一幕影链将为您的图片文件计算文件HASH, 并上传到平台。</div>

    <div class="flex justify-between fixed bottom-3 left-0 right-0">
      <app-btn
        text="取消"
        class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
        border="none"
        @btnClicked="$router.back()"
      ></app-btn>
      <app-btn
        text="确定"
        class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
        border="none"
        :disabled="nextBtnDisabled"
        @btnClicked="$router.back()"
      ></app-btn>
    </div>

    <div class="fullImgBox" v-if="showFull" @click="showFull = !showFull">
      <!-- <div class="fullImgCover"></div> -->
      <img
        :src="showUploadFile"
        alt=""
        class="mx-auto"
      />
    </div>

  </Layout-Child>
</template>

<script lang="ts">
/* eslint-disable */
import Vue from "vue";
import { Uploader, Loading } from "vant";
import { mapMutations, mapState } from "vuex";
import md5 from "md5";
import SparkMD5 from "spark-md5";
import { ActionSheet } from 'vant';

Vue.use(ActionSheet);

enum uploadStatus {
  NULL,
  uploading,
  failed,
  success,
}

export default Vue.extend({
  data() {
    return {
      fileList: [],
      uploading: false,
      uploadStatus,
      status: uploadStatus.NULL,
      coverstatus: uploadStatus.NULL,
      // accept:
      show: false,
      showFull: false,
      actions: [
        { name: '本地相册'},
        { name: '拍照'},    
      ],
    };
  },
  components: {
    "Layout-Child": () => import("@/layout/Child.vue"),
    "app-btn": () => import("@/components/common/Btn.vue"),
    Uploader,
    Loading,
  },
  computed: {
    ...mapState("create", ["fileName","coverName",'coverFile','file']),
    nextBtnDisabled(): boolean {
      if(this.uploadType == '封面图片') {
        return !this.coverName
      }else {
        return !this.fileName;
      }
    },
    uploadType():any{
      return this.$route.query.type
    },
    uploadAccept():any{
      switch(this.uploadType){
        case '剧本':
          return {acceptTitle:'剧本HASH计算',acceptType:'.pdf,.doc,.docx,.txt',acceptText:'仅支持txt、doc、docx、pdf,文件大小限制在100M',acceptSize:1024*1024*100,acceptArray:['.pdf','.doc','.docx','.txt','.PDF','.DOC','.DOCX','.TXT']}
        case '视频':
          return {acceptTitle:'视频HASH计算',acceptType:'video/*',acceptText:'上传视频仅支持MOV、MP4、AVI格式文件，大小限制为500M以内',acceptSize:1024*1024*500,acceptArray:['.mp4','.mov','.avi','.MP4','.MOV','.AVI']}
        case '电影':
          return {acceptTitle:'电影HASH计算',acceptType:'video/*',acceptText:'上传电影仅支持MOV、MP4格式文件，大小限制为1G以内',acceptSize:1024*1024*1024}
        case '音频':
          return {acceptTitle:'音频HASH计算',acceptType:"audio/*",acceptText:'上传音频仅支持MP3格式文件，大小限制为100M以内',acceptSize:1024*1024*100,acceptArray:['.mp3','.MP3']}
        case '图片':
          return {acceptTitle:'图片HASH计算',acceptType:'image/*',acceptText:'仅支持png、jpg、jpeg图片',acceptArray:['.png','.jpg','.jpeg','.PNG','.JPG','.JPEG']}
        case '封面图片':
          return {acceptTitle:'请选择封面图片',acceptType:'image/*',acceptText:'仅支持png、jpg、jpeg图片',acceptArray:['.png','.jpg','.jpeg','.PNG','.JPG','.JPEG']}
        default:
          return {acceptTitle:'',acceptType:'',acceptText:''}
      }
    },
    showUploadFile():string{
      if(this.uploadType == '封面图片' && this.coverFile) {
        return window.URL.createObjectURL(this.coverFile)
      }else if(this.uploadType == '图片' && this.file) {
        return window.URL.createObjectURL(this.file)
      }else {
        return ''
      }
    },
    showImgUploadImg():boolean{
      return (this.status === uploadStatus.success && this.uploadType == '图片') || (this.coverstatus === uploadStatus.success && this.uploadType == '封面图片')
    },
    uploadNull():boolean{
      return ((this.uploadType !== '封面图片' && this.status === uploadStatus.NULL)||(this.uploadType == '封面图片' && this.coverstatus === uploadStatus.NULL))
    },
    uploadLoading():boolean{
      return ((this.uploadType !== '封面图片' && this.status === uploadStatus.uploading)||(this.uploadType == '封面图片' && this.coverstatus === uploadStatus.uploading))
    },
    uploadSuccess():boolean{
      return ((this.uploadType !== '封面图片' && this.status === uploadStatus.success)||(this.uploadType == '封面图片' && this.coverstatus === uploadStatus.success))
    },
    showReUpload():boolean{
      return ((this.uploadType !== '封面图片') && (this.status === uploadStatus.failed || this.status === uploadStatus.success))||((this.uploadType == '封面图片') && (this.coverstatus === uploadStatus.failed || this.coverstatus === uploadStatus.success))
    },
    uploadFailed():boolean {
      return ((this.uploadType !== '封面图片' && this.status === uploadStatus.failed)||(this.uploadType == '封面图片' && this.coverstatus === uploadStatus.failed))
    }
  },
  methods: {
    initUpload(){
      if(this.uploadType == '图片' || this.uploadType == '封面图片') {
        this.show = true
      }else {
        (this.$refs.inputFile as HTMLInputElement).click()
      }
    },
    onSelect(item:any){
        this.show = false;
        let cEl =this.$refs.cameraElem as HTMLInputElement
        let fEl =this.$refs.localImgElem as HTMLInputElement
        switch(item.name){
            case '拍照':
                cEl.click();
              break;  
            case '本地相册':
                fEl.click();
              break;
        }
        this.$toast(item.name);
    },
    async handleFileChange(ref:any) {
      console.log('上传了')
      console.log(ref);
      
      const ele = this.$refs[ref] as HTMLInputElement;
      const files = ele.files as FileList;

      if(!files[0]) {
        return
      }

      //限制大小
      if(this.uploadAccept.acceptSize && files[0].size > this.uploadAccept.acceptSize) {
        this.$toast('文件大小超出限制~')
        ele.value = ''
        return
      }
      
      //限制类型
      const type_name = files[0].name.substring(files[0].name.lastIndexOf('.'),files[0].name.length)
      console.log('图片后缀',type_name)

      if(this.uploadAccept.acceptArray && this.uploadAccept.acceptArray.indexOf(type_name) == -1) {
         this.$toast('请上传指定类型文件~')
         ele.value = ''
         return
      }

      if (files && files.length >= 1) {
        this[this.uploadType == '封面图片'? 'coverstatus':'status'] = uploadStatus.uploading;
        await this.afterRead(files[0]);
        ele.value = ''
      }
    },
    ...mapMutations("create", {
      setState: "SET_STATE",
    }),
    async afterRead(file: File) {
      try {
        //分块计算hash
        const ab = await file.arrayBuffer();
        // const fileMd5 = md5(Buffer.from(ab));
        let chunkSize = 104857600;
        let chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let spark = new SparkMD5.ArrayBuffer();
        while(currentChunk<chunks){
            const start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;
            spark.append(Buffer.from(ab).slice(start,end))
            currentChunk ++
        }
        // spark.append(Buffer.from(ab))
        const fileMd5 = spark.end()
        
        if(this.uploadType == '封面图片') {
          this.setState({
            coverName: file.name,
            coverFile: file,
          });
        }else {
          this.setState({
            fileName: file.name,
            fileHash: fileMd5,
            file: file,
          });
        }
        this[this.uploadType == '封面图片'? 'coverstatus':'status'] = uploadStatus.success;
      } catch (err) {
        this[this.uploadType == '封面图片'? 'coverstatus':'status'] = uploadStatus.failed;
      }
    },

    // async computedHash(file:any){
    //   // const fileReadfun = (file:any)=>{
    //   var blobSlice = File.prototype.slice;

    //   //设置文件分块大小和分块数量
    //   let chunkSize = 104857600;
    //   let chunks = Math.ceil(file.size / chunkSize);

    //   let currentChunk = 0;
    //   let spark = new SparkMD5.ArrayBuffer();
    //   // let spark = new SparkMD5();

    //   // spark.append(e.target.files[0].name);
    //   // console.log(e.target.files[0].slice(0,10));
    //   // console.log((e.target as any).files[0].name);
    //   const fileReader = new FileReader();

    //   //第一次和下一次读取
    //   function loadNext() {
    //     const start = currentChunk * chunkSize,
    //       end = start + chunkSize >= file.size ? file.size : start + chunkSize;

    //     fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    //     // fileReader.readAsBinaryString(blobSlice.call(file, start, end));
    //   }

    //   //文件读取回调
    //   fileReader.onload = function (event:any) {
    //     //获取文件块，每读取一次推到spark中,计算文件HASH
    //     spark.append(event.target.result);
    //     currentChunk++;
    //     //如果当前块的数量小于总数量则继续读取,否则打印hash
    //     if (currentChunk < chunks) {
    //       loadNext();
    //     } else {
    //       console.log(spark.end());

    //       return spark.end()
    //     }
        
    //   };
    //   loadNext();
    // },

    showFullImg(){
      this.showFull = !this.showFull
    },
    clearUpload(){
      if(this.uploadType == '封面图片'){
          this.setState({
            coverName: '',
            coverFile: undefined,
          });
          this.coverstatus = uploadStatus.NULL
      }else {
          this.setState({
            fileName: '',
            fileHash: '',
            file: undefined,
          });
          this.status = uploadStatus.NULL
      }
      for(let item of document.getElementsByClassName('upload')){
        (item as any).value = ''
      }
    },


    afterRead2(file: any) {
      file.status = "uploading";
      file.message = "上传中...";

      setTimeout(() => {
        file.status = "failed";
        file.message = "上传失败";
      }, 1000);
    },
  },
});
</script>

<style scoped lang="less">
.upload-box {
  width: 200px;
  height: 280px;
  margin: 0 auto;
  background: #1d2649;
  border-radius: 15px;
  border: 1px solid #0078ff;
  padding-top: 1px;
  .img-box {
    height: 200px;
    display: flex;
    align-items: center;
    img {
      max-height: 100%;
      max-width: 100%;
      display: block;
    }
  }
}
.hiddenBorder {
  border: none;
}
.fullImgBox {
  position: fixed;
  top:0;
  left: 0;
  height: calc(100vh);
  width: calc(100vw);
  background: black;
  display: flex;
  align-items: center;
  z-index: 100;
  // .fullImgCover {
  //   display: fixed;
  //   top:0;
  //   right: 0;
  //   left: 0;
  //   right: 0;
  // }
  img {
      max-height: 100%;
      max-width: 100%;
      display: block;
  }
}
</style>