<template>
    <div class="signUpPayment">
        <!-- <m-header /> -->
        <m-step :number="4" />

        <van-cell-group>
            <!-- <van-cell title="准考证号：" :border="false">
                <template #default>支付完成后系统生成</template>
            </van-cell> -->
            <!-- <van-cell title="考生名字：" :border="false">
                <template #default>{{ orderInfo.studentName }}</template>
            </van-cell> -->
            <van-cell title="报考专业：" :border="false">
                <template #default>{{ orderInfo.subjectName }}</template>
            </van-cell>
            <van-cell title="乐理知识：" :border="false">
                <template #default>{{ orderInfo.examMusicTheoryLevel }}</template>
            </van-cell>
            <!-- <van-cell title="报考曲目：" :border="false">
                <template #default>
                    <p>钢琴音阶：B大调</p>
                    <p>钢琴练习曲：音画练习曲 OP.33 No.2</p>
                    <p>钢琴乐曲一：奏鸣曲第一乐章</p>
                    <p>钢琴乐曲二：奏鸣曲第二乐章</p>
                </template>
            </van-cell> -->
            <van-cell title="预计考试日期：" :border="false">
                <template #default>{{ orderInfo.examStartTime }}</template>
            </van-cell>
            <!-- <van-cell title="考试地点：" :border="false">
                <template #default>姜杰城航天桥分部</template>
            </van-cell> -->
            <van-cell title="报名费用：" :border="false">
                <template #default>¥{{ orderInfo.fee }}</template>
            </van-cell>
        </van-cell-group>

        <div class="notice">
            请考生于考试两周前严格按照系统要求进行报名及缴费，确保所填信息准确无误，确认之后所有信息无法更改，如因填写内容有误而造成损失，责任由报考者本人承担；请考生在报名缴费前确认可在考试时间内参加考试，最终以准考证上的考试信息为准，请务必按照要求参加考试，否则视为弃考。考生如无法保证按照准考证信息参加考试请慎重报考，报名费用一旦支付后均不允许更改报考级别或退款。
        </div>

        <div class="pay-group">
            <div class="pay-amount">
                <span>￥</span>{{ orderInfo.fee }}
            </div>
            <div class="pay-btn">
                <van-button color="#2DC7AA" @click="onSubmit" round>确认并支付</van-button>
            </div>
        </div>

        <m-payment :closeStatus="isStatus" :amount="Number(payMoney)" :payment="payment" @onChangeStatus="onChangeStatus" />
    </div>
