<script>
import Download from '@/components/icon/download.vue'
import Warning from '@/components/icon/warning.vue'
import Search from '@/components/icon/search.vue'
import { get, post, downLoad } from '../../utils/request'
import { productListNameMapping } from '../../utils/mapping'

export default {
  components: {
    Download,
    Warning,
    Search
  },
  data() {
    return {
      currentPage: 1,
      size: 5,
      search: '',
      productId: '',
      teamId: '',
      status: '',
      deviceStatus: '',
      queryString: '',
      tableData: [],
      total: 0,
      teamList: [],
      productList: [],
      dialogVisible: false,
      deviceId: '',
      cancelEmail: '',
      cancelUniqueSn: '',
      downloadLoading: false
    }
  },
  mounted() {
    let pageText = document.getElementsByClassName('el-pagination__jump')[0]
    if (pageText) {
      pageText.childNodes[0].nodeValue = 'Jump to Page'
    }
    this.pagingQuery()
    this.getproductList()
    this.getTeamList()
  },
  methods: {
    //分页查询
    pagingQuery() {
      get(
        '/pdf-tech/vppDevice/page?page=' +
        this.currentPage +
        '&' +
        'pageSize=' +
        this.size +
        '&' +
        'productId=' +
        this.productId +
        '&' +
        'teamId=' +
        this.teamId +
        '&' +
        'status=' +
        this.status +
        '&' +
        'queryString=' +
        this.queryString
      ).then((res) => {
        if (res.data.code === 200) {
          const data = res.data.result?.list
          for (let i = 0; i < data.length; i++) {
            if (data[i].status === 0) {
              data[i].status = 'Canceled'
              data[i].expireDate = ''
            } else if (data[i].status === 1) {
              data[i].status = 'Activated'
            } else if (data[i].status === 4) {
              data[i].status = 'Expired'
            } else {
              data[i].status = ''
            }
          }
          this.tableData = productListNameMapping(data)
          this.total = res.data.result.total
        }
      })
    },
    // 获取团队管理列表
    getTeamList() {
      // get('/pdf-tech/vppTeam/getManageTeamList', {
      //   teamId: '',
      //   keyword: ''
      // }).then((res) => {
      //   if (res.data.code === 200) {
      //     this.teamList = res.data.result.list
      //   }
      // })
      get('/pdf-tech/vppTeam/listWithAdmin').then((res) => {
        if (res.data.code === 200) {
          this.teamList = res.data.result
        }
      })
    },
    //获取已购买产品
    getproductList() {
      get('/pdf-tech/product/listWithAdmin').then(
        (res) => {
          this.productList = productListNameMapping(res.data.result)
        }
      )
    },
    //取消设备授权
    cancelAuthorization() {
      if (this.downloadLoading) return
      this.downloadLoading = true
      setTimeout(() => {
        this.downloadLoading = false
      }, 2000)
      var urlencoded = new URLSearchParams()
      urlencoded.append('deviceId', this.deviceId)
      post(
        '/pdf-tech/vppDevice/cancel',
        urlencoded
      ).then((res) => {
        if (res.data.code === 200 && res.data.msg == ' Canceled！') {
          this.dialogVisible = false
          this.$message({
            duration: 5000,
            message: 'Canceled Successfully',
            type: 'success'
          })
          this.pagingQuery()
        } else {
          this.$message({
            duration: 5000,
            message: 'Canceled Failed',
            type: 'error'
          })
        }
      })

    },
    //打开对话框
    handleClick(val) {
      // if (this.deviceStatus === 'Activated'){
      this.dialogVisible = true
      this.cancelEmail = val.email
      this.cancelUniqueSn = val.uniqueSn
      this.deviceId = val.id
      this.deviceStatus = val.status
      // }
    },
    handleSizeChange(value) {
      this.size = value
      this.currentPage = 1
      this.pagingQuery()
    },
    handleCurrentChange(value) {
      this.currentPage = value
      this.pagingQuery()
    },
    searchInfo() {
      this.currentPage = 1
      this.pagingQuery()
    },
    // 下载设备文件
    downLoad() {
      if (this.downloadLoading) return
      this.downloadLoading = true
      var urlencoded = new URLSearchParams()
      urlencoded.append("queryString", this.queryString)
      urlencoded.append("productId", this.productId)
      urlencoded.append("teamId", this.teamId)
      urlencoded.append("status", this.status)
      downLoad("/pdf-tech/vppDevice/download", urlencoded).then((res) => {
        setTimeout(() => {
          this.downloadLoading = false
        }, 2000)
        let url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
        let a = document.createElement('a')
        a.style.display = 'none'
        a.href = url
        // 自定义文件名
        a.setAttribute('download', `Device Information.xlsx`)
        document.body.appendChild(a)
        // 下载文件
        a.click()
        // 释放内存
        url = window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<template>
  <div class="flex flex-col items-center">
    <div class="w-full">
      <h1 class="leading-40px">Device Management</h1>
      <div class="
          mt-36px
          mb-16px
          leading-20px
          text-16px
          font-bold
          flex
          justify-between
        ">
        <span>Content</span>
        <el-tooltip class="item" effect="dark" content="Export Data (.xlsx)" placement="bottom">
          <span class="
            flex
            justify-center
            items-center
            rounded-4px
            min-w-28px min-h-28px
            bg-[#fff]
            cursor-pointer
          " @click="downLoad">
            <Download />
          </span>
        </el-tooltip>
      </div>
      <div class="flex bg-[#fff] pt-32px px-24px rounded-t-8px w-full">
        <select v-model="productId" class="w-140px" :class="{ '!text-[#232A40]': productId !== '' }">
          <option value="" selected>Product</option>
          <option v-for="item in productList" :key="item.value" :value="item.id">
            {{ item.name }}
          </option>
        </select>
        <select v-model="status" class="w-140px ml-16px" :class="{ '!text-[#232A40]': status !== '' }">
          <option value="" selected>Status</option>
          <!-- <option value="0" selected>Unactivated</option> -->
          <option value="1" selected>Ativated</option>
          <option value="0" selected>Canceled</option>
          <option value="4" selected>Expired</option>
        </select>
        <select v-model="teamId" class="w-140px ml-16px" :class="{ '!text-[#232A40]': teamId !== '' }">
          <option value="" selected>Team</option>
          <option v-for="item in teamList" :key="item.value" :value="item.id">
            {{ item.name }}
          </option>
        </select>
        <div class="relative">
          <el-input v-model="queryString" size="mini" class="!w-316px ml-16px input-with-select"
            placeholder="Search User Name / Email / UUID">
          </el-input>
          <button class="absolute top-8px right-8px" @click="searchInfo()">
            <Search />
          </button>
        </div>
        <button type="button" @click="searchInfo()" class="
            w-70px
            h-28px
            border-1px border-[#1460F3]
            rounded-4px
            ml-16px
            text-[#1460F3]
            hover:opacity-80
          ">
          Confirm
        </button>
      </div>
      <el-table :data="tableData" class="px-24px rounded-b-8px !w-full">
        <el-table-column prop="productName" label="Product"> </el-table-column>
        <el-table-column prop="memberName" label="User Name" label-class-name="wordBreak"> </el-table-column>
        <el-table-column prop="email" label="Email">
        </el-table-column>
        <el-table-column prop="teamName" label="Team"> </el-table-column>
        <el-table-column prop="uniqueSn" label="UUID"> </el-table-column>
        <el-table-column prop="status" label="Status"> </el-table-column>
        <el-table-column prop="activeDate" label="Activated Date" label-class-name="wordBreak">
        </el-table-column>
        <el-table-column prop="expireDate" label="Expiration Data" label-class-name="wordBreak">
        </el-table-column>
        <el-table-column prop="canceledDate" label="Canceled Date" label-class-name="wordBreak">
        </el-table-column>
        <el-table-column prop="operate" label="Action" align="left" min-width="110">
          <template slot-scope="scope">
            <button v-show="scope.row.status === 'Activated'" @click="handleClick(scope.row)" type="text" class="
                w-60px
                h-20px
                rounded-4px
                border-1px border-[#1460F3]
                text-[#1460F3]
                leading-12px
              ">
              Unbind
            </button>
            <el-dialog :visible.sync="dialogVisible" width="376px" top="30vh" center :show-close="false">
              <Warning />
              <span class="mt-16px">Sure to unbind the license?</span>
              <p>
                The member can activate the license on a new device after unbinding.
              </p>
              <div class="el-dialog__footer_div flex w-full justify-between">
                <el-button @click="dialogVisible = false">No</el-button>
                <el-button type="primary" @click="cancelAuthorization()">
                  Yes
                </el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>
        <p slot="empty">No Data Available</p>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[5, 10, 20]" :page-size="size" :background="true"
        layout="prev, pager, next, sizes, jumper" :total="total"
        class="px-24px !rounded-0 rounded-b-8px mt-20px flex justify-end">
      </el-pagination>
    </div>
  </div>
</template>

<style lang="scss" scoped>
select option:checked {
  color: #000 !important;
}

.el-table__header-wrapper::v-deep .el-table__header {
  display: flex;
  width: 1100px !important;
}

.el-table__header {
  display: flex;
  width: 1100px !important;
}

.el-table::v-deep .el-table__cell {
  padding-right: 10px !important;
  padding-left: 10px !important;
}

.el-table::v-deep thead {
  color: #000 !important;
}

::v-deep .input-with-select .el-input__inner {
  padding: 0 20px 0 8px;
  border-color: #d9d9d9;
  font-size: 14px;
  color: #232A40;
}

::v-deep .input-with-select .el-input__inner::placeholder {
  font-size: 14px;
  font-weight: 400;
  color: #808185;
}

.el-table::v-deep .el-table__cell .wordBreak {
  word-break: normal !important;
}

.el-table::v-deep .cell {
  word-break: break-word;
}
</style>
