<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 { productListNameMapping } from '../../utils/mapping'

const { proxy } = getCurrentInstance()
const currentPage = ref(1)
const size = ref(5)
const productId = ref('')
const teamId = ref('')
const status = ref('')
const queryString = ref('')
const total = ref(0)
const linceseId = ref('')
const licenseStatus = ref('')
const tableData = ref([])
const productList = ref([])
const teamList = ref([])
const dialogVisible = ref(false)
const cancelEmail = ref('')
const toggleKey = ref(0)
const showFiled = ref(['Product', 'User Name', 'Email', 'Team', 'License Code', 'Status', 'Remaining Activatable Devices', 'Number of Activated Devices', 'Action'])
const fieldSelect = ref(['Product', 'User Name', 'Email', 'Team', 'License Code', 'Status', 'Remaining Activatable Devices', 'Number of Activated Devices', 'Action'])
const fieldOptions = ref([{
        value: 'Product',
        label: 'Product'
      }, {
        value: 'User Name',
        label: 'User Name'
      }, {
        value: 'Email',
        label: 'Email'
      }, {
        value: 'Team',
        label: 'Team'
      }, {
        value: 'License Code',
        label: 'License Code'
      }, {
        value: 'Status',
        label: 'Status'
      }, {
        value: 'Operated Date',
        label: 'Operated Date'
      }, {
        value: 'Expiration Data',
        label: 'Expiration Data'
      }, {
        value: 'Action',
        label: 'Action'
      }, {
        value: 'Remaining Activatable Devices',
        label: 'Remaining Activatable Devices'
      }, {
        value: 'Number of Activated Devices',
        label: 'Number of Activated Devices'
      }])
