<template>
  <div class="license">
    <div class="license-left">
      <div class="license-left-header" :class="{'license-left-header-red':active !== 0}">
        <div>
         <div class="license-left-header-icon">
           <!-- 是否激活 -->
           <i v-if="active === 0" class="nz-icon nz-icon-import-success"></i>
           <i v-else class="nz-icon nz-icon-import-failed1"></i>
         </div>
          <div>{{$t('license.nzTitleValue')}}</div>
        </div>
        <div v-if="active === 0">{{$t('license.active')}}</div>
        <div v-else>{{$t('license.inactive')}}</div>
      </div>
      <div class="license-left-body">
        <div>
          <div class="license-left-boyd-title" style="margin-top: 25px">{{$t('license.type')}}</div>
          <div class="license-left-boyd-value">{{ licenseMark.type ? licenseMark.type : '-'}}</div>
        </div>
        <div>
          <div class="license-left-boyd-title">{{$t('license.organization')}}</div>
          <div class="license-left-boyd-value">{{ licenseMark.organization ? licenseMark.organization : '-'}}</div>
        </div>
        <div>
          <div class="license-left-boyd-title">{{$t('license.id')}}</div>
          <div class="license-left-boyd-value">{{ licenseMark.supportID ? licenseMark.supportID : '-'}}</div>
        </div>
        <div>
          <div class="license-left-boyd-title">{{$t('license.proDate')}}</div>
          <div class="license-left-boyd-value">
            <span v-if="licenseList.production_date">{{utcTimeToTimezoneStr(licenseList.production_date * 1000)}}</span>
            <span v-else>-</span>
          </div>
        </div>
        <div>
          <div class="license-left-boyd-title">{{$t('license.expDate')}}</div>
          <div class="license-left-boyd-value">
            <span v-if="expData.id === '20001' && expData.license.license_type === 'expiration'">{{utcTimeToTimezoneStr(expData.license.exp_date * 1000)}}</span>
            <span v-else-if="expData.id === '20001' && expData.license.license_type === 'perpetual'">{{$t('license.permanent')}}</span>
            <span v-else-if="expData.id === '20001' && expData.license.license_type === 'trial'">{{utcTimeToTimezoneStr(this.stateItem * 1000)}} ~ {{ utcTimeToTimezoneStr(this.endItem * 1000)}}</span>
            <span v-else>-</span>
          </div>
        </div>
      </div>
      <div class="license-left-footer">
        <div class="license-left-footer-download" @click="downloadLicense">
          <i class="nz-icon nz-icon-download"></i><span>{{$t('license.downloadID')}}</span>
        </div>
        <el-upload
          ref="upload"
          accept=".xml"
          action=""
          class="license-left-footer-upload"
          :file-list="uploadFileList"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <i class="nz-icon nz-icon-Upload1"></i><span>{{$t('license.uploadLicense')}}</span>
        </el-upload>
      </div>
    </div>
    <div class="license-right">
      <div class="license-right-header">
        <div class="license-right-header-title">{{$t('license.devices')}}&nbsp;({{tableData ? tableData.length : 0}})</div>
      </div>
      <div class="license-right-table">
        <el-table :data="tableData" v-loading="loading">
          <el-table-column v-for="(item, index) in tableTitle" :key="index">
            <template slot="header">
              <span class="data-column__span">{{item.label}} <i class="nz-icon nz-icon-label" v-if="item.type==='label'"/></span>
            </template>
            <template slot-scope="scope" :column="item">
              <template v-if="item.prop === 'devicesName'">
                <span>{{getLicense(scope.row)}}</span>
              </template>
              <template v-else-if="item.prop === 'status'">
                <div v-if="scope.row.status === 0">
                  <div class="active-icon green-bg inline-block"></div> {{ $t('license.active') }}
                </div>
                <div v-else-if="scope.row.status !== 0">
                  <div class="active-icon red-bg inline-block"></div> {{ $t('license.inactive') }}
                </div>
              </template>
              <template v-else>-</template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'license',
  data () {
    return {
      licenseList: {},
      licenseMark: {},
      tableData: [],
      tableTitle: [
        {
          label: this.$t('license.devicesName'),
          prop: 'devicesName'
        },
        {
          label: this.$t('license.status'),
          prop: 'status'
        }
      ],
      expData: {},
      uploadFileList: [],
      uploadFile: { file: '' },
      active: 0,
      loading: true,
      stateItem: '',
      endItem: ''
    }
  },
  methods: {
    licenseGetData () {
      this.$get('/sys/license/detail').then(res => {
        if (res.code === 200) {
          this.licenseMark = res.data.license
          this.licenseList = res.data.license.hasp
          this.licenseList.feature.map(e => {
            if (e.id === '20001') {
              this.expData = e
              this.stateItem = e.license.time_start
              this.endItem = e.license.end_time * 1 + e.license.time_start * 1
            }
          })
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getTimeString () {
      const split = '-'
      const date = new Date()
      const year = date.getFullYear()
      const month = this.formatNum(date.getMonth() + 1)
      const day = this.formatNum(date.getDate())
      const hours = this.formatNum(date.getHours())
      const minutes = this.formatNum(date.getMinutes())
      const seconds = this.formatNum(date.getSeconds())
      return year + split + month + split + day + ' ' + hours + split + minutes + split + seconds
    },
    formatNum (num) {
      return num > 9 ? num : '0' + num
    },
    licenseGetStatus () {
      this.$get('/sys/license/status').then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.active = res.data.status
          }
        } else {
          this.$message.error(res.msg)
        }
      })
      this.$get('/sys/license/status', { scope: 'all' }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list
          this.loading = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleChange (file, fileList) {
      if (fileList.length > 0) {
        this.uploadFileList = [fileList[fileList.length - 1]]
      }
      this.uploadFile.file = this.uploadFileList[0]
      this.upload()
    },
    upload () {
      const form = new FormData()
      form.append('file', this.uploadFile.file.raw)
      this.$post('/sys/license/upload', form).then(res => {
        if (res.code == 200) {
          this.licenseGetStatus()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    downloadLicense () {
      this.$get('/sys/license/token').then(res => {
        const fileName = this.licenseList.id + '-' + this.getTimeString() + '.xml'
        if (window.navigator.msSaveOrOpenBlob) {
          // 兼容ie11
          const blobObject = new Blob([res])
          window.navigator.msSaveOrOpenBlob(blobObject, fileName)
        } else {
          const url = URL.createObjectURL(new Blob([res]))
          const a = document.createElement('a')
          document.body.appendChild(a) // 此处增加了将创建的添加到body当中
          a.href = url
          a.download = fileName
          a.target = '_blank'
          a.click()
          a.remove() // 将a标签移除
        }
      }, error => {
        const $self = this
        const reader = new FileReader()
        reader.onload = function (event) {
          const responseText = reader.result
          const exception = JSON.parse(responseText)
          if (exception.message) {
            $self.$message.error(exception.message)
          } else {
            console.error(error)
          }
        }
        reader.readAsText(error.response.data)
      })
    }
  },
  computed: {
    getLicense () {
      return function (data) {
        return `${data.host}:${data.port}`
      }
    }
  },
  mounted () {
    this.licenseGetData()
    this.licenseGetStatus()
  }
}
</script>
