<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      action=""
      drag
      :accept="accept"
      :file-list="fileList"
      :multiple="multiple"
      :on-change="onChange"
      :auto-upload="autoUpload"
      :on-remove="handleRemove"
      :list-type="'picture-card'"
      :limit="!multiple ? 1 : undefined"
      :on-exceed="onExceed"
      :class="{ items: fileList.length }"
    >
      <em class="el-icon-upload"></em>
      <div class="el-upload__text">
        {{ $t("general.dropFile") }}
        <em>{{ $t("general.clickUpload") }}</em>
      </div>
      <div class="file-container" slot="file" slot-scope="{ file }">
        <div>
          <el-image
            class="w-100 el-upload-list__item-thumbnail"
            :src="file.url"
            v-if="file.file_type === 'IMAGE'"
          ></el-image>
          <div v-else>
            <video
              class="w-100 el-upload-list__item-thumbnail"
              :src="file.url"
            ></video>
          </div>
          <div class="filename text-ellipsis">
            {{ file.name }}
          </div>
        </div>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="onPreview(file)">
            <em class="el-icon-zoom-in"></em>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <em class="el-icon-delete"></em>
          </span>
        </span>
      </div>
      <div class="el-upload__tip" slot="tip">
        {{ $t("dams.uploadType") }}
      </div>
    </el-upload>

    <div class="mt-20 text-right">
      <el-button
        class="el-btn-primary-outline"
        type="primary"
        :disabled="!fileList.length"
        @click="onClearFilesToUpload"
      >
        {{ $t("general.clear") }}
      </el-button>
      <el-button type="primary" :disabled="!fileList.length" @click="onUpload">
        {{ $t("general.upload") }}
      </el-button>
    </div>

    <el-dialog
      width="60%"
      :title="$t('general.preview')"
      :visible.sync="showPreview"
      :destroy-on-close="true"
      append-to-body
    >
      <PreviewDams :item="selectedFile" :edit="false" />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { DamsItem } from "../../model/dams/dams-item.model";
import { uploadAsset } from "../../api/dams";
import { calculateRatio } from "../../utils/calculate-ratio";
import { confirmMsg } from "../../utils/message";
import PreviewDams from "./components/preview-dams.vue";
import { checkFileType } from "../../utils/check-file-type";
import { checkMimeType } from "../../utils/checkMimeType";

@Component({
  name: "DamsUpload",
  components: {
    PreviewDams,
  },
})
export default class extends Vue {
  @Prop({ default: "" }) ratio?: string;
  @Prop({ default: "image/*" }) accept!: string;
  @Prop({ default: false }) multiple!: boolean;
  @Prop({ default: false }) autoUpload!: boolean;
  @Prop({ default: 0 }) folderId!: number;
  @Prop({ default: 0 }) assetId!: number;

  fileList: any = [];

  showPreview = false;
  selectedFile = new DamsItem();

  async onChange(file: any) {
    if (await this.beforeUpload(file.raw)) {
      if (file.raw.type.includes("image")) {
        file.file_type = "IMAGE";
      } else if (file.raw.type.includes("video")) {
        file.file_type = "VIDEO";
      } else if (file.raw.type.includes("mp3")) {
        file.file_type = "AUDIO";
      } else if (file.raw.type.includes("pdf")) {
        file.file_type = "PDF";
      }
      this.fileList.push(file);
    } else {
      const upload: any = this.$refs.upload;
      if (upload) {
        const files = upload.uploadFiles;
        if (files && files.length) {
          let i = 0;
          for (const f of files) {
            if (f.uid === file.uid) {
              files.splice(i, 1);
              break;
            }
            i++;
          }
        }
      }
      return false;
    }
  }



  // async beforeUpload(file: any) {
  //   let valid = true
  //   file.valid = true
  //   let message = ''

  //   const imageType = [
  //     'image/png',
  //     'image/jpg',
  //     'image/jpeg',
  //     'image/webp',
  //     'image/gif',
  //     'image/tiff'
  //   ]

  //   const videoType = [
  //     'video/mp4',
  //     'video/quicktime',
  //     'video/x-ms-wmv',
  //     'video/avi'
  //   ]

  //   const fileNameList = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'tiff', 'mp4', 'mov', 'wmv', 'avi', 'pdf','mp3']
  //   const name = file.name.toLowerCase().split('.')

  //   const validName = fileNameList.includes(name[name.length - 1])

  //   const mineType = await checkMimeType(file)

