<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
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 { userStore } from '@/store/userInfo'
import { productListNameMapping } from '../../../utils/mapping'

const { proxy } = getCurrentInstance()
const currentPage = ref(1)
const size = ref(5)
const productId = ref('')
const status = ref('')
const queryString = ref('')
const total = ref(0)
const licenseCodeId = ref('')
const licenseStatus = ref('')
const tableData = ref([])
const productList = ref([])
const dialogVisible = ref(false)
const cancelLicense = ref('')
const downloadLoading = ref(false)
onMounted(() => {
  let pageText = document.getElementsByClassName('el-pagination__jump')[0]
  if (pageText) {
    pageText.childNodes[0].nodeValue = 'Jump to Page'
  }
  pagingQuery()
  getProductList()
  updateUserInfo()
})
const pagingQuery = (val) => {
  //初始化表格
  tableData.value = []
  get(
    '/pdf-tech/vppLicenseCode/pageForReseller?page=' +
      currentPage.value +
      '&' +
      'pageSize=' +
      size.value +
      '&' +
      'productId=' +
      productId.value +
      '&' +
      'status=' +
      status.value +
      '&' +
      'queryString=' +
      queryString.value
  ).then((res) => {
    const data = res.data.result.list
    for (let i = 0; i < data.length; i++) {
      // 3-Activated,6-Refunded,7-Unactive
      if (data[i].validFlag === 3) {
        data[i].validFlag = 'Activated'
      } else if (data[i].validFlag === 6) {
        data[i].validFlag = 'Refunded'
      } else if (data[i].validFlag === 7) {
        data[i].validFlag = 'Unactive'
      }
      if (data[i].productCode === 'com.brother.pdfreaderpro.mac.product_1') {
        data[i].productName = 'PDF Reader Pro Mac Premium'
      } else if (data[i].productCode === 'com.brother.pdfreaderpro.windows.product_1'){
        data[i].productName = 'PDF Reader Pro Win Premium'
      }
    }

    tableData.value = productListNameMapping(data)
    total.value = res.data.result.total
  })
}
//获取已购买产品
const getProductList = (val) => {
  get('/pdf-tech/product/listWithAll').then(
    (res) => {
      const data = res.data.result
      for (let i = 0; i < data.length; i++) {
        if (data[i].code === 'com.brother.pdfreaderpro.mac.product_1') {
          data[i].name = 'PDF Reader Pro Mac Premium'
        } else if (data[i].code === 'com.brother.pdfreaderpro.windows.product_1'){
          data[i].name = 'PDF Reader Pro Win Premium'
        }
      }
      productList.value = productListNameMapping(res.data.result)
    }
  )
}

//打开对话框
const handleClick = (val) => {
  dialogVisible.value = true
  cancelLicense.value = val.cdkey
  licenseCodeId.value = val.id
  licenseStatus.value = val.validFlag
}
//取消授权序列码
const cancelAssign = () => {
  if (downloadLoading.value) return
  downloadLoading.value = true
  if (licenseStatus.value === 'Unactive' || licenseStatus.value === 'Activated') {
    var urlencoded = new URLSearchParams()
    urlencoded.append('licenseCodeId', licenseCodeId.value)
    post(
      '/pdf-tech/vppLicenseCode/disable',
      urlencoded
    ).then((res) => {
      setTimeout(() => {
        downloadLoading.value = false
      }, 2000)
      if (res.data.code === 200) {
        pagingQuery()
        dialogVisible.value = false
        proxy.$message({
          duration: 5000,
          message: 'Disabled Successfully',
          type: 'success'
        })
      }
    })
  }
}
//切换每页条数
const handleSizeChange = (val) => {
  size.value = val
  currentPage.value = 1
  pagingQuery()
}
//切换分页
const handleCurrentChange = (val) => {
  currentPage.value = val
  pagingQuery()
}
//筛选
const searchInfo = (val) => {
  currentPage.value = 1
  pagingQuery()
}
// 获取用户信息
const updateUserInfo = () => {
  get(
    '/pdf-tech/vppMember/getMemberInfo'
  ).then((res) => {
    if (res.data.code === 200 && res.data.msg == 'success') {
      userStore().setUserInfo(res.data.result)
      if(res.data.result.validFlag === '0'){
        proxy.$router.push('/login')
      }
    }
  })
}
</script>

<template>
  <div class="flex flex-col items-center">
    <div class="w-full">
      <h1 class="leading-40px">Manage License</h1>
      <div
        class="
          mt-36px
          mb-16px
          leading-20px
          text-16px
          font-bold
          flex
          justify-between
        "
      >
        <span>Content</span>
      </div>
      <div class="flex bg-[#fff] pt-32px px-24px rounded-t-8px w-full">
        <select class="w-230px" v-model="productId" :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 class="w-140px ml-16px" v-model="status" :class="{ '!text-[#232A40]': status !== '' }">
          <option value="" selected>Status</option>
          <option value="7">Unactive</option>
          <option value="3">Activated</option>
          <option value="6">Refunded</option>
        </select>
        <div class="relative">
          <el-input
            v-model="queryString"
            size="mini"
            class="!w-316px ml-16px input-with-select"
            placeholder="License Code"
          >
          </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="cdkey" label="License Code" label-class-name="wordBreak"> </el-table-column>
        <el-table-column prop="validFlag" label="Status"> </el-table-column>
        <el-table-column prop="operate" label="Action">
          <template slot-scope="scope">
            <button
              v-if="scope.row.validFlag === 'Unactive' || scope.row.validFlag === 'Activated'"
              @click="handleClick(scope.row)"
              type="text"
              class="
                w-70px
                h-20px
                rounded-4px
                border-1px border-[#1460F3]
                text-[#1460F3]
                leading-12px
              "
            >
              Ban
            </button>
            <el-dialog :visible.sync="dialogVisible" width="376px" top="30vh" center :show-close="false">
              <Warning />
              <p class="mt-16px">Sure to ban this license code?</p>
              <p>
                License Code：<span class="text-16px font-bold">{{
                  cancelLicense
                }}</span>
              </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="cancelAssign()">
                  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>
.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: 20px !important;
  padding-left: 20px !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>

<style lang="scss">
::v-deep .input-with-select .el-input__inner::placeholder {
  font-size: 14px;
  font-weight: 400;
  color: #808185;
}
</style>

