<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('user-avatar')">
                            <img class="g-image--avatar" :src="userStore.userAvatar" />
                        </div>
                        <div class="profile-user__info">
                            <div class="top">
                                <span>{{ userStore.customerName }}</span>
                                <Icon name="checked" color="var(--van-tag-success-color)"
                                    v-if="authStatus === AuthStatus.Certified" />
                                <Icon name="warning" color="var(--van-tag-warning-color)" v-else />
                            </div>
                            <div class="bottom">{{ loginStore.loginId }}</div>
                        </div>
                    </div>
                    <div class="profile-account">
                        <span>正常</span>
                        <span>{{ currentAccount.accountid ?? 0 }}</span>
                    </div>
                </div>
                <div class="bank">
                    <ul>
                        <li>
                            <span>余额</span>
                            <span>{{ currentAccount.currentbalance?.toFixed(2) }}</span>
                        </li>
                        <li>
                            <span>净值</span>
                            <span>{{ currentAccount.hazardValue?.toFixed(2) }}</span>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <span>预扣</span>
                            <span>{{ currentAccount.freezeMargin?.toFixed(2) }}</span>
                        </li>
                        <li>
                            <span>占用</span>
                            <span>{{ currentAccount.usedmargin?.toFixed(2) }}</span>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <span>可用</span>
                            <span>{{ currentAccount.avaiableMoney?.toFixed(2) }}</span>
                        </li>
                        <li>
                            <span>风险率</span>
                            <span :class="currentAccount.hazardRatioColor">
                                {{ parsePercent(currentAccount.hazardRatio) }}
                            </span>
                        </li>
                    </ul>
                </div>
                <div class="button">
                    <Button type="danger" size="small" round @click="doInOutMoney('0')">入金</Button>
                    <Button size="small" round @click="doInOutMoney('1')">出金</Button>
                </div>
            </div>
        </div>
        <app-block class="mine-iconbar">
            <ul>
                <li @click="routerTo('order-position')">
                    <Iconfont label-direction="bottom" icon="g-icon-position--line">我的持仓</Iconfont>
                </li>
                <li @click="routerTo('order-inout')">
                    <Iconfont label-direction="bottom" icon="g-icon-inout--line">持仓过户</Iconfont>
                </li>
                <li @click="routerTo('order-list')">
                    <Iconfont label-direction="bottom" icon="g-icon-order--line">我的订单</Iconfont>
                </li>
                <li @click="routerTo('order-delivery')">
                    <Iconfont label-direction="bottom" icon="g-icon-delivery--line">交货提货</Iconfont>
                </li>
                <li @click="routerTo('order-performance')">
                    <Iconfont label-direction="bottom" icon="g-icon-performance--line">履约信息</Iconfont>
                </li>
            </ul>
        </app-block>
        <app-block class="g-navmenu">
            <CellGroup>
                <Cell is-link :to="{ name: 'bank-capital' }">
                    <template #title>
                        <Iconfont icon="g-icon-capital">资金信息</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'account-certification' }" v-if="authStatus !== AuthStatus.Certified">
                    <template #title>
                        <Iconfont icon="g-icon-certification">实名认证</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'bank-sign' }" v-if="authStatus === AuthStatus.Certified && canBankSign">
                    <template #title>
                        <Iconfont icon="g-icon-sign">签约账户</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'account-protocol', query: { memberUserId: getMemberUserId()} }" v-if="userStore.userType != 2 && authStatus === AuthStatus.Certified">
                    <template #title>
                        <Iconfont icon="g-icon-order--line">合同签署</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'mine-profile' }">
                    <template #title>
                        <Iconfont icon="g-icon-profile">个人信息</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'rules-zcxy' }">
                    <template #title>
                        <Iconfont icon="g-icon-zcxy">用户注册协议</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'rules-yszc' }">
                    <template #title>
                        <Iconfont icon="g-icon-yszc">关于隐私</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'rules-fwrx' }">
                    <template #title>
                        <Iconfont icon="g-icon-fwrx">服务热线</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'mine-setting' }">
                    <template #title>
                        <Iconfont icon="g-icon-setting">设置</Iconfont>
                    </template>
                </Cell>
                <Cell is-link :to="{ name: 'rules-gywm' }">
                    <template #title>
                        <Iconfont icon="g-icon-gywm">关于我们</Iconfont>
                    </template>
                </Cell>
            </CellGroup>
        </app-block>
        <div class="mine-footer">
            <Button class="button-logout" type="danger" size="small" round @click="userLogout">退出登录</Button>
        </div>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, onMounted, onActivated, computed } from 'vue'
import { Cell, CellGroup, Button, Icon } from 'vant'
import { parsePercent } from '@/filters'
import { fullloading, dialog } from '@/utils/vant'
import { useNavigation } from '@mobile/router/navigation'
import { AuthStatus } from '@/constants/account'
import { queryBankAccountSign } from '@/services/api/bank'
import { useLoginStore, useAccountStore, useUserStore, usePositionStore } from '@/stores'
import eventBus from '@/services/bus'
import Iconfont from '@/components/base/iconfont/index.vue'
import { getMemberUserId } from '@/services/methods/user'
import { queryUsereSignRecords } from '@/services/api/account'

const { router, routerTo } = useNavigation()
const loginStore = useLoginStore()
const userStore = useUserStore()
const positionStore = usePositionStore()
const accountStore = useAccountStore()
const { currentAccount } = accountStore.$toRefs()
/// 判断是否能签约
const canBankSign = shallowRef(false) 
const headerRef = shallowRef<HTMLDivElement>()
const authStatus = computed(() => userStore.userAccount.hasauth) // 实名认证状态

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

/// 进行出入金操作判断
const doInOutMoney = (tab: string) => {
    if (authStatus.value === AuthStatus.Certified) {
        // /// 当前未签署合同
        // if (!canBankSign.value) {
        //     dialog({
        //         message: '请先去签署合同条例！',
        //         showCancelButton: true,
        //         confirmButtonText: '去签署合同'
        //     }).then(() => {
        //         router.push({ name: 'account-protocol', query: { memberUserId: getMemberUserId()} })
        //     })
        //     return
        // }
        // 判断是否已签约
        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(() => {
                hideLoading('加载失败', 'fail')
            })
        }, '正在加载...')
    } else {
        dialog({
            message: '请先实名认证，再进行该操作！',
            showCancelButton: true,
            confirmButtonText: '去实名'
        }).then(() => {
            router.push({ name: 'account-certification' })
        })
    }
}

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

onActivated(() => {
    if (authStatus.value !== AuthStatus.Certified) {
        userStore.getUserData()
    }
    accountStore.getAccountList()

    /// 机构不需要签合同
    if (userStore.userInfo.usertype === 2) {
        canBankSign.value = true
        return 
    }
    
    /// 查询数据
    queryUsereSignRecords({
        data: {
            userId: loginStore.userId
        }
    }).then((res) => {
        /// 判断是否能签约
        canBankSign.value = res.data.some(e => e.recordstatus === 3 )
    })
})

onMounted(() => {
    // 请求持仓列表，待优化---可用资金计算可能需要订阅行情
    positionStore.getTradePosition()
})
</script>

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