<template>
  <div class="space-status" :style="{ height: windowHeight - 68 + 'px' }">
    <div class="service-list">
      <div class="service-listTitle">{{$t("serviceDriveAuth['智慧教學服務空間狀態']")}}</div>
      <div class="action-btn" @click="gotoTeacherManagent()">
        <Icon class="share-icon" type="md-share" />{{$t("serviceDriveAuth['分配教學空間']")}} 
      </div>
    </div>
    <div
      v-if="isloading == true||spaceStatus==undefined||spaceStatus.notbuy==true"
      class="no-data-text"
      style="margin-bottom: -50%"
    >
      <img src="../../../assets/icon/no_data.png" width="120" />
      <p style="color: #808080">{{$t("serviceDriveAuth['暂无数据']")}} </p>
    </div>
   
    <Row
      class="main-wrap"
      :style="{ visibility: isloading == true? 'hidden' : 'visible' }"
    >
      <i-col :xs="24" :sm="24" :md="24" :lg="12">
        <p class="nomal-title">{{$t("serviceDriveAuth['空間總數']")}}</p>
        <p class="info-text">
          <span class="info-num">{{ totalavaliable }}</span>
          {{ totalavaliableText }}
        </p>
      </i-col>
      <i-col :xs="24" :sm="24" :md="24" :lg="12">
        <p class="nomal-title">{{$t("serviceDriveAuth['已使用空間總數']")}}</p>
        <p class="info-text" :class="{'over-used':totalused>totalavaliable}">
          <span class="info-num" >{{ totalused }}</span>
          {{ totalusedText }} 
          <Tooltip transfer theme="light" :content="tooltipstext"  placement="bottom" offset="-20">
                        <Icon type="ios-alert-outline" color="#1cc0f3" size="20" v-if='totalused>totalavaliable'  style="position:absolute;top:-17px;margin-left:2px" />
                    </Tooltip>
        </p>
      </i-col>

      <i-col :xs="24" :sm="24" :md="24" :lg="24">
        <div class="chart-wrap">
          <p class="nomal-title">{{$t("serviceDriveAuth['空間使用狀況']")}}</p>
          <SpaceChart :spaceStatus="spaceStatus" :remainDays="remainDays" />
          <!--放置餅圖剩下的空間狀態-->
          <div class="remail-data" v-if="totalavaliable>=totalused">
            <p class="title">{{$t("serviceDriveAuth['未使用空間數']")}}</p>
            <p class="num">
              {{ unUsed }}<span class="small-text"> {{ unUsedText }}</span>
            </p>
            <p class="title">{{$t("serviceDriveAuth['未使用空間比率']")}}</p>
            <p class="num">
              {{ spaceStatus.unUsedPercent }}<span class="small-text"> %</span>
            </p>
          </div>
          <div class="remail-data" v-if="totalavaliable<totalused">
            <p class="title">{{$t("serviceDriveAuth['可使用空間數']")}}</p>
            <p class="num">
               0 <span class="small-text"> GB</span>
            </p>
            <p class="title">{{$t("serviceDriveAuth['可使用空間比率']")}}</p>
            <p class="num">
              0<span class="small-text"> %</span>
            </p>
          </div>
          
        </div>
      </i-col>
      <i-col :xs="24" :sm="24" :md="24" :lg="24">
        <p class="deadline-title">
          {{$t("serviceDriveAuth['當前空間到期日']")}}<span class="deadline-time" v-if="totalavaliable>=totalused"
            >{{ converTime(spaceStatus.endDate) }} ({{ remainDays }} {{$t("serviceDriveAuth['天']")}})</span
          ><span v-else>{{$t("serviceDriveAuth['基本 1GB 永久授權']")}}</span>
        </p>

        <p class="note" v-if="totalavaliable>=totalused">
          ( {{$t("serviceDriveAuth['到期後將變更為IES基本空間，超出基本空間值將被收回']")}} )
        </p>
      </i-col>
    </Row>
    <div
      v-if="spaceStatus.notbuy!=true"
      class="service-list buy-list"
      :style="{ visibility: isloading == true ? 'hidden' : 'visible' }"
    >
      <div class="service-listTitle">{{$t("serviceDriveAuth['購買記錄']")}}</div>

      <div class="list-wrap">
        <!--無資料時-->
        <div
          v-if="spaceStatus.hasOwnProperty('history') == false"
          class="no-data-text"
        >
          <img src="../../../assets/icon/no_data.png" width="120" />
          <p style="color: #808080">{{$t("serviceDriveAuth['暂无数据']")}}</p>
        </div>
        <!--有資料時-->
        <div
          class="buy-item"
          v-for="(i, orderId) in spaceStatus.history"
          :key="orderId"
        >
          <Row>
            <i-col :xs="24" :sm="24" :md="24" :lg="3"
              ><v-icon class="tmd-icon" iconClass="tmd"></v-icon
            ></i-col>
            <i-col :xs="24" :sm="24" :md="24" :lg="21"
              ><p class="title">
                {{$t("serviceDriveAuth['醍摩豆智慧教學服務空間']")}}
                {{ numberWithCommas(i.number) }} {{ i.unit }}
              </p>
              <Row s>
                <i-col :xs="24" :sm="24" :md="24" :lg="12"
                  ><p class="nomal-text">
                    {{$t("serviceDriveAuth['訂單日期']")}}<span class="strong-text">{{
                      converTime(i.orderDate)
                    }}</span>
                  </p></i-col
                >
                <i-col :xs="24" :sm="24" :md="24" :lg="12"
                  ><p class="nomal-text">
                    {{$t("serviceDriveAuth['到期日']")}}<span class="strong-text">{{
                      converTime(i.endDate)
                    }}</span>
                  </p></i-col
                >
              </Row>
            </i-col>
          </Row>
        </div>
      </div>
      <div class="buy-btn">{{$t("serviceDriveAuth['添購其他服務']")}}</div>
    </div>
  </div>