const downloadLoading = ref(false)
onMounted(() => {
  let pageText = document.getElementsByClassName('el-pagination__jump')[0]
  if (pageText) {
    pageText.childNodes[0].nodeValue = 'Jump to Page'
  }
  pagingQuery()
  getproductList()
  getTeamList()
})
const pagingQuery = (val) => {
  //初始化表格
  tableData.value = []
  get(
    '/pdf-tech/vppLicenseCode/page?page=' +
      currentPage.value +
      '&' +
      'pageSize=' +
      size.value +
      '&' +
      'productId=' +
      productId.value +
      '&' +
      'teamId=' +
      teamId.value +
      '&' +
      'status=' +
      status.value +
      '&' +
      'queryString=' +
      queryString.value
  ).then((res) => {
    const data = res.data.result.list
    for (let i = 0; i < data.length; i++) {
      if (data[i].validFlag === 0) {
        data[i].validFlag = 'Deleted'
      } else if (data[i].validFlag === 1) {
        data[i].validFlag = 'Unassigned'
      } else if (data[i].validFlag === 2) {
        data[i].validFlag = 'Assigned'
      } else if (data[i].validFlag === 3) {
        data[i].validFlag = 'Activated'
      } else if (data[i].validFlag === 5) {
        data[i].validFlag = 'Expired'
      } else if (data[i].validFlag === 8) {
        data[i].validFlag = 'Partially activated'
      } else {
        data[i].validFlag = 'Canceled'
        // data[i].endDate = ''
      }
    }
    tableData.value = productListNameMapping(data)
    total.value = res.data.result.total
  })
}
//获取已购买产品
const getproductList = (val) => {
  get('/pdf-tech/product/listWithAdmin').then(
    (res) => {
      productList.value = productListNameMapping(res.data.result)
    }
  )
}
// 修改列表展示字段
const changeTableField = () => {
  toggleKey.value++
  showFiled.value = fieldSelect.value.concat()
}
const removeTag = (val) => {
  if (val === 'all') {
    fieldSelect.value = []
  }
}
const changeSelectField = (val) => {
  if (!val.includes('all') && val.length === fieldOptions.value.length) {
    fieldSelect.value.unshift('all')
  } else if (val.includes('all') && (val.length - 1) < fieldOptions.value.length) {
    fieldSelect.value = fieldSelect.value.filter((item) => {
      return item !== 'all'
    })
  }
}
// 列表展示字段 - 全选功能
const selectAllField = () => {
  if (fieldSelect.value.length < fieldOptions.value.length) {
    fieldSelect.value = []
    fieldOptions.value.map((item) => {
      fieldSelect.value.push(item.value)
    })
    fieldSelect.value.unshift('all')
  } else {
    fieldSelect.value = []
  }
}
// 获取团队管理列表
const getTeamList = (val) => {
  // get('/pdf-tech/vppTeam/getManageTeamList', {
  //   teamId: '',
  //   keyword: ''
  // }).then((res) => {
  //   if (res.data.code === 200) {
  //     teamList.value = res.data.result.list
  //   }
  // })
  //获取团队列表
  get('/pdf-tech/vppTeam/listWithAdmin').then((res) => {
    if (res.data.code === 200) {
      teamList.value = res.data.result
    }
  })
}
//打开对话框
const handleClick = (val) => {
  dialogVisible.value = true
  cancelEmail.value = val.email
  linceseId.value = val.id
  licenseStatus.value = val.validFlag
}
//导出序列码
const download = () => {
  if (downloadLoading.value) return
  downloadLoading.value = true
  var urlencoded = new URLSearchParams()
  urlencoded.append("queryString", queryString.value)
  urlencoded.append("productId", productId.value)
  urlencoded.append("teamId", teamId.value)
  urlencoded.append("status", status.value)
  downLoad('/pdf-tech/vppLicenseCode/download',urlencoded).then(
    (res) => {
      setTimeout(() => {
        downloadLoading.value = 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', `License Information.xlsx`)
      document.body.appendChild(a)
      // 下载文件
      a.click()
      // 释放内存
      url = window.URL.revokeObjectURL(url)
      document.body.removeChild(a) 
    }
  )
}
//取消授权序列码
const cancelAssign = () => {
  if (downloadLoading.value) return
  downloadLoading.value = true
  if (licenseStatus.value === 'Assigned' || licenseStatus.value === 'Activated' || licenseStatus.value === 'Partially activated') {
    var urlencoded = new URLSearchParams()
    urlencoded.append('licenceId', linceseId.value)
    post(
      '/pdf-tech/vppLicenseCode/cancelLicenceAssign',
      urlencoded
    ).then((res) => {
      setTimeout(() => {
        downloadLoading.value = false
      }, 2000)
      if (res.data.code === 200) {
        pagingQuery()
        dialogVisible.value = false
        proxy.$message({
          duration: 5000,
          message: 'Cancel 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()
}
</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 class="flex">
          <el-tooltip
          class="item"
          effect="dark"
          content="Export Data (.xlsx)"
          placement="bottom"
        >
          <span
            @click="download()"
            class="
              flex
              justify-center
              items-center
              rounded-4px
              min-w-28px min-h-28px
              bg-[#fff]
              cursor-pointer
            "
          >
            <Download />
          </span>
          </el-tooltip>
          <router-link
            to="/assign-license"
            class="
              bg-[#1460F3]
              h-28px
              w-111px
              flex
              justify-center
              items-center
              font-500
              text-14px
              ml-12px
              rounded-4px
              text-[#fff]
              hover:opacity-80
            "
          >
            Assign License
          </router-link>
          <router-link
            to="/batch-cancel-license"
            class="
              bg-[#1460F3]
              h-28px
              w-111px
              flex
              justify-center
              items-center
              font-500
              text-14px
              ml-12px
              rounded-4px
              text-[#fff]
              hover:opacity-80
            "
          >
            Batch Remove
          </router-link>
        </div>
      </div>
      <div class="w-full bg-[#fff] rounded-t-8px pt-32px px-24px">
        <span>Header Display Fields</span>
        <el-select v-model="fieldSelect" @change='changeSelectField' @remove-tag='removeTag' multiple placeholder="Please select" class="w-600px mx-20px">
          <el-option v-if="fieldOptions.length" value="all" label="all" @click.native='selectAllField'></el-option>
          <el-option
            v-for="item in fieldOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" @click="changeTableField">Confirm</el-button>
      </div>
      <div class="flex bg-[#fff] pt-32px px-24px w-full" :class="fieldSelect ? 'p-20px rounded-b-8px' : ''">
        <select class="w-140px" 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="2">Assigned</option>
          <option value="3">Activated</option>
          <option value="4">Canceled</option>
          <option value="1">Unassigned</option>
          <option value="5">Expired</option>
          <option value="8">Partially activated</option>
        </select>
        <select class="w-140px ml-16px" v-model="teamId" :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 / 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" :key="toggleKey">
        <el-table-column v-if="showFiled.includes('Product')" prop="productName" label="Product"> </el-table-column>
        <el-table-column v-if="showFiled.includes('User Name')" prop="userName" label="User Name" label-class-name="wordBreak"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Email')" prop="email" label="Email"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Team')" prop="teamName" label="Team"> </el-table-column>
        <el-table-column v-if="showFiled.includes('License Code')" prop="cdkey" label="License Code" label-class-name="wordBreak"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Status')" prop="validFlag" label="Status"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Operated Date')" prop="updatedAt" label="Operated Date" label-class-name="wordBreak"></el-table-column>
        <el-table-column v-if="showFiled.includes('Expiration Data')" prop="endDate" label="Expiration Data" label-class-name="wordBreak"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Remaining Activatable Devices')" prop="availableDevices" label="Remaining Activatable Devices" label-class-name="wordBreak"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Number of Activated Devices')" prop="activatedDevices" label="Number of Activated Devices" label-class-name="wordBreak"> </el-table-column>
        <el-table-column v-if="showFiled.includes('Action')" prop="operate" label="Action" min-width="120">
          <p slot="label">Action<Down /></p>
          <template slot-scope="scope">
            <button
              v-if="scope.row.validFlag === 'Assigned' || scope.row.validFlag === 'Activated' || scope.row.validFlag === 'Partially activated'"
              @click="handleClick(scope.row)"
              type="text"
              class="
                w-70px
                h-20px
                rounded-4px
                border-1px border-[#1460F3]
                text-[#1460F3]
                leading-12px
              "
            >
              Remove
            </button>
            <el-dialog :visible.sync="dialogVisible" width="376px" top="30vh" center :show-close="false">
              <Warning />
              <p class="mt-16px">Sure to remove license?</p>
              <p>
                The member will no onger be able to activate PDF Reader Pro with the license.
              </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()">
                  Remove
                </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>

