<template>
    <page :nav="false" ref="pageRef">
        <view
            class="detailWrapper"
            :style="'background-image:url(' + ossurl.box.headbj + ')'"
        >
            <view
                class="pagae-nav"
                :style="{ paddingTop: statusBarHeight + 'px', background: headerBg }"
            >
                <view class="flex-align-center relative" style="height: 80rpx">
                    <text class="cuIcon-back back" @click.stop="back"></text>
                    <view v-if="data" class="title line-ellipsis">
                        {{ data && data.name }}
                    </view>
                </view>
            </view>
            
            <view :style="{ height: 72 + statusBarHeight * 2 + 'rpx' }"></view>

            <top
                v-if="data"
                :data="data"
                :horse="horse"
                @onShowRecord="showRecord"
                @onShowUpdate="showUpdate"
                :type="2"
            />
            <view class="SwiperBox">
                <swiper
                    class="productSwiper"
                    :indicator-dots="false"
                    circular="true"
                    :autoplay="false"
                    interval="5000"
                    duration="500"
                    :current="current"
                    @change="handleChange"
                >
                    <swiper-item
                        v-for="(item, index) in products"
                        :key="index"
                        @click="showSwipe(index)"
                    >
                        <view class="imageBox">
                            <image :src="item.cover" mode="aspectFit" />
                        </view>
                        <view
                            class="level"
                            :style="{ backgroundImage: 'url(' + ossurl.mine.butbj + ')' }"
                        >
                            {{ getLevel(item.level) }}({{ getProbability(item) }})
                        </view>
                    </swiper-item>
                </swiper>
                <view class="prev" @click="handlePrev" v-if="current !== 0">
                    <image :src="ossurl.box.detail.left" mode="aspectFit" />
                </view>
                <view class="next" @click="handleNext" v-if="products&&current !== products.length - 1">
                    <image :src="ossurl.box.detail.right" mode="aspectFit" />
                </view>
            </view>
			<view class="swiperBottom">
				<image :src="ossurl.box.detail.bottom" style="width: 100%;" mode="widthFix" />
			</view>
        </view>
        <!-- v-if="box && box.lock"-->

        <view class="lockTimeBox" v-if="box && box.lock">
            剩余时间：
            <view class="lockTimeBarBox">
                <view class="lockTime">
                    <view
                        class="processBar"
                        :style="{ right: 'calc(100% - ' + leftNum + '%)' }"
                    ></view>
                </view>
                <view class="line" :style="{ left: leftNum + '%' }"></view>
                <view class="text" :style="{ left: 'calc(' + leftNum + '% - 26rpx)' }">
                    {{ leftTime }}s
                </view>
            </view>
        </view>
        <first-last
            v-if="box && box.prizeList"
            :data="data"
            :box="box"
            :prizeList="box.prizeList"
            @nextBox="nextBox"
            @preBox="preBox"
            @showBox="showBox"
        />
        <product-a
            v-if="products"
            :products="products"
            :poolId="poolId"
            :box="box"
            :levelist="probability"
        />

        <view class="bottom paddingX10" v-if="data && box">
            <view class="bottom-btns flex-align-around">
                <view
                    class="relative btnItem"
                    @click="pay(1)"
                    :style="{ backgroundImage: 'url(' + ossurl.box.detail.yfBtn + '); color: #000;' }"
                >
                    一发入魂
                    <view v-if="$valid.isNumber2(data.specialPrice)" class="text">
                        (¥{{ data.specialPrice }})
                    </view>
                    <view v-else class="text">(¥{{ data.price }})</view>
                </view>
                <view
                    class="relative btnItem"
                    @click="pay(5)"
                    :style="{ backgroundImage: 'url(' + ossurl.box.detail.wlBtn + ')' }"
                >
                    五连绝世
                    <view v-if="data.specialPriceFive" class="text">
                        (¥{{ data.specialPriceFive }})
                    </view>
                    <view v-else class="text">(¥{{ data.price * 5 }})</view>
                </view>
                <view
                    class="relative btnItem"
                    @click="$refs.numRef.show(box)"
                    :style="{ backgroundImage: 'url(' + ossurl.box.detail.csBtn + ')' }"
                >
                    自由超神
                </view>
            </view>
        </view>
        <image class="ck" :src="ossurl.box.detail.warehouse" webp @click="showCK" mode="widthFix" />
        <image class="mj" :src="ossurl.box.detail.stone" v-if="user" webp @click="$router.push('magic')" mode="widthFix" />
        <image class="record" :src="ossurl.box.detail.record" webp @click="showRecord" mode="widthFix" />
        <image class="rule" :src="ossurl.box.detail.rule" webp @click="showRule" mode="widthFix" />
        <image class="refresh" :src="ossurl.box.detail.refresh" webp @click="refreshBox(true)" mode="widthFix" />
		<!-- 锁定 -->
        <image
            v-if="box && !box.lock"
            class="lock"
            :src="ossurl.box.detail.lock"
            webp
            @click="boxLock"
			mode="widthFix"
        />
		<!-- 解锁 -->
        <image
            v-if="box && box.lock && user && box.lock.locker === user.userId"
            class="lock"
            :src="ossurl.box.detail.unlock"
            webp
            @click="boxUnLock"
			mode="widthFix"
        />
        <image
            v-if="
                box && box.leftQuantity > 0 && box.lock && user && box.lock.locker === user.userId
            "
            class="Inclusive"
            :src="ossurl.box.detail.Inclusive"
            webp
            @click="payAll"
			mode="widthFix"
        />
        <box-choose ref="boxRef" v-if="data" :poolId="poolId" @choose="onChooseBox" />
        <num-choose ref="numRef" v-if="data" :poolId="poolId" @pay="onNumPay" />
        <checkout
            ref="checkoutRef"
            v-if="data"
            :data="data"
            @close="onClose"
            :poolId="poolId"
            @success="onSuccess"
        />
        <result-com ref="result" :num="num || 0" :periodQuantity="periodQuantity" />
        <record ref="recordRef" @close="onClose" :poolId="poolId" />
        <hiddenTask ref="hiddenTaskRef" @refresh="init(true)" />
        <ruleDialog ref="ruleDialog"></ruleDialog>
    </page>
