<template>
  <view class="page">
    <view class="nav">
      <view class="n" :class="{ on: tab === 0 }" @click="tab = 0">卡密模式</view>
      <view class="n" :class="{ on: tab === 1 }" @click="tab = 1">机器码模式</view>
    </view>

    <text class="notice">{{ notice }}</text>

    <!-- 卡密 -->
    <scroll-view v-show="tab === 0" scroll-y class="scroll">
      <view class="card">
        <input v-model="c.id" class="inp" placeholder="卡串" />
        <input v-model="c.pwd" class="inp" password placeholder="卡密码（可选）" />
        <button class="btn" @click="verifyCard">验证卡密</button>
        <button class="btn sec" @click="testNet">网络测试</button>
        <button class="btn sec" @click="checkVer">检查版本</button>
        <button class="btn sec" @click="openRenew(c.id)">在线充值（网页）</button>
        <button class="btn sec" @click="openGen">购买生成卡</button>
        <button class="btn sec" @click="openStock">购买库存卡</button>
        <text class="st">{{ status }}</text>
      </view>
    </scroll-view>

    <!-- 机器码 -->
    <scroll-view v-show="tab === 1" scroll-y class="scroll">
      <view class="sub">
        <view class="s" :class="{ on: msub === 0 }" @click="switchM(0)">验证账号</view>
        <view class="s" :class="{ on: msub === 1 }" @click="switchM(1)">卡密充值</view>
      </view>

      <view v-show="msub === 0" class="card">
        <input v-model="m.id" class="inp" placeholder="机器码（账号）" />
        <button class="btn" @click="verifyMachine">验证机器码账号</button>
        <button class="btn sec" @click="testNetM">网络测试</button>
        <button class="btn sec" @click="checkVerM">检查版本</button>
        <button class="btn sec" @click="openRenew(m.id)">在线充值（网页）</button>
        <button class="btn sec" @click="openGen">购买生成卡</button>
        <button class="btn sec" @click="openStock">购买库存卡</button>
        <text class="st">{{ status }}</text>
      </view>

      <view v-show="msub === 1" class="card">
        <input v-model="mr.id" class="inp" placeholder="机器码（账号）" />
        <input v-model="mr.ka" class="inp" placeholder="充值卡号" />
        <input v-model="mr.pwd" class="inp" password placeholder="卡密码（可选）" />
        <button class="btn" @click="activate">激活充值</button>
        <button class="btn sec" @click="openRenew(mr.id)">在线充值（网页）</button>
        <button class="btn sec" @click="openGen">购买生成卡</button>
        <button class="btn sec" @click="openStock">购买库存卡</button>
        <text class="st">{{ status }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getCardClient } from '@/utils/cardSingleton.js'
import { CARD_CFG } from '@/utils/cardConfig.js'
import { renewUrlForUser } from '@/utils/cardConfig.js'
import { cardResult } from '@/utils/bsphp.js'
import { openExternal } from '@/utils/openUrl.js'

