<template>
  <div class="ws-state-image">
    <v-progress-circular
      v-if="loading"
      color="primary"
      indeterminate
    >{{percent}}</v-progress-circular>
    <v-img
      :max-width="maxWidth"
      v-else-if="value"
      :src="value"
    ></v-img>
    <template v-if="value">
      <WsBtn
        outlined
        color="textSecondary"
        :disabled="_disabled"
        @click="$_onClick()"
      >
        <v-icon size="20">mdi-image</v-icon> 更換圖片
      </WsBtn>
      <WsBtn
        outlined
        class="deleteBtn white--text ml-2"
        :disabled="_disabled"
        @click="$_onDelete()"
      >
        <v-icon size="20">mdi-delete</v-icon> 移除圖片
      </WsBtn>
    </template>
    <template v-else>
      <WsBtn
        outlined
        color="textSecondary"
        :disabled="_disabled"
        @click="$_onClick()"
      >
        <v-icon size="20">mdi-image</v-icon> 上傳圖片
      </WsBtn>
    </template>
    <input
      v-show="false"
      @change="$_onChange($event)"
      type="file"
      ref="fileInput"
      accept="image/*"
    >
  </div>
</template>

<script>
export default {
  data: () => ({
    loading: false,
    percent: 0,
  }),
  computed: {
    _disabled() {
      if (this.parent && !this.parentState) {
        return true;
      } else if (
        this.requiredField &&
        (!this.requiredFieldState || this.requiredFieldState.length == 0)
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    $_onDelete() {
      this.$refs.fileInput.file = null;
      this.$emit("input", "");
    },
    $_onClick() {
      this.$refs.fileInput.click();
    },
    $_handleUploadProgress(progressEvent) {
      this.percent = Math.round(
        (progressEvent.loaded / progressEvent.total) * 100
      );
    },
    async $_onChange($event) {
      const file = $event.target.files[0];
      try {
        this.loading = true;
        const putUrl = this.parent
          ? `${this.parent}/${this.parentState}${this.uploadUrl}${file.name}`
          : `${this.uploadUrl}${file.name}`;
        const res = await this.$axios.put(putUrl, file, {
          onUploadProgress: (progressEvent) =>
            this.$_handleUploadProgress(progressEvent),
        });
        this.percent = 0;
        this.$refs.fileInput.file = null;
        this.$emit("input", res.data.signed_url);
      } catch (error) {
        alert("上傳圖片錯誤");
      } finally {
        this.loading = false;
      }
    },
  },
  props: {
    requiredField: {
      default: null,
    },
    requiredFieldState: {
      default: null,
    },
    parentState: {
      default: null,
    },
    parent: {
      default: null,
    },
    maxWidth: {
      type: String,
      default: null,
    },
    value: {
      type: String,
      default: null,
    },
    uploadUrl: {
      type: String,
      required: true,
    },
  },
};
</script>

<style>
</style>