</template>

<script>
    import loginMixin from '@/mixin/login'
    import resource from '@/utils/resource'
    import top from './../award_detail/top'
    import official from './../award_detail/official'
    import productA from './product_a'
    import productB from './../award_detail/product_b'
    import checkout from './../award_detail/checkout'
    import resultCom from './result_com'
    import prince from './../award_detail/prince'
    import boxChoose from './box_choose'
    import numChoose from './num_choose'
    import record from './../award_detail/record'
    import levelRatio from './../award_detail/level_ratio'
    import firstLast from './first_last'
    import hiddenTask from '../hidden_activity/hidden_task_dialog'
    import { throttle } from '@/utils'
    import ossurl from '@/utils/ossurl'
    import { LEVEL_MAP } from '@/utils/config'
    import ruleDialog from './ruleDialog'
    export default {
        mixins: [loginMixin],
        components: {
            top,
            official,
            productA,
            productB,
            checkout,
            resultCom,
            prince,
            boxChoose,
            numChoose,
            record,
            levelRatio,
            firstLast,
            hiddenTask,
            ruleDialog
        },
        data() {
            return {
                ossurl,
                resource,
                poolId: null,
                data: null,
                products: null,
                horse: null,
                lock: false,
                tableData: null,
                periodQuantity: null,
                box: null,
                boxNum: null,
                probability: null,
                leftTime: 0,
                smartPayFlag: true,
                scrollTop: 0,
                current: 0
            }
        },
        computed: {
            statusBarHeight() {
                if (this.$store.state.systemInfo) {
                    return this.$store.state.systemInfo.statusBarHeight
                }
                return 20
            },
            headerBg() {
                return this.scrollTop > 0 ? '#fff' : 'transparent'
            },
            user() {
                return this.$store.state.userInfo
            },
            leftNum() {
                return this.box && this.box.lock && this.box.lock.leftTime
                    ? (this.leftTime / this.box.lock.leftTime) * 100
                    : 0
            }
        },
        onPageScroll(e) {
            this.scrollTop = e.scrollTop
        },
        onLoad(options) {
            this.poolId = options.poolId
            this.poolIn()
            if(this.$store.state.hide){
              this.showRule()
            }
        },
        mounted() {
            setTimeout(() => {
                this.init(true)
            }, 100)
        },
        onUnload() {
            this.poolOut()
            this.lockTimeEnd()
        },
        onShareAppMessage(res) {
            return {
                title: this.data.name,
                path: '/pages/award/index',
                imageUrl: this.data.cover
            }
        },
        onShareTimeline() {
            return {
                title: '燚火漫域 次元聚集地，潮玩新势力',
                query: 'poolId=' + this.poolId,
                imageUrl: this.data.cover
            }
        },
        methods: {
            showSwipe(index) {
                this.$router.push('award_detail_swipe', { poolId: this.poolId, index })
            },
            getLevel(level) {
                let item = LEVEL_MAP[level]
                if (item) {
                    return item.title
                } else {
                    return ''
                }
            },
            back() {
                this.$router.back()
            },
            poolIn() {
                if (this.$common.isLogin()) {
                    this.$service.award.poolIn(this.poolId)
                }
            },
            poolOut() {
                if (this.$common.isLogin()) {
                    this.$service.award.poolOut(this.poolId)
                }
            },
            async init(loading = false) {
                this.getData(loading)
                this.getBox()
                this.getHorse()
            },
            async getData(loading = false) {
                const res = await this.$service.award.detail(this.poolId, loading)
                this.data = res
                res && (this.products = res.luckGoodsList)
                this.$refs.princeRef && this.$refs.princeRef.refresh()
            },
            refreshBox(loading = false) {
                this.getBox(this.boxNum, loading)
            },
            onChooseBox(index) {
                this.getBox(index, true)
            },
            async getBox(num, loading = false) {
                const res = await this.$service.award.box(this.poolId, num, loading)
                res && this.handleBoxResult(res)
            },
            handleBoxResult(res) {
                let map = {}
                if (res.usedStat) {
                    res.usedStat.forEach((item) => {
                        map[item.spuId] = item
                    })
                }
                res.usedStat = map
                this.box = res
                this.boxNum = res.number
                this.lockTimeStart()
                if (res.leftQuantity <= 0) {
                    this.probability = [
                        { level: 'A', probability: '0' },
                        { level: 'B', probability: '0' },
                        { level: 'C', probability: '0' },
                        { level: 'D', probability: '0' }
                    ]
                } else {
                    this.probability = [
                        {
                            level: 'A',
                            probability: ((res.leftQuantityA / res.leftQuantity) * 100).toFixed(4)
                        },
                        {
                            level: 'B',
                            probability: ((res.leftQuantityB / res.leftQuantity) * 100).toFixed(4)
                        },
                        {
                            level: 'C',
                            probability: ((res.leftQuantityC / res.leftQuantity) * 100).toFixed(4)
                        },
                        {
                            level: 'D',
                            probability: ((res.leftQuantityD / res.leftQuantity) * 100).toFixed(4)
                        }
                    ]
                }
            },
            async getHorse() {
                const res = await this.$service.award.detailHorse(this.poolId)
                this.horse = res
            },
            async preBox() {
                if (this.boxNum <= 1) return
                const res = await this.$service.award.preBox(this.poolId, this.boxNum)
                res && this.handleBoxResult(res)
            },
            async nextBox() {
                if (this.boxNum >= this.box.lastNumber) return
                const res = await this.$service.award.nextBox(this.poolId, this.boxNum)
                res && this.handleBoxResult(res)
            },
			showBox(){
				this.$refs.boxRef.show()
			},
            async pay(num) {
                throttle.call(() => {
                    this.previewPay(num)
                })
            },
            async previewPay(num) {
                if (!this.$common.isLogin()) {
                    this.$router.push('login')
                    return
                }
                const res = await this.$service.award.preview(this.poolId, num, this.box.number)
                if (res) {
                    this.$refs.checkoutRef.show(num, res, this.boxNum)
                    this.lock = true
                }
            },
            async payAll() {
                if (!this.$common.isLogin()) {
                    this.$router.push('login')
                    return
                }
                const res = await this.$service.award.preview(
                    this.poolId,
                    1,
                    this.box.number,
                    null,
                    1
                )
                if (res) {
                    this.$refs.checkoutRef.show(res['quantity'], res, this.boxNum, null, 1)
                    this.lock = true
                }
            },
            async onNumPay({ res, chooseNum, boxNum }) {
                this.$refs.checkoutRef.show(chooseNum.length, res, this.boxNum, chooseNum)
            },
            showCK() {
                this.$router.push('store')
            },
            onClose() {
                this.lock = false
            },
            onSuccess({ tradeNo }) {
                this.$refs.numRef && this.$refs.numRef.close()
                this.lock = false
                this.$message.showLoading()
                this.tradeNo = tradeNo
                this.getResult(0)
                if (this.$store.state.hide == 1) {
                    this.$service.user.getHide()
                    this.pageConfig('magic_luck')
                }
                //菊花刷新
            },
            async pageConfig(key) {
                const res = await this.$service.base.pageConfig(key)
                let pageConfig = this.$store.state.pageConfig || {}
                pageConfig[key] = res
                this.$store.commit(SET_PAGE_CONFIG, { ...pageConfig })
            },
            getResult(count) {
                setTimeout(async () => {
                    await this.getResultData()
                    if (this.tableData && this.tableData.length > 0) {
                        this.$message.hideLoading()
                        this.showResult()
                    } else {
                        if (count < 4) {
                            this.initData(count + 1)
                        } else {
                            this.fail()
                        }
                    }
                }, 500)
            },
            async getResultData() {
                const res = await this.$service.award.applyResult(this.tradeNo)
                if (res && res.inventoryList) {
                    let array = res.inventoryList
                    if (res.magicFireworksList && res.magicFireworksList.length > 0) {
                        array = [...res.magicFireworksList, ...res.inventoryList]
                    }
                    this.tableData = array
                    if (res.kingRealtime) {
                        this.periodQuantity = res.kingRealtime.periodQuantity
                    }
                    if (res.richmanTicketRealtime && res.richmanTicketRealtime.changeTicket) {
                        this.changeTicket = res.richmanTicketRealtime.changeTicket
                    } else {
                        this.changeTicket = 0
                    }
                    this.refreshBox()
                }
                const spuIds = res.inventoryList.map((item) => item.spu.id)
                const hideRes = await this.$service.award.hideTaskStart(JSON.stringify(spuIds))
                if (hideRes === 1 || hideRes === 2) {
                    this.$refs.hiddenTaskRef.show(hideRes)
                }
                return true
            },
            async showResult() {
                if (this.tableData && this.tableData.length > 0) {
                    let array = [...this.tableData]
                    this.$refs.result.show(array, this.changeTicket)
                }
            },
            async fail() {
                this.$message.hideLoading()
                this.tableData = null
                this.$message.confirm(
                    '购买结果请至订单详情查看',
                    () => {
                        this.$router.push('order_award')
                    },
                    '',
                    ['去查看', '取消']
                )
            },
            showRecord() {
                this.$refs.recordRef.show()
                this.lock = true
            },
            async boxLock() {
                if (!this.$common.isLogin()) {
                    this.$router.push('login')
                    return
                }
                await this.$service.award.boxLock(this.poolId, this.boxNum)
                this.refreshBox(true)
            },
            async boxUnLock() {
                await this.$service.award.boxUnLock(this.poolId, this.boxNum)
                this.refreshBox(true)
            },
            lockTimeStart() {
                this.lockTimeEnd()
                if (this.box && this.box.lock) {
                    this.leftTime = this.box.lock.leftTime
                    this.timer = setInterval(() => {
                        this.leftTime -= 1
                        if (this.leftTime <= 0) {
                            this.lockTimeEnd()
                            this.getBox()
                        }
                    }, 1000)
                }
            },
            lockTimeEnd() {
                if (this.timer) {
                    clearInterval(this.timer)
                    this.timer = null
                }
                this.leftTime = 0
            },
            closeSmartTitle() {
                this.smartPayFlag = false
            },
            showRule() {
                // this.$router.push('playing_method', { type: 2 })
                this.$refs.ruleDialog.visible = true
            },
            handleChange(e) {
                this.current = e.detail.current
            },
            handlePrev() {
                this.current -= 1
            },
            handleNext() {
                this.current += 1
            },
            getLeftNum(row) {
                if (
                    !this.box ||
                    !this.box.usedStat ||
                    !this.box.usedStat[row.spu.id] ||
                    !this.box.usedStat[row.spu.id].quantity
                ) {
                    return row.quantity
                }
                return row.quantity - this.box.usedStat[row.spu.id].quantity
            },
            getProbability(row) {
                if (!this.box) return
                let leftNum = this.getLeftNum(row)
                return (
                    this.$common.ignoreRatio0(
                        ((leftNum / this.box.leftQuantity) * 100).toFixed(4)
                    ) + '%'
                )
            }
        }
    }
