<template>
    <div class="px-5 py-3">
        <div class="money rounded-[12px] overflow-hidden">
            <img src="@/assets/png-shouyi-bg.png" alt="" class="money-bg" />
            <div class="money-box flex">
                <div class="money-left flex-1 flex flex-col px-4">
                    <div class="text1 text-xs">账户余额</div>
                    <div class="text2 text-4xl mb-5 alimamaShuHeiTi">¥{{ balance }}</div>
                    <n-button
                        class="self-start"
                        @click="showWithdraw = true"
                        type="primary"
                        size="small"
                        icon-placement="right"
                        quaternary
                        round
                    >
                        去提现
                        <template #icon>
                            <n-icon size="18">
                                <ChevronRight />
                            </n-icon>
                        </template>
                    </n-button>
                </div>
                <!-- <div class="money-right px-5 py-2 border rounded-[8px] mr-[19px] flex flex-col items-center">
                    <div class="text1 flex items-center text-xs">
                        我的邀请
                        <n-icon size="18">
                            <ChevronRight />
                        </n-icon>
                    </div>
                    <div class="text2 text-xl alimamaShuHeiTi">21</div>
                </div> -->

                <div class="commission flex items-center text-xs" @click="goCommission">
                    邀请记录<n-icon size="18">
                        <ChevronRight />
                    </n-icon>
                </div>
            </div>
        </div>

        <div class="list">
            <div class="title flex justify-between py-4">
                <span class="alimamaShuHeiTi text-base">收支明细</span>

                <!-- <n-button size="small">
                    2023年4月
                    <n-icon size="18">
                        <ChevronDown />
                    </n-icon>
                </n-button> -->
            </div>

            <div
                class="record-info flex items-center py-4 bg-gray-100 px-3 rounded-[8px] dark:bg-[#20223C]"
                v-for="(item, index) in records"
                :key="index"
            >
                <img class="w-[36px]" :src="item['type'] === 'COMMISSION' ? commissionImg : withdrawImg" alt="" />
                <div class="text px-[12px] flex-1">
                    <div class="text-sm">{{ item['type'] === 'COMMISSION' ? '邀请奖励' : '用户提现' }}</div>
                    <div class="text-xs text-[#797A8A] mt-[2px]">{{ formatTime(item['createdAt']) }}</div>
                </div>
                <div
                    class="num text-lg alimamaShuHeiTi"
                    :class="{ 'text-[#7C3AED] dark:text-[#FFF671]': item['type'] === 'COMMISSION' }"
                >
                    {{ item['amount'] > 0 ? '+' : '' }}{{ item['amount'] }}
                </div>
            </div>

            <div class="empty py-6" v-if="!recordLoading && records.length === 0">
                <img class="w-3/5 block mx-[auto]" :src="isDark ? emptyDarkImg : emptyImg" alt="" />
                <div class="text-sm text-[#939599] text-center py-3">暂无信息</div>
            </div>
        </div>

        <n-modal v-model:show="showCommission" class="max-w-sm" transform-origin="center">
            <n-card
                :border="false"
                title="我的邀请"
                class="!rounded-xl commission-card"
                content-style="padding:0;overflow:auto"
            >
                <commission-pannel></commission-pannel>
            </n-card>
        </n-modal>

        <n-modal v-model:show="showWithdraw" class="max-w-sm !w-[90%]" transform-origin="center">
            <n-card
                :border="false"
                title="余额提现"
                class="!rounded-xl"
                content-style="padding:5px 20px 10px;overflow:auto"
                header-style="padding:10px 20px"
            >
                <n-form ref="withdrawForm" :model="form" :rules="rules" :show-require-mark="false">
                    <n-form-item path="name" label="姓名">
                        <template #label>
                            <div class="text-sm font-bold">姓名</div>
                        </template>
                        <n-input v-model:value="form.name" placeholder="请输入真实姓名"> </n-input>
                    </n-form-item>
                    <n-form-item path="account" label="银行卡号">
                        <template #label>
                            <div class="text-sm font-bold">银行卡号</div>
                        </template>
                        <n-input
                            v-model:value="form.account"
                            placeholder="请输入提现的银行卡号"
                            :allow-input="onlyAllowNumber"
                        >
                        </n-input>
                    </n-form-item>
                    <n-form-item path="amount" label="提现金额">
                        <template #label>
                            <div>
                                <div class="text-sm font-bold">提现金额</div>
                                <div class="text-xs text-[#C8C9CC] mt-[2px]">全部可提现 ¥{{ balance }}</div>
                            </div>
                        </template>
                        <div class="flex items-center w-[100%]">
                            <n-input-number
                                size="large"
                                class="flex-1"
                                placeholder="请输入提现金额"
                                v-model:value="form.amount"
                                :show-button="false"
                            >
                                <template #prefix> ￥ </template>
                            </n-input-number>
                            <n-button
                                class="!ml-[10px]"
                                secondary
                                type="primary"
                                @click="form.amount = balance"
                                round
                                size="small"
                                >全部</n-button
                            >
                        </div>
                    </n-form-item>
                </n-form>

                <div class="px-6 mt-10">
                    <n-button type="primary" :loading="loading" block round size="large" @click="submit"
                        >确认提现</n-button
                    >
                </div>
            </n-card>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, Ref, computed } from 'vue'
