<template>
    <view class="pageWrapper">
        <tabbar2 custom-class=" " :tabs="tabs" @change="clickTab" />
        <scroll-view
            class="wrapperScroll"
            style="height: calc(100vh - 500rpx)"
            scroll-y
            refresher-enabled
            refresher-default-style="white"
            @refresherrefresh="pullRefresh"
            :refresher-triggered="refreshing"
            @scrolltolower="loadMore"
        >
            <view v-if="tableData && tableData.length > 0" class="" style="padding: 20rpx 0">
                <view
                    v-for="(item, index) in tableData"
                    :key="item.id"
                    class="cell"
                    @click="showDetail(item)"
                >
                    <view class="header">
                        <view class="titleBox" @click.stop="choose(item)">
                            <template v-if="item.safeFlag !== 1">
                                <view class="checkBox" :class="{ check: !!checkMap[item.id] }">
                                    <view class="cuIcon-check"></view>
                                </view>
                            </template>
                            <image class="icon-title" :src="LEVEL_MAP[item.level].titleText" />
                        </view>
                        <view
                            class="lockBox"
                            @click.stop="
                                item.safeFlag !== 1 ? moveToBx(item, index) : moveOutBx(item, index)
                            "
                        >
                            {{ item.safeFlag !== 1 ? '锁定' : '解锁' }}
                            <image
                                :src="item.safeFlag !== 1 ? ossurl.mine.lock : ossurl.mine.unlock"
                                webp
                                class="lockImage"
                            />
                        </view>
                    </view>
                    <view class="flex-align paddingT14">
                        <image
                            class="icon flex-shrink0"
                            :src="item.spu.cover"
                            @click.stop="showGoodsDetail(item)"
                            mode="aspectFit"
                        />
                        <view class="flex1 marginL12">
                            <view
                                class="font4 bold paddingB13"
                                style="-webkit-line-clamp: 2;word-break: break-all;text-overflow：ellipsis"
                            >
                                {{ item.spu.name }}
                            </view>
                            <view class="flex-align-between">
                                <view class="font3" style="opacity: 0.8">
                                    从
                                    <text v-if="item.fromRelationType === 'LUCK'">宝箱</text>
                                    <text v-else-if="item.fromRelationType === 'TRADE'">魔换</text>
                                    <text v-else-if="item.fromRelationType === 'LUCK_ROOM'">
                                        福利房
                                    </text>
                                    <text v-else-if="item.fromRelationType === 'LUCK_KING'">
                                        魔王战
                                    </text>
                                    <text v-else-if="item.fromRelationType === 'LUCK_WHEEL'">
                                        魔天轮
                                    </text>
                                    <text v-else-if="item.fromRelationType === 'SUBSTITUTE'">
                                        置换
                                    </text>
                                    <text v-else-if="item.fromRelationType === 'ACTIVITY'">
                                        活动
                                    </text>
                                    <text v-else-if="item.fromRelationType === 'DOLL_MACHINE'">
                                        娃娃机
                                    </text>
                                    <text v-else>其他</text>
                                    获得
                                </view>
                                <!-- <view v-if="hide" class="flex-align-between">
                                    <view class="font4 radius2" v-if="item.magicAmount > 0">
                                        可兑换
                                        <text :style="{ color: '#FEC433' }">
                                            {{ item.magicAmount }}
                                        </text>
                                        源石
                                    </view>
                                    <view v-else class="font4 radius2">不可兑换</view>
                                </view> -->
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <empty v-if="isEmpty" :top="200" />
        </scroll-view>
        <image
            v-if="tableData && tableData.length > 0 && hide && total > 5"
            :src="ossurl.mine.exchange"
            webp
            class="convert_all"
            @click.stop="showConvertAll"
        />

        <view v-if="tableData && tableData.length > 0" class="bottom paddingX10">
            <view class="bottom-btns flex-align-around">
                <view v-if="type != 1" class="relative btnBox" @click="showCheckout">
                    <view>立即提货</view>
                    <view class="text">5件包邮</view>
                </view>
                <!-- <view v-if="type != 1 && hide" class="relative btnBox2" @click="showConvertConfirm">
                    <view>兑换源石</view>
                    <view class="text">可抵扣支付</view>
                </view> -->
            </view>
            <view class="flex-align-center font2 paddingT8" style="color: #9e9e9e">
                已选
                <text class="font2 paddingX1" style="color: #000">
                    {{ Object.values(checkMap).length }}
                </text>
                件商品
            </view>
        </view>
        <convert-confirm ref="convertConfirmRef" @convert-success="onConvertSuccess" />
        <convert-all ref="convertAllRef" @convert-success="onConvertSuccess" />
        <gift-all ref="giftAllRef" @gift-success="onGiftSuccess" />
        <checkout ref="checkoutRef" @success="onTakeSuccess" />
        <gift-confirm ref="giftConfirmRef" @success="onGiftConfirmSuccess" />
        <goods-detail ref="goodsDetailRef" />
    </view>
