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

    <label @click="initUpload" class="inline-block">
      <div
        ref="uploadBox"
        class="
          upload-box
          text-center
          flex
          items-center
          justify-center
          text-font-white
        "
      >
        <img
          v-if="showNotUploadImg "
          src="@/assets/icons/upload.png"
          alt=""
          class="mx-auto"
        />
        <img
          v-else-if="showImgUploadImg"
          :src="showUploadFile"
          alt=""
          class="mx-auto"
        />
        <img
          v-else-if="status === uploadStatus.success && uploadType !== '图片' && uploadType !== '封面图片'"
          src="@/assets/icons/upload.png"
          alt=""
          class="mx-auto"
        />
        <Loading type="spiner" v-else-if="status === uploadStatus.uploading || coverstatus === uploadStatus.uploading" />
        <div v-else-if="status === uploadStatus.failed || coverstatus === uploadStatus.uploading">上传失败</div>
      </div>
    </label>

    <div class="text-center text-font-white">
      <div v-if="(uploadType == '封面图片' && !coverName) || (uploadType !== '封面图片' && !fileName)" class="mt-2">{{uploadAccept.acceptText}}</div>
      <div v-else class="mt-2">
        {{ (uploadType == '封面图片' && coverName)?coverName:fileName }}
      </div>
      <!-- <div v-if="uploadType == '封面图片' && coverName" class="mt-2">
        {{ coverName }}
      </div>
      <div v-else-if="uploadType !== '封面图片' && fileName" class="mt-2">
        {{ fileName }}
      </div> -->

      <label for="upload" class="mt-2">
        <div
          v-if="showReUpload"
          style="color: #0076ff"
          class="inline-block"
        >
          重新上传
        </div>
      </label>

    </div>

    <div class="flex justify-between fixed bottom-0 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>

  </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,
      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.params.type
    },
    uploadAccept():object{
      switch(this.uploadType){
        case '剧本':
          return {acceptTitle:'请上传剧本附件',acceptType:'application/pdf,application/msword,text/plain',acceptText:'支持扩展名格式PDF'}
        case '视频':
          return {acceptTitle:'请上传视频附件',acceptType:'video/*',acceptText:'上传视频仅支持MOV、MP4格式文件，大小限制为100M以内'}
        case '电影':
          return {acceptTitle:'请上传电影附件',acceptType:'video/*',acceptText:'上传视频仅支持MOV、MP4格式文件，大小限制为100M以内'}
        case '音频':
          return {acceptTitle:'请上传音频附件',acceptType:"audio/*",acceptText:'上传音频仅支持MP3格式文件'}
        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 ''
      }
    },
    showNotUploadImg():boolean{
      return (this.uploadType !== '封面图片' && this.status === uploadStatus.NULL) || (this.uploadType == '封面图片' && this.coverstatus === uploadStatus.NULL)
    },
    showImgUploadImg():boolean{
      return (this.status === uploadStatus.success && this.uploadType == '图片') || (this.coverstatus === uploadStatus.success && this.uploadType == '封面图片')
    },
    showReUpload():boolean{
      return ((this.uploadType !== '封面图片') && (this.status === uploadStatus.failed || this.status === uploadStatus.success))||((this.uploadType == '封面图片') && (this.coverstatus === uploadStatus.failed || this.coverstatus === uploadStatus.success))
    }
  },
  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.afterRead(files[0]);
      }
    },
    ...mapMutations("create", {
      setState: "SET_STATE",
    }),
    async afterRead(file: File) {
      try {
        const ab = await file.arrayBuffer();
        const fileMd5 = md5(Buffer.from(ab));
        
        // const ossRet = await this.$service.nftService.ossPolicy();
        // const uploadRet = await this.$service.nftService.uploadFileToOss(
        //   file,
        //   ossRet
        // );
        if(this.uploadType == '封面图片') {
          this.coverstatus = uploadStatus.uploading;
          this.setState({
            coverName: file.name,
            coverFile: file,
          });
          this.coverstatus = uploadStatus.success;
        }else {
          this.status = uploadStatus.uploading;
          this.setState({
            fileName: file.name,
            fileHash: fileMd5,
            file: file,
          });
          this.status = uploadStatus.success;
        }

      } catch (err) {
        console.log(err, "show err");
        if(this.uploadType == '封面图片') {
          this.coverstatus = uploadStatus.failed;
        }else {
          this.status = uploadStatus.failed;
        }
        
      }
    },
    afterRead2(file: any) {
      file.status = "uploading";
      file.message = "上传中...";

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

<style scoped>
.upload-box {
  width: 140px;
  height: 71px;
  background: #1d2649;
  border-radius: 15px;
  border: 1px solid #0078ff;
}
</style>