<template>
  <div class="service-list">
    <div class="service-listTitle listTitle-noMargin"><span class="title-item" :class="{ 'title-checked': true }" @click="setTab(0)">{{$t("serviceDriveAuth['服務授權列表']")}}<span class="title-checked-line"></span></span> <span class="title-item" @click="setTab(1)">{{$t("serviceDriveAuth['智慧教室授權管理']")}}</span></div>
    <div class="serviceList-wrap" :style="{ height: windowHeight - 116 + 'px' }">
      <div class="service-item" v-for="(item, index) in serviceList" :key="index" v-show="item.prodCode != 'AEGMCPLY'">
        <div class="detail-btn" @click="setIntroOpen(index)">
          <Icon v-show="serviceIntroIsOpen[index].isOpen == false" type="ios-arrow-down" />
          <Icon v-show="serviceIntroIsOpen[index].isOpen == true" type="ios-arrow-up" />
        </div>
        <div v-for="(proName, index) in serviceNameList" :key="index">
          <p class="service-name" v-if="item.prodCode == proName && proName != 'AEGMCPLY'">
            {{ $t(`serviceDriveAuth['${proName}']`) }}
          </p>
        </div>
        <p class="unbuy" v-if="item.hasOwnProperty('notbuy') == true">{{$t("serviceDriveAuth['未購買']")}}</p>
        <p class="isbuy" v-else>{{$t("serviceDriveAuth['已購買']")}}</p>

        <p class="nomal-text">
          {{$t("serviceDriveAuth['服務啟用 / 到期日:']")}}
          <span class="strong-text" v-if="item.startDate != 0 && item.prodCode != 'RYGVCPLY'">{{ converTime(item.startDate) }} - {{ converTime(item.endDate) }}</span>
          <span class="strong-text" v-if="item.startDate == 0 && item.prodCode != 'RYGVCPLY'">--</span>
          <span class="strong-text" v-if="item.prodCode == 'RYGVCPLY' && isNaN(aclassOneTimeLimitData.startDate) == false">{{ converTime(aclassOneTimeLimitData.startDate) }} - {{ converTime(aclassOneTimeLimitData.endDate) }}</span>
        </p>
        <div v-if="item.hasOwnProperty('notbuy') != true">
          <Row class="time-bar-wrap">
            <i-col :xs="24" :sm="24" :md="24" :lg="20" style="padding-right: 10px">
              <div class="time-bar" v-if="item.startDate != 0"></div>
              <div
                class="remain-bar"
                v-if="item.startDate != 0"
                :style="{
                  width: (dateRemain(today(), converTime(item.endDate)) / dateRemain(converTime(item.startDate), converTime(item.endDate))).toFixed(2) * 100 + '%',
                  'background-color': colorPercent(converTime(item.startDate), converTime(item.endDate)) ? '#ad3435' : '#1cc0f3'
                }"
              ></div>
            </i-col>
            <i-col :xs="24" :sm="24" :md="24" :lg="4" v-if="item.startDate != 0">
              <span class="remainDay">{{$t("serviceDriveAuth['剩餘']")}}</span>
              <span
                class="remainDay-text"
                :style="{
                  color: colorPercent(converTime(item.startDate), converTime(item.endDate)) ? '#ad3435' : '#1cc0f3'
                }"
                >{{ dateRemain(today(), converTime(item.endDate)) }}</span
              ><span class="remainDay">{{$t("serviceDriveAuth['天']")}}</span>
            </i-col>
          </Row>
          <Row class="time-bar-wrap" v-if="isNaN(aclassOneTimeLimitData.startDate) == false">
            <i-col :xs="24" :sm="24" :md="24" :lg="20" style="padding-right: 10px">
              <div class="time-bar" v-if="item.prodCode == 'RYGVCPLY'"></div>
              <div
                class="remain-bar"
                v-if="item.prodCode == 'RYGVCPLY'"
                :style="{
                  width: (dateRemain(today(), converTime(aclassOneTimeLimitData.endDate)) / dateRemain(converTime(aclassOneTimeLimitData.startDate), converTime(aclassOneTimeLimitData.endDate))).toFixed(2) * 100 + '%',
                  'background-color': colorPercent(converTime(aclassOneTimeLimitData.startDate), converTime(aclassOneTimeLimitData.endDate)) ? '#ad3435' : '#1cc0f3'
                }"
              ></div>
            </i-col>

            <i-col :xs="24" :sm="24" :md="24" :lg="4" v-if="item.prodCode == 'RYGVCPLY'">
              <span class="remainDay">{{$t("serviceDriveAuth['剩餘']")}}</span>
              <span
                class="remainDay-text"
                :style="{
                  color: colorPercent(converTime(aclassOneTimeLimitData.startDate), converTime(aclassOneTimeLimitData.endDate)) ? '#ad3435' : '#1cc0f3'
                }"
                >{{ dateRemain(today(), converTime(aclassOneTimeLimitData.endDate)) }}</span
              ><span class="remainDay">{{$t("serviceDriveAuth['天']")}}</span>
            </i-col>
          </Row>
        </div>
        <!--給AclassOne-->
        <div class="detailinfo-block" v-if="index == 0 && serviceIntroIsOpen[index].isOpen == true">
          <Row>
            <i-col :xs="24" :sm="24" :md="24" :lg="10">
              <p class="nomal-text auth-num" v-if="item.hasOwnProperty('notbuy') == false">
                {{$t("serviceDriveAuth['無週期授權數量']")}}：<span class="strong-text">{{ item.avaliable }}</span>
              </p>
            </i-col>
            <i-col :xs="24" :sm="24" :md="24" :lg="14">
              <p class="nomal-text auth-num" v-if="aclassOneTimeLimitData != ''">
                {{$t("serviceDriveAuth['有週期授權數量']")}}：<span class="strong-text">{{ aclassOneTimeLimitData.avaliable }}</span>
              </p></i-col
            >
          </Row>
          <Row v-if="item.hasOwnProperty('notbuy') == false">
            <i-col :xs="24" :sm="24" :md="24" :lg="10">
              <div class="title-rec"></div>
              <p class="nomal-text title-withRec">
                 {{$t("serviceDriveAuth['固定分配數']")}}：<span class="strong-text">{{ item.staUsed }} ({{ ((item.staUsed / item.avaliable) * 100).toFixed(1) }}%)</span>
              </p>
              <br />
              <div class="title-rec"></div>
              <p class="nomal-text title-withRec">
                 {{$t("serviceDriveAuth['動態分配數']")}}：<span class="strong-text">{{ item.dynUsed }} ({{ ((item.dynUsed / item.avaliable) * 100).toFixed(1) }}%)</span>
              </p></i-col
            >
            <i-col :xs="24" :sm="24" :md="24" :lg="7">
              <p class="nomal-text">
                 {{$t("serviceDriveAuth['總使用率']")}}：<span class="strong-text"> {{ (((item.dynUsed + item.staUsed) / item.avaliable) * 100).toFixed(1) }}%</span>
              </p></i-col
            >
            <i-col :xs="24" :sm="24" :md="24" :lg="7"> <AclassOneChart :less="item.dynUsed" :used="item.staUsed" :avaliable="item.avaliable"/></i-col>
          </Row>
          <p
            v-if="item.hasOwnProperty('notbuy') == true"
            class="detail"
            :style="{
              'margin-top': item.hasOwnProperty('notbuy') != true ? '0px' : '10px'
            }"
          >
            {{$t("serviceDriveAuth['詳細服務內容']")}}:
          </p>
          <Row v-if="item.hasOwnProperty('notbuy') == true">
            <i-col :xs="24" :sm="24" :md="24" :lg="16"> <p class="intro-text">待提供</p></i-col>
          </Row>
          <div class="action-btn" @click="gotoStudentManagent()">
            {{$t("serviceDriveAuth['管理AClassOne授權']")}}:
          </div>
        </div>

        <!--給其他產品-->
        <div class="detailinfo-block" v-if="index != 0 && serviceIntroIsOpen[index].isOpen == true">
          <p class="detail" :style="{ 'margin-top': item.hasOwnProperty('notbuy') != true ? '0px' : '10px' }">
            {{$t("serviceDriveAuth['詳細服務內容']")}}:
          </p>
          <Row>
            <i-col :xs="24" :sm="24" :md="24" :lg="16"> <p class="intro-text">待提供</p></i-col>
          </Row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import AclassOneChart from './AclassOneChart'