</template>
<script>
    import pageMixin from './../../mixin/page'
    import empty from '@/components/empty'
    import { LEVEL_MAP } from '@/utils/config'
    import convertConfirm from './convert_confirm'
    import convertAll from './convert_all'
    import giftAll from './gift_all'
    import checkout from './checkout'
    import ossurl from '@/utils/ossurl'
    import goodsDetail from './goods_detail'
    import { throttle } from '@/utils'
    import tabbar2 from '@/components/tabbar2'
    import giftConfirm from './gift_confirm'

    const Tabs = [
        { title: '全部', value: '' },
        { title: '普通', value: 'D' },
        { title: '隐藏', value: 'C' },
        { title: '欧皇', value: 'B' },
        { title: '超神', value: 'A' },
        { title: '其他', value: 'OTHER' }
    ]
    export default {
        mixins: [pageMixin],
        components: {
            empty,
            convertConfirm,
            checkout,
            goodsDetail,
            convertAll,
            tabbar2,
            giftAll,
            giftConfirm
        },
        props: {
            type: {
                default: 0,
                type: Number
            }
        },
        data() {
            return {
                ossurl,
                LEVEL_MAP,
                refreshing: false,
                tab: Tabs[0],
                tabs: Tabs,
                checkMap: {},
                total: 0
            }
        },
        computed: {
            top() {
                let height = this.$store.state.systemInfo.statusBarHeight + 36 + 50 + 10 + 40
                return height
            },
            itemWidth() {
                let width = this.$store.state.systemInfo.screenWidth
                width = (width - 8 - 40) / 3
                let height = (165 / 109) * width
                return { width, height }
            },
            hide() {
                return !this.$store.state.hide
            }
        },
        mounted() {
            this.refresh(true)
        },
        methods: {
            pullRefresh() {
                this.refreshing = true
                this.refresh()
            },
            clickTab(item) {
                this.tab = item
                this.refresh(true)
            },
            async getSumInventory() {
                const res = await this.$service.award.getSumInventory()
                this.total = res
            },
            async loadData(loading = false) {
                this.getSumInventory()
                const res = await this.$service.award.store(
                    this.pageNum,
                    this.pageSize,
                    '',
                    this.tab.value,
                    loading
                )
                setTimeout(() => {
                    this.refreshing = false
                }, 1000)
                return res
            },
            choose(item) {
                if (item.safeFlag == 1) return
                if (!!this.checkMap[item.id]) {
                    delete this.checkMap[item.id]
                } else {
                    this.checkMap[item.id] = item
                }
                this.checkMap = { ...this.checkMap }
            },
            forceChoose(item, flag, refresh = true) {
                if (flag) {
                    this.checkMap[item.id] = item
                } else {
                    delete this.checkMap[item.id]
                }
                if (refresh) {
                    this.checkMap = { ...this.checkMap }
                }
            },
            checkAll() {
                if (!this.tableData) return
                let flag = this.tableData.every((item) => {
                    return item.safeFlag == 1 || !!this.checkMap[item.id]
                })
                if (flag) {
                    this.checkMap = {}
                } else {
                    this.tableData.forEach((item) => {
                        item.safeFlag != 1 && this.forceChoose(item, true, false)
                    })
                    this.checkMap = { ...this.checkMap }
                }
            },
            async showConvertConfirm() {
                for (let x in this.checkMap) {
                    let item = this.checkMap[x]
                    if (item.magicAmount <= 0) {
                        delete this.checkMap[x]
                    }
                }
                this.checkMap = { ...this.checkMap }
                let goods = Object.values(this.checkMap)
                if (goods.length === 0) {
                    this.$message.warn('请至少选择一个商品！')
                    return
                }
                const res = await this.$service.award.convertPreview(goods.map((item) => item.id))
                if (res) {
                    this.$refs.convertConfirmRef.show(goods, res.totalMagicAmount)
                }
            },
            showGiftAll() {
                const goods = Object.values(this.checkMap)
                if (goods.length === 0) {
                    this.$message.warn('请至少选择一个商品！')
                    return
                }
                const ids = goods.map((obj) => obj.id)
                this.$refs.giftAllRef.show(ids)
            },
            onConvertSuccess() {
                this.checkMap = {}
                this.refresh(true)
                this.$emit('convertSuccess')
                this.$message.success('兑换成功')
            },
            async showCheckout() {
                let goods = Object.values(this.checkMap)
                if (goods.length === 0) {
                    this.$message.warn('请至少选择一个商品！')
                    return
                }
                const res = await this.$service.award.takePreview(goods.map((item) => item.id))
                if (res) {
                    this.$refs.checkoutRef.show(res, goods)
                }
            },
            onTakeSuccess() {
                this.checkMap = {}
                this.refresh(true)
                this.$emit('takeSuccess')
                this.$message.success('提货成功')
            },
            onGiftSuccess(data, param) {
                const goods = Object.values(this.checkMap)
                this.$refs.giftConfirmRef.show(data, goods, param)
            },
            onGiftConfirmSuccess() {
                this.checkMap = {}
                this.refresh(true)
                this.$message.success('转赠成功')
            },
            showGoodsDetail(item) {
                this.$refs.goodsDetailRef.show(item.spu)
            },
            moveToBx(item, index) {
                throttle.call(() => {
                    this.realMoveToBx(item, index)
                })
            },
            async realMoveToBx(item, index) {
                const res = await this.$service.award.moveToSaveStore([item.id])
                if (res) {
                    item.safeFlag = 1
                    this.$set(this.tableData, index, { ...item })
                    // if (this.checkMap) {
                    //     this.checkMap = { ...this.checkMap }
                    // }
                }
            },
            moveOutBx(item, index) {
                throttle.call(() => {
                    this.realMoveOutBx(item, index)
                })
            },
            async realMoveOutBx(item, index) {
                const res = await this.$service.award.moveOutSaveStore([item.id])
                if (res) {
                    item.safeFlag = 0
                    this.$set(this.tableData, index, { ...item })
                }
            },
            showSell() {
                // this.$message.alert('敬请期待')
                let goods = Object.values(this.checkMap)
                if (goods.length === 0) return
                this.checkMap = {}
                this.$cache.set(this.$cache.key.STORE_SELL, goods)
                this.$router.push('sell_create_more')
            },
            showDetail(item) {
                if (item.safeFlag == 0&&item.magicAmount > 0) {
                    this.$router.push('store_detail', {
                        id:item.id
                    })
                }
            },
            async showConvertAll() {
                const res = await this.$service.award.convertAllPreview()
                if (res) {
                    let array = res.filter((item) => item.statistic.count > 0)
                    if (!array || array.length === 0) {
                        this.$message.alert('没有可兑换的普通和隐藏款')
                        return
                    }
                    this.$refs.convertAllRef.show(array)
                }
            }
        }
    }