export default {
  data() {
    return {
      tab: 0,
      msub: 0,
      notice: '加载公告…',
      status: '',
      c: { id: '', pwd: '' },
      m: { id: '' },
      mr: { id: '', ka: '', pwd: '' }
    }
  },
  onLoad() {
    this.bootstrap()
  },
  onShow() {
    const app = getApp()
    if (app && app.globalData && app.globalData.noticeMessage) {
      this.notice = app.globalData.noticeMessage
    }
  },
  methods: {
    switchM(i) {
      this.msub = i
      if (i === 0) {
        this.m.id = this.mr.id
      } else {
        this.mr.id = this.m.id
      }
      this.status = ''
    },
    async bootstrap() {
      const cli = getCardClient()
      try {
        await cli.bootstrap()
        const n = await cli.getNotice()
        const msg = cardResult(n, '').message || '暂无公告'
        this.notice = msg
        const app = getApp()
        if (!app.globalData) app.globalData = {}
        app.globalData.noticeMessage = msg
      } catch (e) {
        this.notice = '初始化失败'
      }
      const mc = getCardClient().machineCode()
      this.m.id = mc
      this.mr.id = mc
    },
    openRenew(user) {
      openExternal(renewUrlForUser(CARD_CFG.renewUrlBase, user))
    },
    openGen() {
      openExternal(CARD_CFG.genUrl)
    },
    openStock() {
      openExternal(CARD_CFG.stockUrl)
    },
    async verifyCard() {
      const id = this.c.id.trim()
      if (!id) {
        this.status = '请输入卡串'
        return
      }
      const cli = getCardClient()
      try {
        const r = await cli.loginIC(id, this.c.pwd, null, null)
        let msg = cardResult(r, '').message
        if (!msg) msg = '验证失败'
        const ok = r.code === 1081 || (msg && msg.indexOf('1081') >= 0)
        if (!ok) {
          this.status = msg
          return
        }
        const exp = await cli.getDateIC()
        let expDisplay = cardResult(exp, '').message || '-'
        this.status = '验证成功，已打开主控制面板'
        uni.navigateTo({
          url:
            '/pages/control/control?cardId=' +
            encodeURIComponent(id) +
            '&vip=' +
            encodeURIComponent(expDisplay)
        })
      } catch (e) {
        this.status = String(e.message || e)
      }
    },
    async testNet() {
      try {
        const ok = await getCardClient().connect()
        this.status = ok ? '网络连接正常' : '网络连接异常'
      } catch (e) {
        this.status = '网络连接异常'
      }
    },
    async checkVer() {
      try {
        const r = await getCardClient().getVersion()
        let v = cardResult(r, '').message
        this.status = v ? '当前版本：' + v : '版本获取失败'
      } catch (e) {
        this.status = '版本获取失败'
      }
    },
    async verifyMachine() {
      const id = this.m.id.trim()
      if (!id) {
        this.status = '【机器码】请输入机器码（账号）'
        return
      }
      const cli = getCardClient()
      const globalUUID = cli.machineCode()
      try {
        const feat = await cli.addCardFeatures(id, globalUUID, globalUUID)
        let featMsg = cardResult(feat, '').message
        if (!featMsg) featMsg = '（无 data）'
        this.status = '[AddCardFeatures.key.ic] code=' + feat.code + ' ' + featMsg
        const featOk =
          feat.code === 1011 ||
          feat.code === 1081 ||
          (featMsg && (featMsg.indexOf('1081') >= 0 || featMsg.indexOf('成功') >= 0))
        if (!featOk) return
        const r = await cli.loginIC(id, '', globalUUID, globalUUID)
        let msg = cardResult(r, '').message
        if (!msg) msg = '验证失败'
        this.status = '[login.ic] ' + msg
        const ok = r.code === 1081 || (msg && msg.indexOf('1081') >= 0)
        if (!ok) return
        const exp = await cli.getDateIC()
        let expDisplay = cardResult(exp, '').message || '-'
        this.status = '验证成功（机器码账号），已打开主控制面板'
        uni.navigateTo({
          url:
            '/pages/control/control?cardId=' +
            encodeURIComponent(id) +
            '&vip=' +
            encodeURIComponent(expDisplay)
        })
      } catch (e) {
        this.status = String(e.message || e)
      }
    },
    testNetM() {
      this.testNet()
    },
    checkVerM() {
      this.checkVer()
    },
    async activate() {
      const icid = this.mr.id.trim()
      if (!icid) {
        this.status = '【机器码】请输入机器码（账号）'
        return
      }
      const ka = this.mr.ka.trim()
      if (!ka) {
        this.status = '请输入充值卡号'
        return
      }
      try {
        const r = await getCardClient().rechargeCard(icid, ka, this.mr.pwd)
        let msg = cardResult(r, '').message
        if (!msg) msg = '（无 data）'
        this.status = '[chong.ic] code=' + r.code + ' ' + msg
      } catch (e) {
        this.status = String(e.message || e)
      }
    }
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(165deg, var(--theme-grad-a), var(--theme-grad-b));
  padding: 20rpx;
  box-sizing: border-box;
}
.nav {
  display: flex;
  border-radius: 12rpx;
  overflow: hidden;
  margin-bottom: 16rpx;
  background: rgba(255, 255, 255, 0.25);
}
.n {
  flex: 1;
  text-align: center;
  padding: 22rpx 0;
  color: #fff;
  font-size: 28rpx;
}
.n.on {
  background: rgba(255, 255, 255, 0.95);
  color: var(--theme-primary);
  font-weight: 600;
}
.notice {
  display: block;
  color: #fff;
  font-size: 26rpx;
  margin-bottom: 16rpx;
  padding: 16rpx;
  background: rgba(0, 0, 0, 0.15);
  border-radius: 12rpx;
}
.scroll {
  max-height: calc(100vh - 220rpx);
}
.sub {
  display: flex;
  gap: 12rpx;
  margin-bottom: 16rpx;
}
.s {
  flex: 1;
  text-align: center;
  padding: 14rpx;
  border-radius: 999rpx;
  background: rgba(255, 255, 255, 0.35);
  color: #fff;
  font-size: 24rpx;
}
.s.on {
  background: #fff;
  color: var(--theme-primary);
}
.card {
  background: rgba(255, 255, 255, 0.94);
  border-radius: 16rpx;
  padding: 24rpx;
}
.inp {
  border: 1px solid #e0e0e0;
  border-radius: 10rpx;
  padding: 18rpx;
  margin-bottom: 16rpx;
  font-size: 28rpx;
}
.btn {
  margin-bottom: 14rpx;
  background: var(--theme-primary);
  color: #fff;
  font-size: 28rpx;
}
.btn.sec {
  background: #fff;
  color: var(--theme-primary);
  border: 1px solid var(--theme-primary);
}
.st {
  display: block;
  margin-top: 16rpx;
  font-size: 26rpx;
  color: #333;
  white-space: pre-wrap;
}
</style>