import { mapGetters,mapMutations } from 'vuex'
export default {
  props: ['serviceList', 'windowWidth', 'windowHeight'],
  name: 'ServiceList',
  data() {
    return {
      serviceIntroIsOpen: {},
      oriIndex: '',
      aclassOneTimeLimitData: ''
    }
  },
  components: {
    AclassOneChart
  },
  computed: {
    ...mapGetters({
      serviceIntroIsOpenVuex: 'serviceDriveAuth/getServiceIntroIsOpen',
      serviceNameList: 'serviceDriveAuth/getServiceNameList'
    })
  },
  created() {
    this.serviceIntroIsOpen = this.serviceIntroIsOpenVuex
  },

  watch: {
    serviceList: function() {
      //根據服務的長度生出開關，只要服務數量變動就必須重置
      let temp = []

      for (let i = 0; i < this.serviceList.length; i++) {
        temp.push({
          index: i,
          isOpen: false
        })
        temp[0].isOpen = true //預設把AclassOne細節打開
        if (this.serviceList[i].prodCode == 'AEGMCPLY' && this.serviceList[i].hasOwnProperty('notbuy') != true) {
          //console.log(this.serviceList[i])
          this.aclassOneTimeLimitData = this.serviceList[i]
        }
      }
      this.serviceIntroIsOpen = temp
    }
  },
  beforeRouteLeave(to, from, next) {
    this.setTab(0)
    next()
  },
  methods: {
    ...mapMutations({
      setTab: 'serviceDriveAuth/setTab'
    }),
    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
    },
    gotoStudentManagent() {
      this.$router.push('/home/studentAccount')
    },
    colorPercent: function(a, b) {
      if (this.dateRemain(this.today(), b) / this.dateRemain(a, b) < 0.3) return true
      else return false
    },
    setIntroOpen(index) {
      this.serviceIntroIsOpen[index].isOpen = !this.serviceIntroIsOpen[index].isOpen
      //console.log(index, this.serviceIntroIsOpen);
    },
    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 './ServiceList.less';
</style>
