<template>
    <view class="container">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <!-- 首页自定义导航栏 -->
        <view class="search-input sticky-top">
            <view class="search-content" @click="handleToSearch">
                <text class="iconfont icon-sousuo"></text>
                <view class="search-text">搜索商品</view>
            </view>
        </view>
        <!-- 轮播图 -->
        <cm-banner
            :list="bannerList"
            :current="current"
            @change="index => (current = index)"
            @click="onSwiperClick"
        ></cm-banner>

        <!-- 金刚区菜单 -->
        <cm-navbar :modal="navbarList" @click="onNavbarClick"></cm-navbar>

        <!-- 加入我们 -->
        <view class="grid"></view>
        <view class="join-us">
            <image :src="staticUrl + 'icon-join-us.png'" class="join-icon"></image>
            <view class="join-content">
                <view class="join-label-title">呵呵商城福利群</view>
                <view class="join-label-text">进群第一时间得知优惠福利！</view>
            </view>
            <view class="join-button" @click="handleJoinUs">加入我们</view>
        </view>
        <view class="grid"></view>

        <!-- 优惠券专区 -->
        <view class="coupon-area" v-if="couponList.length > 0">
            <cm-floor-title title="优惠券专区" @click="onMoreCoupon"></cm-floor-title>
            <cm-coupon-area :couponList="couponList" @click="onCouponClick"></cm-coupon-area>
        </view>

        <!-- 楼层区域 -->
        <view class="cm-floor" v-for="floorData in floorList" :key="floorData.id">
            <cm-floor-template
                :floorData="floorData"
                @onBannerClick="onBannerClick"
                @more="onMoreProduct"
            ></cm-floor-template>
        </view>

        <!-- 优惠券活动弹窗 -->
        <cm-active-alert></cm-active-alert>
    </view>
</template>

<script>
import { fetchHomeCarousel, fetchHomeNavbar, fetchHomeFloorData, fetchHomeCouponList } from '@/services/api/home.js'
import { fetchCouponDisplay } from '@/services/api/coupon.js'
import { fetchProductFloorList } from '@/services/api/goods.js'
import { shareDataResult } from '@/common/share.helper.js'
import { mapActions, mapGetters } from 'vuex'

