<script setup>
import { onMounted, ref, getCurrentInstance, computed, watch } from 'vue'
import Shopping from '@/components/icon/shopping.vue'
import { get, postWithHeader } from '../../../utils/request'
import { userStore } from '@/store/userInfo'
const { proxy } = getCurrentInstance()

const memberRole = ref('')
const companyId = ref('')
const baseUrl = import.meta.env.VITE_STORE_DOMIN

onMounted(() => {
  updataUserInfo()
  memberRole.value = userStore().user.role
  companyId.value = userStore().user.companyId
  isOwnTry()
  const userAgent = navigator.userAgent
  const isWindows = /Windows/.test(userAgent)
  if (isWindows) {
    techPlatform.value = 'Windows'
    proPlatform.value = 'Windows'
  }
  getOverview()
})

// 获取用户信息
const updataUserInfo = () => {
  get(
    '/pdf-tech/vppMember/getMemberInfo'
  ).then((res) => {
    if (res.data.code === 200 && res.data.msg == 'success') {
      userStore().setUserInfo(res.data.result)
    }
  })
}

// 判断是否有试用权限
const showTry = ref(false)
const dialogVisible = ref(false)
const isOwnTry = () => {
  get(
    baseUrl + '/api/member/already-tried?company_id=' + companyId.value
  ).then((res) => {
    if (res.data.code === 200) {
      showTry.value = !res.data.tried
    }
  })
}
const freeTry = () => {
  const data = JSON.stringify({
    company_id: companyId.value
  })
  postWithHeader(baseUrl + '/api/vpp_members/trialByCompany', data).then(res => {
    dialogVisible.value = false
    if (res.data.code !== 200) {
      proxy.$message.error({
        duration: 5000,
        message: res.data.message
      })
    } else {
      proxy.$message({
        duration: 5000,
        message: 'Trial Successfully',
        type: 'success'
      })
      window.location.href = '/product'
      isOwnTry()
    }
  })
}

const techPlatform = ref('Mac')
const proPlatform = ref('Mac')
const proProduct = ref('Permanent License')

// 购买链接
const proBuyUrl = computed(() => {
  if (proPlatform.value === 'Windows') {
    if (proProduct.value === 'Permanent License') {
      return '/product/4'
    } else {
      return "/product/5"
    }
  } else {
    if (proProduct.value === 'Permanent License') {
      return '/product/2'
    } else {
      return "/product/3"
    }
  }
})

// 产品
const tableData = ref([])
const isHaveProduct = ref('or')
const codeMap = [
  {
    title: "LynxPDF Editor (Enterprise)",
    code: "com.brother.pdftecheditor",
    url: "/product/0"
  },
  {
    title: "PDF Reader Pro Cross-Platform",
    code: "com.brother.pdfreaderpro.cross.platform.product_3",
    url: "/product/1"
  },
  {
    title: "PDF Reader Pro Permanent for Mac",
    code: "com.brother.pdfreaderpro.mac.product_3",
    url: "/product/2"
  },
  {
    title: "PDF Reader Pro Premium for Mac",
    code: "com.brother.pdfreaderpro.mac.product_1",
    url: "/product/3"
  },
  {
    title: "PDF Reader Pro Permanent for Windows",
    code: "com.brother.pdfreaderpro.windows.product_3",
    url: "/product/4"
  },
  {
    title: "PDF Reader Pro Premium for Windows",
    code: "com.brother.pdfreaderpro.windows.product_1",
    url: "/product/5"
  }
]
// 计算商品信息
const computeList = (productList) => {
  tableData.value = productList.map(product => {
    const match = codeMap.find(item => item.code === product.code)
    if (match) {
      return {
        ...match,
        id: product.id,
        assignedCodeNumber: product.assignedCodeNumber,
        codeNumber: product.codeNumber,
        name: product.name,
      }
    }
    return null
  }).filter(item => item !== null)
}
const getOverview = () => {
  if (proxy.$route.query && proxy.$route.query.type === 'isNoAdmin') {
    isHaveProduct.value = 'no'
    return
  }
  get('/pdf-tech/product/purchasedProductList').then((res) => {
    if (res.data.result.length === 0) {
      isHaveProduct.value = 'no'
      return
    }
    computeList(res.data.result)
    isHaveProduct.value = 'yes'
  })
}
</script>