</template>

<script>
import SpaceChart from "./SpaceChart.vue";
import "@/icons/svg/tmd.svg";
export default {
  props: ["spaceStatus", "windowHeight", "windowWidth", "isloading"],
  name: "SpaceStatus",
  components: {
    SpaceChart,
  },
  data() {
    return {
      remainDays: 0,
      totalavaliable: 0,
      totalavaliableText: "",
      totalused: 0,
      totalusedText: "",
      unUsed: 0,
      unUsedText: "",
    };
  },
  computed:{
    tooltipstext:function(){
      return this.$t("serviceDriveAuth['空間已到期，超過僅供檢視']")
    }
  },
  watch: {
    spaceStatus: function (value) {
      console.log(value)
      if (value !== undefined) {
        this.remainDays = this.dateRemain(
          this.today(),
          this.converTime(value.endDate)
        );
        this.totalavaliable = this.finalFormatNum(value.avaliable);
        this.totalavaliableText = this.finalFormatText(value.avaliable);
        this.totalused = this.finalFormatNum(value.totalused);
        this.totalusedText = this.finalFormatText(value.totalused);
        this.unUsed = this.finalFormatNum(value.unUsed);
        this.unUsedText = this.finalFormatText(value.unUsed);
      }
    },
  },
  methods: {
    
    finalFormatNum(byte) {
      return this.numberWithCommas(this.formatBytes(byte)).substr(
        0,
        this.numberWithCommas(this.formatBytes(byte)).length - 2
      );
    },
    finalFormatText(byte) {
      return this.numberWithCommas(this.formatBytes(byte)).substr(
        this.numberWithCommas(this.formatBytes(byte)).length - 2,
        this.numberWithCommas(this.formatBytes(byte)).length - 1
      );
    },

    formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return "0 Bytes";
      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
    },

    gotoTeacherManagent() {
      this.$router.push("/home/teachermgmt");
    },
    numberWithCommas(x) {
      if (x != undefined)
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    converTime: function (time) {
      //time: Unix timestamp(秒)
      let datetime = new Date();
      //let timerecount = time * 1000 - datetime.getTimezoneOffset() * 60 * 1000;
      let timerecount = time * 1000;
      datetime.setTime(timerecount);
      let year = datetime.getFullYear();
      let month = datetime.getMonth() + 1;
      let date = datetime.getDate();
      let hour = datetime.getHours();
      let ampm = hour >= 12 ? "PM" : "AM";
      hour %= 12;
      hour = hour || 12; // the hour '0' should be '12'
      let minute = datetime.getMinutes();
      return year + "." + month + "." + date;
    },
    today() {
      var today = new Date();
      var dd = String(today.getDate()).padStart(2, "0");
      var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
      var yyyy = today.getFullYear();

      today = yyyy + "/" + mm + "/" + dd;
      return today;
    },
    dateRemain(today, endday) {
     
     
      let strEndday = endday.replace('.','/');

      //console.log(today, strEndday);

      let oDate1 = new Date(today);
      let oDate2 = new Date(strEndday);
      let iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); // 把相差的毫秒數轉換為天數
      //console.log(iDays);
      return iDays;
    },
  },
};
</script>

<style lang='less'>
@import "./SpaceStatus.less";
</style>