<script>
import { get } from '../../utils/request'
import * as echarts from 'echarts'
import { userStore } from '@/store/userInfo'
import { productListNameMapping } from '../../utils/mapping'


export default {
  beforeRouteEnter(to, from, next) {
    // 判断是不是分销商
    const role = userStore().user.role||''
    if(role.indexOf('4') !== -1){
      next('/reseller-manage-product')
    }else{
      next()
    }
  },
  data () {
    return {
      overview: {
        totalLicenses: null,
        assignedLicenses: null,
        availableLicenses: null,
        activatedDevices: null,
      },
      productList: [],
      overviewProduct: {
        totalLicenses: null,
        availableLicenses: null,
        activatedDevices: null,
        validPeriod: null,
        expireDate: null,
        timeLeft: null
      },
      dataFilterProductSelect: '',
      dataFilterSelectLoading: false,
      chartData: {
        date: [],
        assignedLicensesYData: [],
        activatedLicenseYData: []
      },
      chartSelectValue: '2',
      chartSelectLoading: false,
      teamData: {
        totalTeam: null,
        totalMember: null,
        assignedMember: null
      },
      teamMemberData: {
        teamMember: null,
        assignedMember: null,
        remainingActivatableDevices: null
      },
      teamList: [],
      teamSelect: '',
      teamFilterProductSelect: '',
      teamSelectLoading: false
    }
  },
  created () {
    this.getOverview()
    this.getOverviewProduct()
    this.getChartStatistics(2)
    this.getTeamData()
    this.getTeamMemberData()
    this.getProductList()
    this.getTeamList()
  },
  mounted () {
    this.drawLine()
  },
  methods: {
    // 获取全局预览数据，不区分产品
    getOverview () {
      get('/pdf-tech/vppDashboard/getOverview').then((res) => {
        if (res.data.code === 200) {
          this.overview.totalLicenses = res.data.result.totalLicenses
          this.overview.assignedLicenses = res.data.result.availableDevices
          this.overview.availableLicenses = res.data.result.remainingAvailableDevices
          this.overview.activatedDevices = res.data.result.activatedDevices
        }
      })
    },
    // 获取全局预览数据，区分产品
    getOverviewProduct () {
      if (this.dataFilterSelectLoading) return
      this.dataFilterSelectLoading = true
      get('/pdf-tech/vppDashboard/getOverviewProduct', {
        codeList: this.dataFilterProductSelect
      }).then((res) => {
        setTimeout(() => {
          this.dataFilterSelectLoading = false
        }, 2000)
        Object.keys(this.overviewProduct).forEach(key => (this.overviewProduct[key] = ''))
        if (res.data.code === 200) {
          this.overviewProduct.totalLicenses = res.data.result.totalLicenses
          this.overviewProduct.availableLicenses = res.data.result.remainingAvailableDevices
          this.overviewProduct.activatedDevices = res.data.result.activatedDevices
          this.overviewProduct.validPeriod = res.data.result.validPeriod
          //转换过期时间
          let time = res.data.result.expireDate
          if(time !== '--'){
            let month = time
            switch (true) {
              case month.indexOf('Jan') !== -1 :
                month = '01'
                break
              case month.indexOf('Feb') !== -1:
                month = '02'
                break
              case month.indexOf('Mar') !== -1:
                month = '03'
                break
              case month.indexOf('Apr') !== -1:
                month = '04'
                break
              case month.indexOf('May') !== -1:
                month = '05'
                break
              case month.indexOf('Jun') !== -1:
                month = '06'
                break
              case month.indexOf('Jul') !== -1:
                month = '07'
                break
              case month.indexOf('Aug') !== -1:
                month = '08'
                break
              case month.indexOf('Sep') !== -1:
                month = '09'
                break
              case month.indexOf('Oct') !== -1:
                month = '10'
                break
              case month.indexOf('Nov') !== -1:
                month = '11'
                break
              case month.indexOf('Dec') !== -1:
                month = '12'
                break
              default:
                month = ''
                break
            }
            let day = time.split(' ')[2]
            let year = time.slice(-4)
            time = month + '/' + day + '/' + year
          }
          this.overviewProduct.expireDate = time
          this.overviewProduct.timeLeft = res.data.result.timeLeft
        }
      })
    },
    // 获取图表数据
    getChartStatistics (type) {
      if (this.chartSelectLoading) return
      this.chartSelectLoading = true
      if (this.chartSelectValue !== '') {
        type = this.chartSelectValue
      } else {
        type = 2
      }
      get('/pdf-tech/vppDashboard/getChartStatistics/' + type).then((res) => {
        setTimeout(() => {
          this.chartSelectLoading = false
        }, 2000)
        if (res.data.code === 200) {
          this.chartData.date = []
          this.chartData.assignedLicensesYData = []
          this.chartData.activatedLicenseYData = []
          res.data.result.forEach((item) => {
            this.chartData.date.push(this.formatterDate(item.date))
            this.chartData.assignedLicensesYData.push(item.licences.assignedLicenses)
            this.chartData.activatedLicenseYData.push(item.licences.activatedLicense)
          })
          this.drawLine()
        } else {
          this.$message.error({duration: 5000, message: res.data.msg})
        }
      })
    },
    // 获取团队数据
    getTeamData () {
      get('/pdf-tech/vppDashboard/getTeamData').then((res) => {
        if (res.data.code === 200) {
          this.teamData.totalTeam = res.data.result.totalTeam
          this.teamData.totalMember = res.data.result.totalMember
          this.teamData.assignedMember = res.data.result.assignedMember
        }
      })
    },
    // 获取团队成员数据
    getTeamMemberData () {
      if (this.teamSelectLoading) return
      this.teamSelectLoading = true
      const arr = []
      if(this.teamFilterProductSelect){
        arr.push(this.teamFilterProductSelect)
      }
      //teamId: this.teamSelect,
      // codeList: arr
      get('/pdf-tech/vppDashboard/getTeamMemberData?teamId='+this.teamSelect+'&codeList='+arr).then((res) => {
        setTimeout(() => {
          this.teamSelectLoading = false
        }, 2000)
        Object.keys(this.teamMemberData).forEach(key => (this.teamMemberData[key] = ''))
        if (res.data.code === 200) {
          this.teamMemberData.teamMember = res.data.result.teamMember
          this.teamMemberData.assignedMember = res.data.result.assignedMember
          this.teamMemberData.remainingActivatableDevices = res.data.result.remainingActivatableDevices
        }
      })
    },
    // 绘制Echarts图表
    drawLine () {
      let myChart = echarts.getInstanceByDom(
        this.$refs.chart
      )
      if (myChart == null) {
        myChart = echarts.init(this.$refs.chart)
      }
      myChart.setOption({
        color: ['#1460F3', '#FFAE49'],
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#F6F7F9',
          borderColor: '#D9D9D9',
          extraCssText: 'box-shadow: none;'
        },
        legend: {
          right: 0,
          top: -30,
          itemWidth: 124,
          itemHeight: 0,
          itemGap: 24,
          textStyle: {
            color: '#808185',
            fontSize: 14,
            lineHeight: 14,
            padding: 7
          },
          formatter: '\n\n{name}',
          align:'none'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartData.date,
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: 'rgba(81, 140, 255, 0.16)',
              width: 2,
              type: 'solid'
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          axisLabel: {
            margin: 10,
            color: '#505258'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            margin: 20,
            color: '#505258'
          },
          splitLine: {
            lineStyle: {
              color: ['#D9D9D9']
            }
          },
          minInterval: 1,
          max: function (value) {
            return value.max + 2
          }
        },
        series: [
          {
            name: 'Assigned Licenses',
            type: 'line',
            data: this.chartData.assignedLicensesYData,
            lineStyle: {
              width: 3
            },
            showSymbol: false,
            symbol: 'circle',
            symbolSize: 12,
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 4,
              shadowBlur: 4,
              shadowColor: 'rgba(28, 78, 174, 0.31)'
            }
          },
          {
            name: 'Activated Licenses',
            type: 'line',
            data: this.chartData.activatedLicenseYData,
            lineStyle: {
              width: 3
            },
            showSymbol: false,
            symbol: 'circle',
            symbolSize: 12,
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 4,
              shadowBlur: 4,
              shadowColor: 'rgba(148, 98, 37, 0.22)'
            }
          }
        ]
      }, true)
      window.onresize = function () {
        myChart.resize()
      }
    },
    // 获取所有产品
    getProductList () {
      get('/pdf-tech/product/listWithAdmin').then((res) => {
        if (res.data.code === 200) {
          this.productList = productListNameMapping(res.data.result)
        }
      })
    },
    // 获取所有团队
    getTeamList() {
      // get('/pdf-tech/vppTeam/getManageTeamList', {
      //   teamId: '',
      //   keyword: ''
      // }).then((res) => {
      //   if (res.data.code === 200) {
      //     res.data.result.list.forEach(item => {
      //       this.teamList.push({
      //           label: item.name,
      //           value: item.id
      //       })
      //     })
      //   }
      // })
      get('/pdf-tech/vppTeam/listWithAdmin').then((res) => {
        if (res.data.code === 200) {
          res.data.result.forEach(item => {
            this.teamList.push({
                label: item.name,
                value: item.id
            })
          })
        }
      })
    },
    // 日期自定格式
    formatterDate (data) {
      if (!data) return ''
      const dateArr = data.split('-')
      return dateArr[1] + '/' + dateArr[2]
    }
  }
}
</script>