<template>
  <div class="flex flex-col items-center">
    <div class="w-full">
      <div class="
      mb-32px
      leading-20px
      text-16px
      font-bold
      flex
      justify-between
      ">
        <h1 class="leading-40px">Product</h1>
        <a v-if="memberRole === '1'" href="/product/custom"
          class="flex items-center h-28px px-10px py-4px bg-[#1460F3] rounded-4px text-14px leading-20px font-400 text-[#fff] cursor-pointer hover:opacity-80">
          <Shopping class="mr-8px" />Buy More Products
        </a>
      </div>
      <div v-if="isHaveProduct === 'or'"></div>
      <div v-else-if="isHaveProduct === 'yes'">
        <el-table :data="tableData" class="px-24px pb-40px rounded-b-8px">
          <el-table-column prop="title" label="Product">
            <template slot-scope="scope">
              <div class="flex items-center text-[#232A40]">
                <img v-if="scope.row.code === 'com.brother.pdfreaderpro.cross.platform.product_3'"
                  src="@/assets/images/cross.png" alt="logo" class="h-32px mr-12px">
                <img v-else src="@/assets/images/logo.png" alt="logo" class="h-32px mr-12px">
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="Quantity" label="Quantity" width="360">
            <template slot-scope="scope">
              {{ scope.row.assignedCodeNumber }}/{{ scope.row.codeNumber }}
              <span v-if="scope.row.codeNumber !== 1">Licenses</span>
              <span v-else>License</span>
            </template>
          </el-table-column>
          <el-table-column prop="Purchase" label="Purchase" width="160">
            <template slot-scope="scope">
              <div v-if="memberRole?.indexOf('1') !== -1">
                <a :href="scope.row.url"
                  class="w-89px inline-block text-center h-28px mt-8px rounded-4px border-1px border-[#1460F3] text-[#1460F3] leading-28px hover:bg-[#1460F333]">
                  Buy Now
                </a>
              </div>
            </template>
          </el-table-column>
          <p slot="empty">No Data Available</p>
        </el-table>
      </div>
      <!-- 购买卡片 -->
      <div v-else class="flex mt-24px">
        <div class="card max-w-400px w-[32%]">
          <div class="bg-[#fff] rounded-t-8px p-32px text-center">
            <img class="w-64px m-auto" src="@/assets/images/logo.png" alt="logo">
            <div class="font-bold text-20px leading-24px mt-16px text-[#232A40]">LynxPDF Editor (Enterprise)</div>
            <div class="mt-16px text-14px leading-20px text-[#505258]">Cost-Effective PDF Solution Tailored to Your
              Business</div>
          </div>
          <div class="bg-[#F6F7F9] p-32px rounded-b-8px">
            <div v-if="memberRole === '1'">
              <a href="/product/0"
                class="rounded-8px bg-[#1460F3] flex leading-40px text-[#fff] justify-center font-700 text-16px hover:opacity-80">
                Buy Now</a>
              <a v-if="showTry" @click="dialogVisible = true"
                class="mt-16px cursor-pointer rounded-8px border-1px border-[#1460F3] flex leading-40px text-[#1460F3] justify-center font-700 text-16px hover:opacity-80">
                Apply for Trial</a>
            </div>
            <div v-else class="text-center text-14px leading-20px text-[#808185]">Please contact the super admin to purchase license or apply for trial.</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 试用弹窗 -->
    <el-dialog title="" :visible.sync="dialogVisible" width="376px" top="30vh" center :show-close="false">
      <!-- <Warning /> -->
      <p class="mt-16px">Are you sure to apply for the 14-day free trial of LynxPDF Editor (Enterprise)?</p>
      <p>The License code will be sent to the Admin Console after applying successfully.</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="freeTry">
          Apply
        </el-button>
        <el-button @click="dialogVisible = false">Cancel</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
  line-height: 40px;
  margin-top: 20px;

  .el-input {
    input {
      border: 1px solid #E2E3E5;
      font-size: 16px;
      font-weight: 400;
      line-height: 24px;
      text-align: left;
      color: #101828;
    }

    .el-select__caret {
      color: #404653;
    }
  }
}
::v-deep .el-table {
  border-radius: 8px;
  &::before {
    display: none;
  }
}
</style>