</script>
<style lang="scss" scoped>
    .pageWrapper {
        padding: 0rpx 20rpx;
    }
    .bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        height: 212rpx;
        background-color: #fff;
        .bottom-btns {
            height: 100rpx;
            text-align: center;
            color: #000;
            .btnBox {
                padding-top: 8rpx;
                width: 326rpx;
                height: 80rpx;
                background: #fff7e3;
                border-radius: 40rpx;
            }
            .btnBox2 {
                padding-top: 8rpx;
                width: 326rpx;
                height: 80rpx;
                background: #fec433;
                border-radius: 40rpx;
            }
            .text {
                text-align: center;
                font-size: 20rpx;
                color: #735200;
            }
        }
        .image {
            height: 108rpx;
            width: 0;
        }
    }
    .cell {
        background: #ffffff;
        border-radius: 12rpx;
        border: 2rpx solid rgba(255, 255, 255, 0.4);
        padding: 30rpx;
        margin-bottom: 20rpx;
        position: relative;
        overflow: hidden;
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
            padding-bottom: 28rpx;
            .titleBox {
                display: flex;
                align-items: center;
            }
            .lockBox {
                display: flex;
                align-items: center;
                font-size: 24rpx;
                font-family: Source Han Sans, Source Han Sans;
                font-weight: 350;
                color: #999999;
            }
            .lockImage {
                width: 48rpx;
                height: 48rpx;
            }
        }
        .icon {
            width: 180rpx;
            height: 180rpx;
            border-radius: 10rpx;
        }
        .icon-title {
            width: 90rpx;
            height: 32rpx;
            // margin-left: -18rpx;
        }

        .btn-bx {
            width: 180rpx;
            height: 40rpx;
            background: linear-gradient(90deg, #2affff 0%, #4d70f2 100%);
            border-radius: 20rpx;
        }
        .safe-flag {
            width: 192rpx;
            height: 120rpx;
            position: absolute;
            right: 32rpx;
        }
    }
    .check-all {
        width: 120rpx;
        height: 120rpx;
        position: fixed;
        bottom: 388rpx;
        right: 0;
    }
    .convert_all {
        width: 68rpx;
        height: 98rpx;
        position: fixed;
        bottom: 600rpx;
        right: 20rpx;
    }

    .checkBox {
        border: 4rpx solid #000000;
        background-color: #fff;
        color: #fff;
        width: 32rpx;
        border-radius: 4rpx;
        margin-right: 12rpx;
        height: 32rpx;
        text-align: center;
        line-height: 28rpx;
        font-size: 24rpx;
        &.check {
            background: #fec433;
            border-color: #fec433;
            color: #000;
        }
    }
</style>