</script>

<style></style>
<style lang="scss" scoped>
    .award-detail {
        padding-bottom: calc(136rpx + env(safe-area-inset-bottom));
    }
    .detailWrapper {
        background-size: 100% auto;
        background-repeat: no-repeat;
        height: 1240rpx;
        .SwiperBox {
            position: relative;
            .prev,
            .next {
                position: absolute;
                top: 20%;
                z-index: 90;
                image {
                    width: 108rpx;
                    height: 108rpx;
                }
            }
            .prev {
                left: 0;
            }
            .next {
                right: 0;
            }
        }
        .productSwiper {
            height: 750rpx;

            .imageBox {
                text-align: center;
                height: 40.5vh;
                font-size: 0;
                line-height: 0;
                image {
                    width: 520rpx;
                    height: 40.5vh;
                    animation: animateImage 3s;
                    animation-play-state: running;
                    animation-iteration-count: infinite;
                    animation-timing-function: linear;
                }
            }
            .level {
                text-align: center;
                font-size: 24rpx;
                font-family: Alimama ShuHeiTi, Alimama ShuHeiTi;
                font-weight: 700;
                color: #333;
                background-size: 272rpx 62rpx;
                background-position: center;
                background-repeat: no-repeat;
                line-height: 62rpx;
            }
            @keyframes animateImage {
                from,
                to {
                    transform: translate3d(0, 0, 0);
                }

                25% {
                    transform: translate3d(0, 10px, 0);
                }
                50% {
                    transform: translate3d(0, 0, 0);
                }

                75% {
                    transform: translate3d(0, -10px, 0);
                }
                100% {
                    transform: translate3d(0, 0, 0);
                }
            }
        }
    }
    .pagae-nav {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        z-index: 100;
        align-items: center;
        .title {
            font-size: 30rpx;
            font-weight: bold;
            text-align: center;
            line-height: 72rpx;
            width: 500rpx;
        }
        .back {
            z-index: 1800;
            font-size: 32rpx;
            line-height: 32rpx;
            position: absolute;
            left: 20rpx;
            top: 24rpx;
        }
    }
    .bg {
        position: fixed;
        z-index: -1;
        left: 0;
        right: 0;
        top: 0;
        width: 100%;
        height: 100%;
    }
    .smart_pay {
        height: 50rpx;
        background: linear-gradient(90deg, #3800b3 0%, #655b82 100%);
        margin: 20rpx 28rpx;
        border-radius: 20rpx;
        padding: 0 20rpx;
        color: #fff;
        line-height: 50rpx;
        .smart_rule {
            display: inline-block;
            width: 36rpx;
            height: 36rpx;
            line-height: 30rpx;
            margin: 0 0 0 10rpx;
            vertical-align: text-top;
        }
        .smart_X {
            position: absolute;
            right: 20rpx;
            top: 5rpx;
            width: 32rpx;
            height: 32rpx;
        }
    }
   .fill-height {
        height: 168rpx;
    }
    .bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        background: #373737;
        height: 168rpx;
        padding-bottom: 40rpx;
		z-index: 20;
        .bottom-btns {
            height: 128rpx;
            .btnItem {
                font-size: 28rpx;
                font-family: Source Han Sans CN, Source Han Sans CN;
                font-weight: 700;
                color: #ffffff;
                line-height: 44rpx;
                background-size: 100% 100%;
                padding: 20rpx 12rpx;
                text-align: center;
                flex: 1;
                margin: 0 13rpx;
                .text {
                    display: inline-block;
                    font-size: 18rpx;
                    line-height: 18rpx;
                }
                &:first-child {
                    margin-left: 0;
                }
                &:last-child {
                    margin-right: 0;
                }
            }
        }
        .image {
            height: 108rpx;
            width: 0;
        }
    }
    .sw,
    .mj,
    .ck {
        position: fixed;
        right: 0rpx;
        width: 84rpx;
    }
    .mj {
        bottom: 800rpx;
    }
    .sw {
        bottom: 540rpx;
        width: 128rpx;
        height: 128rpx;
    }
    .ck {
        bottom: 690rpx;
    }
    .record {
        position: fixed;
        left: 0rpx;
        width: 96rpx;
        bottom: 670rpx;
    }
    .rule {
        position: fixed;
        left: 10rpx;
        bottom: 800rpx;
        width: 84rpx;
    }
    .refresh {
        position: fixed;
        right: 0rpx;
        width: 84rpx;
        bottom: 580rpx;
    }
    .lock {
        position: fixed;
        left: 10rpx;
        width: 84rpx;
        height: 96rpx;
        bottom: 540rpx;
    }
    .Inclusive {
        position: fixed;
        right: 0rpx;
        bottom: 460rpx;
        width: 96rpx;
        height: 96rpx;
    }
    .lockTimeBox {
        display: flex;
        align-items: center;
        padding: 20rpx;
        background-color: #fde9dd;
        padding-bottom: 0;
        font-size: 24rpx;
        .lockTimeBarBox {
            position: relative;
            flex: 1;
            height: 60rpx;
            .line {
                width: 4rpx;
                height: 24rpx;
                background: #fead33;
                border-radius: 4rpx;
                left: 0;
                right: 0;
                bottom: 16rpx;
                position: absolute;
            }
            .text {
                position: absolute;
                line-height: 26rpx;
                width: 54rpx;
                text-align: center;
                font-size: 20rpx;
                background: #000;
                color: #fff;
                top: -20rpx;
                &::after {
                    content: '';
                    display: block;
                    border: 8rpx solid;
                    border-color: #000 transparent transparent transparent;
                    position: absolute;
                    bottom: -16rpx;
                    left: 20rpx;
                    z-index: 100;
                }
            }
        }
        .lockTime {
            border-radius: 16rpx;
            height: 16rpx;
            background: rgba(255, 255, 255, 0.63);
            position: absolute;
            bottom: 20rpx;
            left: 0;
            right: 0;
            overflow: hidden;
            .processBar {
                position: absolute;
                left: 0;
                height: 16rpx;
                background: linear-gradient(270deg, #fec433 0%, #fead33 100%);
            }
        }
    }
</style>
