
<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" accept="image/*" class="upload hidden" ref='localImgElem' @change="handleFileChange('localImgElem')"/>
    <input type="file" accept="image/*" 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=='封面图片'?"上传封面":'上传附件'}}
      </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="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 { 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():object{
      switch(this.uploadType){
        case '剧本':
          return {acceptTitle:'请上传剧本附件',acceptType:'.pdf,.doc,.docx,.txt',acceptText:'仅支持txt、doc、docx、pdf,文件大小限制在100M'}
        case '视频':
          return {acceptTitle:'请上传视频附件',acceptType:'video/*',acceptText:'上传视频仅支持MOV、MP4格式文件，大小限制为500M以内'}
        case '电影':
          return {acceptTitle:'请上传电影附件',acceptType:'video/*',acceptText:'上传电影仅支持MOV、MP4格式文件，大小限制为1G以内'}
        case '音频':
          return {acceptTitle:'请上传音频附件',acceptType:"audio/*",acceptText:'上传音频仅支持MP3格式文件，大小限制为100M以内'}
        case '图片':
          return {acceptTitle:'请上传图片附件',acceptType:'image/*',acceptText:'仅支持png、jpg图片'}
        case '封面图片':
          return {acceptTitle:'请上传封面图片',acceptType:'image/*',acceptText:'仅支持png、jpg图片'}
        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);
    },
    handleFileChange(ref:any) {
      const ele = this.$refs[ref] as HTMLInputElement;
      const files = ele.files;
      if (files && files.length >= 1) {
        this[this.uploadType == '封面图片'? 'coverstatus':'status'] = uploadStatus.uploading;
        this.afterRead(files[0]);
      }
    },
    ...mapMutations("create", {
      setState: "SET_STATE",
    }),
    async afterRead(file: File) {
      try {
        const ab = await file.arrayBuffer();
        const fileMd5 = md5(Buffer.from(ab));
        
        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;
      }
    },
    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>