<template>
  <view class="wrap">
    <view v-if="loading" class="loading">加载中…</view>
    <text class="line">账号名称：{{ account }}</text>
    <text class="line">到期时间：{{ vip }}</text>
    <text class="info">{{ userInfo }}</text>
    <text class="err">{{ err }}</text>

    <view class="fields">
      <button
        v-for="(f, i) in fields"
        :key="i"
        class="fb"
        type="default"
        @click="fetchField(f)"
      >
        {{ f.displayName }} ({{ f.raw }})
      </button>
    </view>

    <view class="perfect">
      <text class="sec">完善资料（至少填一项）</text>
      <input v-model="pq" class="inp" placeholder="QQ" />
      <input v-model="pm" class="inp" placeholder="邮箱" />
      <input v-model="pmb" class="inp" type="number" placeholder="手机" />
      <input v-model="pc" class="inp" placeholder="图片验证码" />
      <button class="go" @click="submitPerfect">提交资料</button>
    </view>

    <button class="out" @click="logout">退出登录</button>
    <button class="doc" type="default" @click="openDoc">开发文档</button>
  </view>
</template>

<script>
import { getMobileApi } from '@/utils/apiSingleton.js'
import { USER_INFO_FIELDS } from '@/utils/userConfig.js'
import { apiDataMessage } from '@/utils/bsphp.js'

export default {
  data() {
    return {
      loading: true,
      account: '-',
      vip: '-',
      userInfo: '-',
      err: '',
      fields: USER_INFO_FIELDS,
      pq: '',
      pm: '',
      pmb: '',
      pc: '',
      fieldBusy: false
    }
  },
  onShow() {
    this.loadProfile(true)
  },
  methods: {
    parseValue(raw) {
      if (raw == null) return ''
      const t = String(raw).trim()
      const parts = t.split('=')
      if (!parts.length) return t
      const v = parts[parts.length - 1].trim()
      return v || t
    },
    async loadProfile(showProgress) {
      const api = getMobileApi()
      if (showProgress) {
        this.loading = true
        this.err = ''
      }
      try {
        const e = await api.ensureReady()
        if (e) {
          this.err = e.message
          this.loading = false
          return
        }
        const nameRes = await api.client.getUserInfo('UserName')
        const nd = api.wrap(nameRes, '')
        let account = '-'
        let err = ''
        if (nd.code != null && nd.code !== 200) {
          err = nd.message
        } else {
          account = this.parseValue(nd.message)
        }

        const vipRes = await api.client.getUserInfo('UserVipDate')
        let vipEnd = this.parseValue(api.wrap(vipRes, '').message)
        if (!vipEnd) {
          const endRes = await api.client.getEndTime()
          vipEnd = this.parseValue(api.wrap(endRes, '').message)
        }
        if (!vipEnd) vipEnd = '-'

        const infoRes = await api.client.getUserInfo()
        const infoMsg = apiDataMessage(infoRes.data)
        let userInfo = infoMsg || '-'
        if (!infoMsg && !err) err = '获取用户信息失败'

        this.account = account
        this.vip = vipEnd
        this.userInfo = userInfo
        this.err = err
      } catch (ex) {
        this.err = String(ex)
      }
      this.loading = false
    },
    async fetchField(f) {
      if (this.fieldBusy) return
      this.fieldBusy = true
      const api = getMobileApi()
      try {
        const r = await api.client.getUserInfo(f.raw)
        const d = api.wrap(r, '')
        const codeStr = d.code != null ? String(d.code) : 'nil'
        const body = d.message || '(空)'
        const msg = 'info: ' + f.raw + '\ncode: ' + codeStr + '\ndata: ' + body
        uni.showModal({ title: f.displayName, content: msg, showCancel: false })
      } catch (e) {
        /* empty */
      }
      this.fieldBusy = false
    },
    async submitPerfect() {
      const api = getMobileApi()
      const params = {}
      if (this.pq.trim()) params.qq = this.pq.trim()
      if (this.pm.trim()) params.mail = this.pm.trim()
      if (this.pmb.trim()) params.mobile = this.pmb.trim()
      if (this.pc.trim()) params.coode = this.pc.trim()
      if (!Object.keys(params).length) {
        this.err = '请至少填写一项资料或验证码'
        return
      }
      const e = await api.ensureReady()
      if (e) {
        this.err = e.message
        return
      }
      const r = await api.client.perfectUserInfo(params)
      const d = api.wrap(r, '')
      if (d.code === 200 || d.code === 1011) {
        this.err = d.message || '提交成功'
        this.loadProfile(false)
      } else {
        this.err = d.message || '提交失败'
      }
    },
    logout() {
      const api = getMobileApi()
      api.client.logout().finally(() => {
        uni.reLaunch({ url: '/pages/auth/auth' })
      })
    },
    openDoc() {
      const u = 'https://www.bsphp.com/chm-38.html'
      // #ifdef H5
      window.open(u)
      return
      // #endif
      // #ifdef APP-PLUS
      plus.runtime.openURL(u)
      return
      // #endif
      uni.setClipboardData({
        data: u,
        success: () => uni.showToast({ title: '链接已复制', icon: 'none' })
      })
    }
  }
}
</script>

<style scoped>
.wrap {
  padding: 24rpx;
  padding-bottom: 80rpx;
}
.loading {
  margin-bottom: 16rpx;
  font-size: 28rpx;
}
.line {
  display: block;
  font-size: 30rpx;
  margin-bottom: 12rpx;
  font-weight: 600;
}
.info {
  display: block;
  font-size: 24rpx;
  color: #555;
  margin: 16rpx 0;
  white-space: pre-wrap;
}
.err {
  display: block;
  color: #c62828;
  font-size: 26rpx;
  margin-bottom: 16rpx;
}
.fields {
  margin: 20rpx 0;
}
.fb {
  width: 100%;
  margin-bottom: 12rpx;
  font-size: 24rpx;
  text-align: left;
}
.perfect {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin: 24rpx 0;
}
.sec {
  font-size: 28rpx;
  font-weight: 600;
  display: block;
  margin-bottom: 16rpx;
}
.inp {
  border: 1px solid #e0e0e0;
  border-radius: 10rpx;
  padding: 16rpx;
  margin-bottom: 12rpx;
  font-size: 28rpx;
}
.go {
  background: var(--theme-primary);
  color: #fff;
  margin-top: 8rpx;
}
.out {
  margin-top: 24rpx;
  background: #c62828;
  color: #fff;
}
.doc {
  margin-top: 16rpx;
}
</style>
