<template>
    <div class="transfer">
        <div style="flex: 1;overflow-y: auto;padding: 0 16px;" class="transfer-box">
            <div>
                <div>减少时长的云机</div>
                <div>
                    <comoros :key="transferUserCardKey" :dayTime="countObj.transferMinDay"
                        :transferPhoneList="transferPhoneList" v-model="params.transferUserCardId"
                        :name.sync="transferUserCardName" @confirm="comorosConfirm" />
                </div>
            </div>
            <div class="transfer-item">
                <div>增加时长的云机</div>
                <div>
                    <comoros :key="acceptUserCardKey" :disabledId="params.transferUserCardId"
                        :transferPhoneList="transferPhoneList" :buyVipType="buyVipType" v-model="params.acceptUserCardId"
                        :name.sync="acceptUserCardName" :androidVersion="androidVersion" distinguishBool />
                </div>
            </div>
            <div class="transfer-item">
                <div>转移的时间</div>
                <div class="transfer-item-input">
                    <van-field placeholder="请输入转移的时间" v-model="params.transferTime"
                        @input="params.transferTime = params.transferTime.replace(/\D/g, '')" />
                    天
                </div>
            </div>
            <span style="font-size: 12px;font-weight: 400;color: #3B7FFF;line-height: 16px;margin-top: 5px;"
                @click="(params.transferTime && Object.keys(countObj).length) && serviceCount()"
                :class="{ opacity: !params.transferTime || !Object.keys(countObj).length }">{{ countLoading ? '正在计算中...' :
                    '服务费计算'
                }}</span>
            <div class="transfer-tip">
                <div>
                    温馨提示：
                </div>
                <div class="transfer-tip-content">
                    <div v-html="html"></div>
                </div>
            </div>
        </div>
        <div class="transfer-btn" v-show="btnVisible">
            <van-button type="info" block
                :disabled="!params.transferUserCardId || !params.acceptUserCardId || !params.transferTime"
                :loading="allocateLoading" @click="changePopUpType(0)" loading-text="正在分配时间中...">
                分配时间
            </van-button>
        </div>

        <van-dialog v-model="visible" :title="clickType ? '服务费计算' : ''" confirmButtonColor="#3B7FFF" className="dialog"
            showCancelButton cancelButtonColor="#999999" @confirm="!clickType && confirm()"
            @close="allocateLoading = false">
            <div style="padding: 16px;font-weight: 100;">
                <template v-if="clickType">
                    <div style="display: flex; justify-content: space-between;">
                        <div>转移天数：</div>
                        <div style="color: #F9F9F9;">{{ params.transferTime }}天</div>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <div>服务费：</div>
                        <div style="color: #F9F9F9;">{{ serviceCharge }}天</div>
                    </div>

                </template>

                <template v-else>
                    <div style="line-height: 30px;">
                        <div style="text-align: center;font-weight:bold;">
                            确定要将【{{ transferUserCardName }}】
                        </div>
                        <div style="text-align: center;">
                            时间分配给【{{ acceptUserCardName }}】
                        </div>
                        <div style="text-align: center;margin-top: 10px">
                            服务费：{{ serviceCharge }}天
                        </div>
                    </div>
                </template>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import {
    sha256
} from 'js-sha256';
import BigNumber from "bignumber.js";
import { Toast } from 'vant'
const comoros = () => import('./comoros.vue')
export default {
    name: 'tansferDuration',
    components: {
        comoros
    },
    props: {
        token: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            visible: false,// 显示弹窗
            transferPhoneList: [], // 云机列表
            buyVipType: '', // 当前选中的云机类型
            params: {},
            acceptUserCardKey: +new Date(),
            transferUserCardKey: +new Date(),
            acceptUserCardName: '',
            transferUserCardName: '',
            // 点击类型 0 是确认转移、1是计算手续费
            clickType: 0,
            // 计算loading
            countLoading: false,
            // 计算服务费的对象
            countObj: {},
            // 服务费
            serviceCharge: '',
            // 分配时间loading
            allocateLoading: false,
            html: '',
            androidVersion: '',
            btnVisible: true
        };
    },

    mounted() {
        this.init()
        this.getFeeRatio()
        this.getRule()
        const userAgent = navigator.userAgent
        if (userAgent.includes("Android")) {
            window.onresize = this.monitoringDevices
        }
    },
    beforeDestroy() {
        window.onresize = null
    },
    methods: {
        init() {
            this.params = {
                acceptUserCardId: '', // 接受设备ID
                transferUserCardId: '', // 转移设备ID
                transferTime: '' // 转移天数
            }
            this.acceptUserCardKey = +new Date()
            this.transferUserCardKey = +new Date()
            this.buyVipType = ''
            this.serviceCharge = ''
            this.getTransferPhoneList()
        },
        // 获取云机列表
        getTransferPhoneList() {
            this.$axios.$get('resources/v5/time/transfer/getTransferPhoneList', { header: { token: this.token, versionName: '5.7.4' } }).then(res => {
                if (res.success) {
                    this.transferPhoneList = res.data
                }
            })
        },
        // 确认框
        comorosConfirm(data) {
            this.buyVipType = data.buyVipType
            this.buyVipType === 'SVIP' && (this.androidVersion = data.androidVersion);
            this.acceptUserCardKey = +new Date()
            this.params.acceptUserCardId = ''
        },

        // 获取手续费比例
        getFeeRatio() {
            this.$axios.$get('resources/v5/time/transfer/getFeeRatio', { headers: { Authorization: this.token, versionName: '5.7.4' } }).then(res => {
                if (res.success) {
                    res.data.transferMinDay = res.data.transferMinDay * 24 * 60
                    this.countObj = res.data
                }
            }).catch(err => {
                Toast.fail(err.message)
            })
        },

        // 确定提交
        async confirm() {
            // 获取服务器时间
            let requestTime = await this.$axios.$get('pay/v1/order/getSystemTime', { headers: { Authorization: this.token, versionName: '5.7.4' } })

            requestTime = new Date(requestTime.data * 1000).$formatTime()
            const requestTimeSign = sha256("Register_SZX_2023:" + requestTime)
            this.$axios.$post('resources/v5/time/transfer/transferDurationOperation', {
                ...this.params,
                requestTime
            }, { headers: { Authorization: this.token, versionName: '5.7.4', requestTimeSign } }).then(res => {
                if (res.success) {
                    this.init()
                    Toast.success(res.msg)
                }
            }).catch(err => {
                Toast.fail(err.message)
            }).finally(() => {
                this.allocateLoading = false
            })

        },

        // 服务费计算
        serviceCount(bool = true) {
            if (this.countLoading) return
            if (bool) this.countLoading = true
            const arr = this.countObj.list.sort((a, b) => {
                return a.timeConsumingEnd - b.timeConsumingEnd
            })
            let commission = null
            for (const i of arr) {
                if (+this.params.transferTime <= i.timeConsumingEnd) {
                    commission = i.commission
                    break
                }
            }
            if (!commission) commission = this.countObj.commissionSet
            const serviceCharge = +new BigNumber(this.params.transferTime).times(new BigNumber(commission).div(100))
            this.serviceCharge =  serviceCharge < 1 ? 1 : serviceCharge
            this.countLoading = false
            if (bool) this.changePopUpType(1)
        },

        changePopUpType(e) {
            if (!Object.keys(this.countObj).length) {
                Toast.fail('活动已结束')
                return
            }
            if (!e) {
                this.serviceCount(false)
                this.allocateLoading = true
            }
            this.visible = true
            this.clickType = e
        },

        // 获取规则
        getRule() {
            this.$axios.$get('/public/v4/agreement/content', {
                params: {
                    agreementCoding: 'YJSBSJZY2024'
                }, headers: { Authorization: this.token, versionName: '5.7.4' }
            }).then(res => {
                const html = res.data.content;
                const rx = /<body[^>]*>([\s\S]+?)<\/body>/i;
                let m = rx.exec(html);
                if (m) {
                    m = m[1]
                };
                this.html = m

            })
        },
        monitoringDevices() {
            this.btnVisible = !this.btnVisible
        }
    },
};
</script>