</template>
<script>
import MStep from '@/components/MStep'
import MPayment from '@/components/MPayment'
import dayjs from 'dayjs'
import numeral from 'numeral'
// import { changeTwoDecimal } from '@/utils/common'
import { getExamRegistration, repay, examRegistrationAdd } from './SignUpApi'
import setLoading from '@/utils/loading'
const levelToCN = {
    1: "壹级",
    2: "贰级",
    3: "叁级",
    4: "肆级",
    5: "伍级",
    6: "陆级",
    7: "柒级",
    8: "捌级",
    9: "玖级",
    10: "拾级",
}
export default {
    name: 'signUpPayment',
	components: { MStep, MPayment },
    data () {
        const query = this.$route.query
        const params = localStorage.getItem("examRegistrationParams") ? JSON.parse(localStorage.getItem("examRegistrationParams")) : null
        return {
            orderNo: query.orderNo,
            examRegistrationId: query.examRegistrationId,
            payMoney: 0,
            orderInfo: { fee: 0 },
            params: params,
            payMap: {},
            isStatus: false,
            paymentResult: null, // 点击支付存支付信息
			payment: {}, // 支付对象
        }
    },
    mounted() {
        // 插入token
        // let params = this.$route.query
        // if(params.Authorization) {
        //     localStorage.setItem('Authorization', decodeURI(params.Authorization))
        //     localStorage.setItem('userInfo', decodeURI(params.Authorization))
        // }
        this.__init()
    },
    methods: {
        async __init() {
            setLoading(true)
            try {
                if(!this.examRegistrationId) {
                    setLoading(false)
                    if(this.params) {
                        this.onParse(this.params)
                    } else {
                        window.history.go(-1)
                    }
                    return
                }
                const res = await getExamRegistration({ examRegistrationId: this.examRegistrationId })
                setLoading(false)
                const result = res.data
                if(result.code == 200) {
                    //
                    const tempResult = result.data
                    this.onParse(tempResult)
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                // 
            }
        },
        onParse(tempResult) {
            let fee = numeral(tempResult.theoryLevelFee).add(tempResult.levelFee)
            let number = fee.value()
            const tempLevel = tempResult.examMusicTheoryLevel ? levelToCN[tempResult.examMusicTheoryLevel] + `/￥${numeral(tempResult.theoryLevelFee).format('0,0.00')}` : "免考"
            const params = {
                studentName: tempResult.studentName,
                subjectName: tempResult.subjectName + `(${levelToCN[tempResult.level]}/￥${numeral(tempResult.levelFee).format('0,0.00')})`,
                examMusicTheoryLevel: tempLevel,
                examStartTime: dayjs(tempResult.examStartTime).format("YYYY-MM-DD"),
                fee: numeral(number).format('0,0.00')
            }
            this.payMoney = number
            this.orderInfo = params
        },
        onChangeStatus(val) {
            this.isStatus = val
            // if(this.paymentResult) {
            //     this.orderNo = this.paymentResult.orderNo
            //     this.paymentResult = null
            // }
        },
        async onSubmit() {
            // 没有订单号说明是创建订单
            if(this.orderNo) {
                this.onRePay()
                return
            } else {
                this.onExamRegistration()
            }
        },
        async onExamRegistration() {
            setLoading(true)
            // 有订单号说明重新支付
            try {
                let res = await examRegistrationAdd(this.params)
                setLoading(false)
                let result = res.data
                if(result.code == 200) {
                    this.payMap = result.data.payMap
                    this.paymentResult = result.data.payMap
                    const orderNo = result.data.payMap.orderNo
                    this.orderNo = orderNo
                    const examRegistrationId = result.data.examRegister.id
                    const origin = window.location.origin
                    history.replaceState("", "Title", `${origin}/#/signUpPayment?orderNo=${orderNo}&examRegistrationId=${examRegistrationId}`)
                    this.onSubmitPay()
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                //
            }
        },
        async onRePay() {
            setLoading(true)
            // 有订单号说明重新支付
            try {
                let res = await repay({ orderNo: this.orderNo })
                setLoading(false)
                let result = res.data
                if(result.code == 200) {
                    this.payMap = result.data.payMap
                    this.paymentResult = result.data.payMap
                    const orderNo = result.data.payMap.orderNo
                    this.orderNo = orderNo
                    const examRegistrationId = result.data.examRegister.id
                    const origin = window.location.origin
                    history.replaceState("", "Title", `${origin}/#/signUpPayment?orderNo=${orderNo}&examRegistrationId=${examRegistrationId}`)
                    this.onSubmitPay()
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                //
            }
        },
        onSubmitPay() {
            // submit 提交
            let result = this.payMap
            if(result.type == "YQPAY") {
                let f = result.payMap
                document.querySelector('#onSubmit').action = f.host
                document.querySelector('#apiContent').value = f.apiContent
                document.querySelector('#merNo').value = f.merNo
                document.querySelector('#notifyUrl').value = f.notifyUrl
                document.querySelector('#sign').value = f.sign
                document.querySelector('#signType').value = f.signType
                document.querySelector('#timestamp').value = f.timestamp
                document.querySelector('#version').value = f.version
                document.querySelector('#onSubmit').submit()
            } else if (result.type == 'ADAPAY') {
				this.payment = result
				// 开始支付窗口
				this.isStatus = true
			}
        }
    },
    destroyed() {
        window.removeEventListener("popstate", ()=>{})
    }
}
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable");
.signUpPayment {
    height: 100vh;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: @--main-bg-color;
    .title {
        font-size: .16rem;
        color: @--font-second-color;
        padding: .12rem .16rem;
    }
    /deep/.van-cell {
        padding: .1rem .16rem;
        font-size: .15rem;
        color: @--font-main-color;
    }
    /deep/.van-cell__title {
        width: 1.1rem;
        flex: none;
    }
    /deep/.van-cell__value {
        text-align: left;
        color: @--font-main-color;
        p {
            padding-bottom: .15rem;
            &:last-child{
                padding-bottom: 0;
            }
        }
    }

    /deep/.van-cell-group {
        padding: .1rem 0 .15rem;
        margin-top: .15rem;
        border-radius: .1rem;
        overflow: hidden;
    }

    .notice {
        font-size: .13rem;
        color: @--font-second-color;
        padding: .2rem .16rem;
        line-height: .18rem;
        margin-bottom: .55rem;
    }

    .pay-group {
        position: fixed;
        bottom: 0;
        width: calc(100% - .32rem);
        height: .55rem;
        line-height: .53rem;
        padding: 0 .16rem;
        display: flex;
        justify-content: space-between;
        align-content: center;
        background-color: #ffffff;
    }
    .pay-amount {
        color: #FF1818;
        font-size: .26rem;
        span {
            font-size: .16rem;
        }
    }
    /deep/.van-button {
        font-size: .16rem;
        padding: 0 .2rem;
    }
}

.van-popup-song {
    width: 80%;
    border-radius: .08rem;
}
.song-popup {
    text-align: center;
    .title {
        font-size: 18px;
        font-weight: 500;
        color: #333333;
        padding: .2rem 0 .24rem;
    }
    .song-upload {
        margin: 0 .5rem;
        padding: .18rem 0 .1rem;
        border-radius: .05rem;
        border: 1px dashed #777777;
        font-size: .16rem;
        color: #777;
    }
    .song-popup-tips {
        font-size: .14rem;
        color: #808080;
        padding-top: .1rem;
        padding-bottom: .25rem;
    }
    .popup-group {
        width: 100%;
        display: flex;
        color: @--main-color;
        background-color: #F0F0F0;
        font-size: .18rem;
        span {
            padding: .12rem 0;
            flex: 1;
        }
        .popup-sure {
            color: #ffffff;
            background-color: @--main-color;
        }
    }
}
</style>