  //   // name and the mimetype need to be in the accept list type
  //   if (validName && mineType) {
  //     if (this.accept.includes('image')) {
  //       if (!imageType.includes(file.type)) {
  //         message = this.$t('general.onlyImage') as string
  //         valid = false
  //       } else {
  //         if (this.ratio) {
  //           const data: any = await this.readImage(file)
  //           if (
  //             data.width &&
  //             data.height &&
  //             calculateRatio(data.width, data.height) !== this.ratio
  //           ) {
  //             message = `${this.$t('banner.invalidRatio') as string} ${
  //                 this.ratio
  //               }`
  //             valid = false
  //           }
  //         }
  //       }
  //     } else if (this.accept.includes('video')) {
  //       if (!videoType.includes(file.type)) {
  //         message = this.$t('general.onlyVideo') as string
  //         valid = false
  //       }
  //     } else {
  //       if (
  //         !file.type.includes('image') &&
  //         !file.type.includes('video') &&
  //         !file.type.includes('pdf')
  //       ) {
  //         message = this.$t('general.onlyImageVideoPdf') as string
  //         valid = false
  //       }
  //     }
  //   } else {
  //     message = this.$t('general.onlyImageVideoPdf') as string
  //     valid = false
  //   }

  //   if (file.type.includes('image') && !imageType.includes(file.type)) {
  //     message = this.$t('dams.imageRestrict') as string
  //     valid = false
  //   } else if (file.type.includes('video') && !videoType.includes(file.type)) {
  //     message = this.$t('dams.videoRestrict') as string
  //     valid = false
  //   }

  //   if (file.size > 20000000) {
  //     message = this.$t('dams.exceedFileSize') as string
  //     valid = false
  //   }

  //   if (!valid) {
  //     setTimeout(() => {
  //       this.$message({
  //         message: message,
  //         type: 'error'
  //       })
  //     })
  //   }

  //   return valid
  // }
  async beforeUpload(file: any) {
  let valid = true;
  file.valid = true;
  let message = "";

  const maxSize = 20000000; 

  // const validType = await checkMimeType(file);

  // if (!validType) {
  //   message = this.$t("general.invalidFile") as string;
  //   valid = false;
  // } else
 if (file.size > maxSize) {
    message = this.$t("dams.exceedFileSize") as string;
    valid = false;
  }

  if (!valid) {
    setTimeout(() => {
      this.$message({
        message: message,
        type: "error",
      });
    });
  }

  return valid;
}
  async readImage(file: any) {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const img: any = new Image();
        img.onload = () => {
          resolve(img);
        };
        img.src = reader.result;
      };
    });
  }

  handleRemove(file: any) {
    if (file && this.fileList && this.fileList.length) {
      let i = 0;
      for (const f of this.fileList) {
        if (f.uid.toString() === file.uid.toString()) {
          this.fileList.splice(i, 1);
          break;
        }
        i++;
      }
    }
  }

  onExceed() {
    this.$message({
      message: this.$t("banner.onlyOneFile") as string,
      type: "error",
    });
  }

  onPreview(file: any) {
    if (file) {
      if (file.url) {
        this.selectedFile.url = file.url;
        this.selectedFile.file_type = file.file_type;
        if (this.selectedFile.url) {
          this.selectedFile.url = decodeURI(this.selectedFile.url);
        }
        this.showPreview = true;
      }
    }
  }

  async onClearFilesToUpload() {
    if (!this.fileList) {
      return;
    }
    if (await confirmMsg("general.confirmRemove", true, true)) {
      this.fileList = [];
    }
  }

  onClearAll() {
    this.fileList = [];
  }

  async onUpload() {
    if (!this.fileList) {
      return;
    }
    const fileInfo = new FormData();
    fileInfo.append("folder_id", this.folderId.toString());

    if (this.assetId) {
      fileInfo.append("asset_id", this.assetId.toString());
    }

    for (const file of this.fileList) {
      fileInfo.append("file", file.raw);
    }

    const response: any = await uploadAsset(fileInfo);
    if (response) {
      if (response.asset_details && response.asset_details.length) {
        response.asset_details = checkFileType(response.asset_details);

        if (!this.multiple) {
          this.$emit("uploaded", response.asset_details[0].url);
        } else {
          this.$emit("uploaded", response.asset_details);
          this.fileList = [];
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .upload-demo {
  &:not(.items) {
    .el-upload-list {
      display: none;
    }
  }

  .el-upload-list__item-thumbnail {
    height: 80%;

    img {
      object-fit: contain;
    }
  }

  .el-upload__tip {
    margin-top: 45px;
  }

  .el-upload--picture-card {
    line-height: unset;
    border: 1px solid transparent;
  }

  .file-container {
    height: 148px;

    & > div {
      height: 148px;
    }

    video {
      height: 120px;
    }

    .filename {
      margin-top: -10px;
      padding: 5px 5px 0px 5px;
    }
  }
}
</style>