<template>
  <div>
    <h1>Home</h1>
    <div class="flex justify-between mt-24px mb-32px">
      <div class="block flex items-center p-24px basis-full mr-24px">
        <img src="@/../static/images/dashboard/total_licenses.png" alt="total_licenses" class="w-48px h-48px mr-16px">
        <div class="tip-nav">
          <p class="text-32px font-700 leading-36px text-[#232A40]">{{ overview.totalLicenses }}</p>
          <p class="text-16px font-700 leading-20px text-[#505258]">Total licenses</p>
          <div class="tip"><span class="tip-icon"></span>Number of total license under this account</div>
        </div>
      </div>
      <div class="block flex items-center p-24px basis-full mr-24px">
        <img src="@/../static/images/dashboard/assigned_licenses.png" alt="assigned_licenses" class="w-48px h-48px mr-16px">
        <div class="tip-nav">
          <p class="text-32px font-700 leading-36px text-[#232A40]">{{ overview.assignedLicenses }}</p>
          <p class="text-16px font-700 leading-20px text-[#505258]">Total Activatable Devices</p>
          <div class="tip"><span class="tip-icon"></span>Total number of devices that can be activated</div>
        </div>
      </div>
      <div class="block flex items-center p-24px basis-full mr-24px">
        <img src="@/../static/images/dashboard/availqble_licenses.png" alt="availqble_licenses" class="w-48px h-48px mr-16px">
        <div class="tip-nav">
          <p class="text-32px font-700 leading-36px text-[#232A40]">{{ overview.availableLicenses }}</p>
          <p class="text-16px font-700 leading-20px text-[#505258]">Remaining Activatable Devices</p>
          <div class="tip tip-long"><span class="tip-icon"></span>Number of devices remaining to be activated</div>
        </div>
      </div>
      <div class="block flex items-center p-24px basis-full">
        <img src="@/../static/images/dashboard/activated_devices.png" alt="activated_devices" class="w-48px h-48px mr-16px">
        <div class="tip-nav">
          <p class="text-32px font-700 leading-36px text-[#232A40]">{{ overview.activatedDevices }}</p>
          <p class="text-16px font-700 leading-20px text-[#505258]">Activated Devices</p>
          <div class="tip tip-other"><span class="tip-icon"></span>Number of activated device</div>
        </div>
      </div>
    </div>

    <h2>Filter</h2>
    <div class="block p-24px mt-12px mb-32px">
      <div class="flex">
        <select v-model="dataFilterProductSelect" name="dataFilterProduct" class="min-w-180px mr-16px" :class="{ '!text-[#232A40]': dataFilterProductSelect !== '' }">
          <option value="">Product</option>
          <option v-for="item in productList" :key="item.id" :value="item.code">{{ item.name }}</option>
        </select>
        <div @click="getOverviewProduct" class="w-70px h-28px border-[#1460F3] border-1px rounded-4px px-10px py-4px text-14px leading-20px text-[#1460F3] cursor-pointer hover:opacity-80">Confirm</div>
      </div>
      <div class="flex flex-wrap justify-between mt-24px">
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Total Licenses</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.totalLicenses }}</span>
        </div>
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Remaining Activatable Devices</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.availableLicenses }}</span>
        </div>
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center">
          <span class="text-14px font-bold text-[#505258]">Number of Activated Devices</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.activatedDevices }}</span>
        </div>
      </div>
      <div class="flex flex-wrap justify-between mt-24px">
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Valid Period (month)</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.validPeriod }}</span>
        </div>
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Expiration Date</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.expireDate }}</span>
        </div>
        <div class="h-56px flex-1 bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex justify-between items-center">
          <span class="text-14px font-bold text-[#505258]">Days Left (day)</span>
          <span class="text-16px font-bold text-[#232A40]">{{ overviewProduct.timeLeft }}</span>
        </div>
      </div>
    </div>

    <h2>Statistics</h2>
    <div class="block p-24px mt-12px mb-32px">
      <div class="flex">
        <div class="flex justify-between">
          <select v-model="chartSelectValue" name="date" class="min-w-180px mr-16px" :class="{ '!text-[#232A40]': chartSelectValue !== '' }">
            <option value="" disabled>Statistics Time</option>
            <option value="1">Today</option>
            <option value="2" selected>Last 7 Days</option>
            <option value="3">Last 30 Days</option>
            <option value="4">This Month</option>
          </select>
          <div @click="getChartStatistics()" class="w-70px h-28px border-[#1460F3] border-1px rounded-4px px-10px py-4px text-14px leading-20px text-[#1460F3] cursor-pointer hover:opacity-80">Confirm</div>
        </div>
        <div></div>
      </div>
      <div class="w-[100%] h-320px" ref="chart"></div>
    </div>

    <h2>Team Data</h2>
    <div class="flex justify-between mt-12px">
      <div class="block py-24px flex-auto mr-24px text-center">
        <div class="relative inline-block w-96px h-96px inline-flex items-center justify-center mb-12px">
          <img src="@/../static/images/dashboard/team_data_blue.png" class="w-96px h-96px absolute top-0 left-0">
          <p class="text-32px text-[#1460F3] leading-36px font-700">{{ teamData.totalTeam }}</p>
        </div>
        <p class="text-16px leading-20px font-700 text-[#505258]">Total Team</p>
      </div>
      <div class="block py-24px flex-auto mr-24px text-center">
        <div class="relative inline-block w-96px h-96px inline-flex items-center justify-center mb-12px">
          <img src="@/../static/images/dashboard/team_data_yellow.png" class="w-96px h-96px absolute top-0 left-0">
          <p class="text-32px text-[#FFAE49] leading-36px font-700">{{ teamData.totalMember }}</p>
        </div>
        <p class="text-16px leading-20px font-700 text-[#505258]">Total Members</p>
      </div>
      <div class="block py-24px flex-auto text-center">
        <div class="relative inline-block w-96px h-96px inline-flex items-center justify-center mb-12px">
          <img src="@/../static/images/dashboard/team_data_purple.png" class="w-96px h-96px absolute top-0 left-0">
          <p class="text-32px text-[#664FF5] leading-36px font-700">{{ teamData.assignedMember }}</p>
        </div>
        <p class="text-16px leading-20px font-700 text-[#505258]">Team Assigned Member</p>
      </div>
    </div>

    <div class="block p-24px mt-24px mb-32px">
      <div class="flex">
        <select v-model="teamSelect" name="team" class="min-w-140px mr-16px" :class="{ '!text-[#232A40]': teamSelect !== '' }">
          <option value="">Team</option>
          <option v-for="item in teamList" :key="item.value" :value="item.value">{{ item.label }}</option>
        </select>
        <select v-model="teamFilterProductSelect" name="teamFilterProduct" class="min-w-180px mr-16px" :class="{ '!text-[#232A40]': teamFilterProductSelect !== '' }">
          <option value="">Product</option>
          <option v-for="item in productList" :key="item.id" :value="item.code">{{ item.name }}</option>
        </select>
        <div @click="getTeamMemberData" class="w-70px h-28px border-[#1460F3] border-1px rounded-4px px-10px py-4px text-14px leading-20px text-[#1460F3] cursor-pointer hover:opacity-80">Confirm</div>
      </div>
      <div class="flex flex-wrap justify-between mt-24px">
        <div class="h-56px bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex-auto flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Team Member</span>
          <span class="text-16px font-bold text-[#232A40]">{{ teamMemberData.teamMember }}</span>
        </div>
        <div class="h-56px bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex-auto flex justify-between items-center mr-24px">
          <span class="text-14px font-bold text-[#505258]">Team Assigned Member</span>
          <span class="text-16px font-bold text-[#232A40]">{{ teamMemberData.assignedMember }}</span>
        </div>
        <div class="h-56px bg-[#F6F7F9] border-[#D9D9D9] border-1px rounded-4px py-18px pl-24px pr-40px flex-auto flex justify-between items-center">
          <span class="text-14px font-bold text-[#505258]">Remaining Activatable Devices</span>
          <span class="text-16px font-bold text-[#232A40]">{{ teamMemberData.remainingActivatableDevices }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.tip-nav{
  position: relative;
  cursor: pointer;
  &:hover .tip{
    display: block;
  }
  .tip{
    position: absolute;
    bottom: -65px;
    left: -40%;
    background: #373A47;
    color: #fff;
    padding: 8px;
    width: 200px;
    box-shadow: 0px 4px 16px rgba(129, 149, 200, 0.18);
    border-radius: 4px;
    font-size: 14px;
    line-height: 20px;
    display: none;
    .tip-icon{
      position: absolute;
      width: 0;
      height: 0;
      top: -7px;
      left: calc(50% - 8px);
      border-left: 8px solid transparent;
      border-right: 8px solid transparent;
      border-bottom: 8px solid #373A47;
      z-index: 10000;
    }
  }
  .tip-other{
    bottom: -45px;
  }
  .tip-long{
    bottom: -85px;
  }
}
</style>