import { NButton, NIcon, NModal, NCard, FormInst, NForm, NFormItem, NInput, NInputNumber, useMessage } from 'naive-ui'
import { ChevronRight, ChevronDown } from '@vicons/tabler'
import { fetchUserBalance, fetchUserBalanceRecords, fetchWithdraw } from '@/api'
import withdrawImg from '@/assets/icon-tixian.png'
import commissionImg from '@/assets/icon-jiangli.png'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { useRouter } from 'vue-router'
import { CommissionPannel } from '@/components/common'
import emptyImg from '@/assets/empty.png'
import emptyDarkImg from '@/assets/empty-dark.png'
import { useTheme } from '@/hooks/useTheme'
import { format } from 'date-fns'

const balance = ref(0)
getBanlance()
function getBanlance() {
    fetchUserBalance().then((res: any) => {
        balance.value = res.balance
    })
}

const recordLoading = ref(true)
const records = ref([])
fetchUserBalanceRecords().then((res: any) => {
    records.value = res
    recordLoading.value = false
})
const { isMobile } = useBasicLayout()
const showCommission = ref(false)
const router = useRouter()
function goCommission() {
    if (isMobile.value) {
        router.push('/commission')
    } else {
        showCommission.value = true
    }
}

const showWithdraw = ref(false)
const withdrawValue = ref(0)
const canWithdraw = computed(() => {
    return Number(withdrawValue.value) > 0
})
const form = ref({
    name: '',
    account: '',
    amount: 0
})
const message = useMessage()
const loading = ref(false)
const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)
const rules = {
    name: [
        {
            required: true,
            message: '请输入真实姓名',
            trigger: ['blur']
        }
    ],
    account: [
        {
            validator(rule: any, value: any) {
                if (!value) {
                    return new Error('请输入提现的银行卡号')
                } else if (!/^([1-9]{1})(\d{15}|\d{16}|\d{18})$/.test(value)) {
                    return new Error('银行卡号格式错误')
                }

                return true
            },
            trigger: ['blur']
        }
    ],
    amount: [
        {
            validator(rule: any, value: any) {
                if (!value || Number(value) <= 0) {
                    return new Error('提现金额不能为空')
                }

                return true
            },
            trigger: ['blur']
        }
    ]
}

const withdrawForm: Ref<FormInst | null> = ref(null)
async function submit() {
    try {
        await withdrawForm.value?.validate()
    } catch (e: any) {
        return
    }
    loading.value = true
    fetchWithdraw({
        ...form.value
    })
        .then(res => {
            message.success('提现成功')
            getBanlance()
            showWithdraw.value = false
        })
        .catch(e => {
            message.error(e.message)
        })
        .finally(() => {
            loading.value = false
        })
}

const { isDark } = useTheme()

function formatTime(str: any) {
    return format(new Date(str), 'yyyy-MM-dd HH:mm')
}
</script>

<style lang="less" scoped>
.money {
    position: relative;
    color: #fff;

    .money-bg {
        display: block;
        height: 144px;
        width: 100%;
    }
    .money-box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        .f();

        .money-left {
            flex-grow: 1;
        }

        .n-button {
            background-color: #fff;
        }

        .money-right {
            border-color: #ffffff30;
            background: linear-gradient(180deg, #6d43ff 0%, rgba(109, 67, 255, 0.3) 100%);
        }
    }
}

.list {
    color: var(--n-text-color);
}
.record-info + .record-info {
    margin-top: 16px;
}

.commission {
    padding: 4px 6px 4px 15px;
    background: #6033ff;
    box-shadow: -2px 2px 4px 0px #9f83ff;
    border-radius: 0px 12px 0px 12px;
    position: absolute;
    top: 0;
    right: 0;
}
.commission-card {
    max-height: 80vh;
    min-height: 50vh;
}
</style>
