<template>
  <app-view class="mine">
    <template #header>
      <app-navbar title="我的" :show-back-button="false" @ready="onReady" />
    </template>
    <div ref="headerRef" class="mine-header">
      <div class="mine-header__wrapper">
        <div class="profile">
          <div class="profile-user">
            <div class="profile-user__avatar" @click="routerTo('UserAvatar')">
              <img class="g-image--avatar" :src="userAvatar" />
            </div>
            <div class="profile-user__info">
              <div>
                <Tag :type="authStatus ? 'success' : 'primary'">{{ getAuthStatusName(authStatus) }}</Tag>
              </div>
              <span>{{ loginId }}</span>
            </div>
          </div>
          <div class="profile-account">
            <span>正常</span>
            <span>{{ firstAccountId }}</span>
          </div>
        </div>
        <div class="bank" v-if="accountInfo">
          <div class="bank-item">
            <span>余额</span>
            <span>{{ accountInfo.currentbalance.toFixed(2) }}</span>
          </div>
          <div class="bank-item">
            <span>冻结</span>
            <span>{{ freezeMargin.toFixed(2) }}</span>
          </div>
          <div class="bank-item">
            <span>可用</span>
            <span>{{ avaiableMoney.toFixed(2) }}</span>
          </div>
          <div class="bank-item">
            <span>
              <a @click="routerTo('bank-statement')">资金流水</a>
            </span>
            <span></span>
          </div>
        </div>
        <div class="button">
          <Button size="small" @click="doInOutMoney('1')" round>提现</Button>
          <Button type="primary" size="small" @click="doInOutMoney('0')" round>充值</Button>
        </div>
      </div>
    </div>
    <app-block class="mine-iconbar">
      <ul>
        <li @click="showQRCode = true">
          <img src="@mobile/assets/icons/generalize.svg" />
          <span>注册编码</span>
        </li>
        <li @click="routerTo('my-order')">
          <img src="@mobile/assets/icons/order.svg" />
          <span>我的订单</span>
        </li>
        <li @click="routerTo('my-wareorder')">
          <img src="@mobile/assets/icons/wareorder.svg" />
          <span>我的仓单</span>
        </li>
      </ul>
    </app-block>
    <app-block class="g-navmenu">
      <CellGroup>
        <Cell is-link :to="{ name: 'account-certification' }"
          v-if="[AuthStatus.Uncertified, AuthStatus.Rejected].includes(authStatus)">
          <template #title>
            <app-iconfont icon="icon-shimingrenzheng">实名认证</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'bank-sign' }" v-if="authStatus === AuthStatus.Certified">
          <template #title>
            <app-iconfont icon="icon-qianyuezhanghu">签约账户</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'rules-zcxy' }">
          <template #title>
            <app-iconfont icon="icon-yonghuzhucexieyi">用户注册协议</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'rules-yszc' }">
          <template #title>
            <app-iconfont icon="icon-guanyuzhengce">关于隐私</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'NavigationInvoice' }">
          <template #title>
            <app-iconfont icon="icon-fapiaoshuoming">关于发票</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'rules-fwrx' }">
          <template #title>
            <app-iconfont icon="icon-kefurexian">服务热线</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'NavigationSetting' }">
          <template #title>
            <app-iconfont icon="icon-shezhi">设置</app-iconfont>
          </template>
        </Cell>
        <Cell is-link :to="{ name: 'rules-gywm' }">
          <template #title>
            <app-iconfont icon="icon-guanyuwomen">关于我们</app-iconfont>
          </template>
        </Cell>
      </CellGroup>
    </app-block>
    <div class="mine-footer">
      <Button class="button-logout" type="primary" size="small" round @click="userLogout">退出登录</Button>
    </div>
    <app-register-code v-model:show="showQRCode" :text="registerCode" />
  </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, onActivated, computed } from 'vue'
import { Cell, CellGroup, Button, Tag, showFailToast } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { getFileUrl } from '@/filters'
import { useNavigation } from '@/hooks/navigation'
import { loginStore, accountStore, userStore } from '@/stores'
import AppIconfont from '@mobile/components/base/iconfont/index.vue'
import { queryBankAccountSign } from '@/services/api/bank'
import { queryUserAccount } from '@/services/api/account'
import { AuthStatus, getAuthStatusName } from '@/constants/account'
import eventBus from '@/services/bus'
import AppRegisterCode from '@mobile/components/modules/register-code/index.vue'

const { router, routerTo } = useNavigation()
const { userId, loginId, firstAccountId } = loginStore.$mapGetters()
const { userInfo } = userStore.$mapGetters()
const { accountInfo, freezeMargin, avaiableMoney } = accountStore.$mapGetters()

const authStatus = shallowRef(AuthStatus.Uncertified) // 实名认证状态
const registerCode = shallowRef('') // 注册编码
const headerRef = shallowRef<HTMLDivElement>()
const showQRCode = shallowRef(false)

// 用户头像
const userAvatar = computed(() => {
  const file = userInfo.value?.headurl
  return file ? getFileUrl(file) : ''
})

const onReady = (el: HTMLDivElement) => {
  // 设置背景图位置
  headerRef.value?.style.setProperty('background-position', `0 -${el.clientHeight}px`)
}

/// 进行出入金操作判断
const doInOutMoney = (tab: string) => {
  if (authStatus.value === AuthStatus.Certified) {
    fullloading((hideLoading) => {
      queryBankAccountSign().then((res) => {
        hideLoading()
        const { signstatus } = res.data[0] ?? {}
        /// 只有已签约的情况下才可以进行出入金
        if (signstatus && signstatus === 4) {
          router.push({ name: 'bank-wallet', query: { tab } })
        } else {
          dialog({
            message: '请先添加签约账户信息！',
            showCancelButton: true,
            confirmButtonText: '去签约'
          }).then(() => {
            router.push({ name: 'bank-sign' })
          })
        }
      }).catch(() => {
        showFailToast('加载失败')
      })
    }, '正在加载...')
  } else {
    dialog({
      message: '请先实名认证，再进行该操作！',
      showCancelButton: true,
      confirmButtonText: '去实名'
    }).then(() => {
      router.push({ name: 'account-certification' })
    })
  }
}

const userLogout = () => {
  dialog({
    message: '是否退出当前账号？',
    showCancelButton: true
  }).then(() => {
    eventBus.$emit('LogoutNotify')
  })
}

onActivated(() => {
  if (authStatus.value !== AuthStatus.Certified) {
    // 获取用户账号信息
    queryUserAccount({
      userID: userId.value
    }).then((res) => {
      authStatus.value = res.data.hasauth
      registerCode.value = res.data.refernum
    })
  }
})
</script>

<style lang="less">
@import './index.less';
</style>