export default {
    data() {
        return {
            isRequest: true,
            bannerData: [],
            navbarList: [],
            floorInfo: {},
            floorList: [],
            couponList: [],
            current: 0,
            isRefresh: false,
            couponTipStr: ''
        }
    },
    computed: {
        ...mapGetters(['userId', 'accessToken']),
        bannerList() {
            return this.bannerData.map(item => item.image)
        }
    },
    onPullDownRefresh() {
        this.initHomeInfo()
    },
    onShareAppMessage() {
        const shareData = { type: 0, inviteUserId: this.userId }
        return shareDataResult(shareData)
    },
    onShow() {
        this.fetchCartKindCount() // 购物车商品数量
        this.checkCouponAlert() // 优惠券弹窗
    },
    onLoad() {
        this.initHomeInfo()
    },
    methods: {
        ...mapActions('cart', ['fetchCartKindCount']),
        ...mapActions('coupon', ['checkCouponAlert']),

        // 搜索
        handleToSearch() {
            this.$router.navigateTo('goods/goods-search')
        },

        // 金刚区菜单导航
        onNavbarClick(navbar) {
            this.$setStorage('NAVBAR', { type: 'navbar', id: navbar.id })
            this.$router.navigateTo('goods/goods-list')
        },

        // 更多优惠券
        onMoreCoupon() {
            this.$router.navigateTo('coupon/coupon-receive')
        },

        // 优惠券点击（领取）
        onCouponClick(coupon) {
            coupon = { ...coupon }
            if (coupon.controlType === 'receive') {
                const index = this.couponList.findIndex(item => item.couponId === coupon.couponId)
                this.couponList.splice(index, 1)
                coupon.controlType = 'use'
                this.$set(this.couponList, index, coupon)
            }
        },

        // 商品楼层轮播图点击事件
        onBannerClick(banner) {
            if (!banner.link) return
            this.$router.navigateTo(`others/web-view?websit=${banner.link}`)
        },

        // 更多商品
        onMoreProduct(floor) {
            this.$setStorage('NAVBAR', { type: 'floor', id: floor.id })
            this.$router.navigateTo('goods/goods-list')
        },

        // 加入我们
        handleJoinUs() {
            this.$router.navigateTo('others/join-us')
        },

        // 初始化首页信息
        initHomeInfo() {
            this.fetchCarousel()
            this.fetchNavbar()
            this.fetchFloorData()
            this.fetchCouponList()
        },

        // 轮播图跳转
        onSwiperClick(index) {
            const link = this.bannerData[index].link
            if (!link) return
            this.$router.navigateTo(`others/web-view?websit=${link}`)
        },

        // 获取轮播图列表
        async fetchCarousel() {
            try {
                const resultCarousel = await fetchHomeCarousel() // 轮播图

                this.bannerData = resultCarousel.data
            } catch (e) {
                console.log('获取轮播图列表失败')
            }
        },

        // 获取金刚区菜单
        async fetchNavbar() {
            try {
                const resultNavbar = await fetchHomeNavbar() // 轮播图
                this.navbarList = resultNavbar.data
            } catch (e) {
                console.log('获取金刚区菜单失败')
            }
        },

        // 获取楼层信息
        async fetchFloorData() {
            try {
                const resultFloorData = await fetchHomeFloorData({ userId: this.userId }) // 商品楼层信息
                this.floorInfo = resultFloorData.data.page
                this.floorList = resultFloorData.data.floorList
                // 楼层信息加载成功
                this.isRequest = false
                uni.stopPullDownRefresh()
            } catch (e) {
                console.log('获取楼层信息失败')
            }
        },

        // 获取优惠券列表
        async fetchCouponList() {
            try {
                this.fetchCouponDisplay() // 获取可领取优惠券类型
                const resultCouponData = await fetchHomeCouponList({ userId: this.userId })
                this.couponList = [
                    ...resultCouponData.data.map(item => {
                        item.controlType = 'receive'
                        return item
                    }),
                    ...this.generateCouponTips()
                ]
            } catch (e) {
                console.log('获取优惠券列表失败')
            }
        },

        // 获取可领取优惠券类型
        async fetchCouponDisplay() {
            try {
                const res = await fetchCouponDisplay({ userId: this.userId })
                this.couponTipStr = res.data
            } catch (e) {
                console.log('获取优惠券类型失败')
            }
        },

        // 生成优惠券说明
        generateCouponTips() {
            const result = [
                {
                    type: 'tip',
                    id: 1,
                    name: '好友邀请券福利'
                },
                {
                    type: 'tip',
                    id: 2,
                    name: '好友消费券福利'
                },
                {
                    type: 'tip',
                    id: 3,
                    name: '分享券福利'
                }
            ]
            return result.filter(item => this.couponTipStr.indexOf(item.id.toString()) > -1)
        }
    }
}
</script>

<style lang="scss" scoped>
.grid {
    height: 24rpx;
    background-color: #f7f7f7;
}

.container {
    min-height: 100vh;
    background: url(https://static.caimei365.com/app/mini-hehe/icon/icon-index-bg.png) no-repeat top center;
    background-size: 750rpx auto;
    background-position-y: -220rpx;

    .search-input {
        width: 100%;
        padding: 24rpx;
        box-sizing: border-box;
        background: linear-gradient(180deg, #fa55bf 0%, #f8458b 100%);

        .search-content {
            @extend .cm-flex-center;
            justify-content: flex-start;
            width: 702rpx;
            height: 66rpx;
            border-radius: 33rpx;
            color: #8a8a8a;
            background: #fff;
            box-sizing: border-box;
            padding: 0 24rpx;
            .iconfont {
                font-size: 34rpx;
                margin-right: 12rpx;
            }
            .search-text {
                font-size: 24rpx;
            }
        }
    }

    // 加入我们
    .join-us {
        @extend .cm-flex-between;
        padding: 24rpx;
        background-color: #fff;

        .join-icon {
            width: 136rpx;
            height: 136rpx;
            display: block;
        }

        .join-content {
            @extend .cm-flex-center;
            flex-direction: column;
            align-items: flex-start;

            .join-label-title {
                font-size: 30rpx;
                font-weight: bold;
                color: #333333;
                margin-bottom: 24rpx;
            }
            .join-label-text {
                font-size: 24rpx;
                color: #333333;
            }
        }
        .join-button {
            width: 136rpx;
            height: 56rpx;

            text-align: center;
            line-height: 56rpx;
            font-size: 26rpx;
            font-weight: 400;
            color: #ffffff;

            background: #ff457b;
            border-radius: 8rpx;
        }
    }

    // 优惠券专区
    .coupon-area {
        padding-top: 24rpx;
    }

    .cm-floor {
        margin-bottom: 60rpx;
    }
}
</style>