<style lang="scss" scoped>
.transfer {
    padding: 0 0 30px;
    display: flex;
    flex-direction: column;
    height: 100%;

    .transfer-item {
        margin-top: 16px;
    }

    .transfer-tip {
        margin-top: 24px;
    }

    .transfer-item-input {
        margin-top: 8px;
        display: flex;
        align-items: center;
    }

    .transfer-tip-content {
        margin-top: 8px;
    }

    .transfer-tip-content {
        font-size: 12px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #959799;
        line-height: 17px;
    }

    .transfer-btn {
        padding: 0 16px;
        height: 48px;
        margin-top: 20px;
        .van-button {
            height: 100%;
            border-radius: 5px;
        }
    }

    .van-field {
        background: #2C2C2D;
        margin-right: 12px;
        border-radius: 5px;
        height: 52px !important;
        font-weight: 500 !important;
        align-items: center;

        ::v-deep .van-field__control {
            color: #fff;
        }

        ::v-deep .van-field__control::-webkit-input-placeholder {
            color: #999999 !important;
        }
    }
}

.dialog {
    color: #CFD1D4;

    ::v-deep [class*=van-hairline]::after {
        border-color: rgba(72, 72, 72, 0.5);
    }

    &,
    ::v-deep .van-button__content {
        background: #2C2C2D;
    }
}

.opacity {
    opacity: .4;
}

.transfer-tip-content {
    ::v-deep ol {
        list-style-type: decimal;
    }

    ::v-deep ul {
        list-style-type: disc;
    }
}
</style>