<template>
    <view class="cart">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <view class="sticky-top">
            <!-- 自定义顶部 -->
            <cm-header
                :rightButton="null"
                :leftButtonGroup="leftButtonGroup"
                title="购物车"
                @leftClick="handleLeftClick"
                @rightClick="handleRightClick"
            ></cm-header>
            <view style="height: 8rpx;background-color: #fff;"></view>
            <template v-if="!isDeleted && (shopList.length !== 0 || expiredProducts.length !== 0)">
                <!-- 顶部 -->
                <view class="goods-total">
                    <view class="total">共{{ kindCount }}件商品</view>
                    <tui-button
                        :size="24"
                        width="88rpx"
                        height="42rpx"
                        shape="circle"
                        :plain="true"
                        type="base"
                        @click="isDeleted = true"
                    >
                        删除
                    </tui-button>
                </view>
                <view class="receive-coupon">
                    <view class="tip-text" v-text="couponTipText"></view>
                    <tui-button
                        :size="24"
                        width="88rpx"
                        height="42rpx"
                        shape="circle"
                        type="base"
                        @click="visiable = true"
                    >
                        领券
                    </tui-button>
                </view>
            </template>
        </view>
        <!-- 购物车列表为空 -->
        <template v-if="shopList.length === 0 && expiredProducts.length === 0">
            <tui-no-data :imgUrl="staticUrl + 'icon-empty-cart.png'" :imgHeight="230" :imgWidth="290">
                <view class="empty-tip">购物车空空的，快去逛逛吧~</view>
            </tui-no-data>
        </template>
        <template v-else>
            <!-- 有效商品 -->
            <view class="supplier-area" v-for="item in shopList" :key="item.shopId">
                <cm-cart-supplier-area
                    :shopInfo="item"
                    @change="checkedProductChange"
                    @countChange="onCountChange"
                    ref="supplierArea"
                ></cm-cart-supplier-area>
            </view>
            <!-- 失效商品 -->
            <view class="supplier-area" v-if="expiredProducts.length > 0">
                <cm-cart-expired-area :expiredList="expiredProducts"></cm-cart-expired-area>
            </view>
            <view style="height: 100rpx;"></view>
            <!-- 安全区域 -->
            <cm-safe-area-bottom></cm-safe-area-bottom>
            <!-- 购物车导航 -->
            <cm-cart-navbar
                :safeArea="true"
                :isCheckedAll="isChekedAll"
                :isDeleted="isDeleted"
                :data="navbarData"
                @all="onCheckedAll"
                @submit="onSumit"
                @cancel="isDeleted = false"
                @remove="removeModal = true"
            ></cm-cart-navbar>
        </template>

        <!-- 优惠券列表 -->
        <cm-coupon-popup
            :visiable="visiable"
            :list="couponList"
            :couponTabs="couponTabs"
            :hasSafeArea="true"
            @close="visiable = false"
            @change="onCouponChange"
            @couponClick="onCouponClick"
            hasTabs="true"
            translateY="34px"
        ></cm-coupon-popup>
        <!-- 确认弹框 -->
        <tui-modal :show="removeModal" content="确认删除选中的商品吗？" @click="onConfirmRemove"></tui-modal>
    </view>
</template>

<script>
import { fetchCartInfo } from '@/services/api/cart.js'
import { fetchCouponListByProductIds } from '@/services/api/coupon.js'
import { arrayUnique } from '@/common/utils.js'
import { mapGetters, mapActions } from 'vuex'
import CouponUtils from '@/common/couponUtils.js'
// 业务帮助函数
import {
    totalAllCheckedProduct,
    computeTotalPrice,
    initFormatCouponList,
    makeCouponUseTip
} from '@/common/business.helper.js'

const resetData = () => ({
    leftButtonGroup: [
        {
            icon: 'icon-daohangfanhui',
            color: '#333'
        },
        {
            icon: 'icon-fanhuishouye',
            color: '#333'
        }
    ],

    isRequest: true,
    isDeleted: false,
    expiredProducts: [], // 失效商品列表
    shopList: [], // 供应商&&商品列表
    checkedShopMap: {},
    isChekedAll: false,
    removeModal: false,

    // 商品价格
    checkedProductList: [],
    allPrice: 0, // 商品总价

    // 优惠券列表
    visiable: false,
    currentTab: 0,
    receiveCouponList: [], // 已领取优惠券
    ableCouponList: [], // 可领取优惠券
    couponTabs: [],
    currentCoupon: null,
    nextCoupon: null,
    couponTipText: '', // 可用优惠券提示

    // 保存变动
    changeRef: null
})

export default {
    data() {
        return resetData()
    },
    computed: {
        ...mapGetters(['userId', 'kindCount']),
        couponList() {
            return this.currentTab === 0 ? this.receiveCouponList : this.ableCouponList
        },
        navbarData() {
            const result = {
                finallyPrice: 0, // 实际应付
                couponAmount: 0,
                allPrice: 0,
                discountedPrice: 0,
                count: 0
            }

            if (this.currentCoupon) {
                result.couponAmount = this.currentCoupon.couponAmount
                result.discountedPrice = this.currentCoupon.couponAmount
            }

            result.allPrice = this.allPrice

            if (this.allPrice - result.discountedPrice > 0) {
                result.finallyPrice = this.allPrice - result.couponAmount
            }

            result.count = this.checkedProductList.length

            console.log(result)

            return result
        }
    },
    onPullDownRefresh() {
        this.resetData()
        this.fetchCartInfo()
    },
    onShow() {
        this.resetData()
        this.fetchCartInfo()
    },
    methods: {
        // 自定义导航触发事件
        handleLeftClick() {},
        handleRightClick() {},
        headerNavInit(info) {
            this.headerNavHeight = info.height
        },
        ...mapActions('cart', ['removeFromCart']),

        // 初始化数据
        resetData() {
            const data = resetData()
            for (let key in data) {
                this[key] = data[key]
            }
        },

        // 提交订单
        onSumit() {
            if (this.checkedProductList.length <= 0) {
                return this.$toast.error('请选择商品')
            }
            const params = {}
            params.allPrice = this.allPrice
            params.allCount = this.checkedProductList.length
            params.cartIds = this.checkedProductList.map(product => product.cartId)
            params.productIds = this.checkedProductList.map(product => product.productId)
            params.productCount = ''
            uni.setStorageSync('COMMIT_CART_INFO', params)
            this.$router.navigateTo('order/order-create')
        },

        // 优惠券列表类型更换
        onCouponChange(index) {
            this.currentTab = index
        },
        // 优惠券点击事件
        onCouponClick(coupon) {
            if (coupon.controlType === 'receive') {
                this.fetchCouponList()
            } else {
                this.visiable = false
            }
        },
        // 设置couponTab数据
        makeCouponTabs() {
            return [
                {
                    name: '已领取优惠券',
                    num: this.receiveCouponList.length,
                    isDot: false,
                    disabled: false
                },
                {
                    name: '可领取优惠券',
                    num: this.receiveCouponList.ableCouponList,
                    isDot: false,
                    disabled: false
                }
            ]
        },

        // 获取购物车商品可用优惠券
        async fetchCouponList() {
            const productIds = []
            this.shopList.forEach(shop => shop.productList.forEach(product => productIds.push(product.productId)))
            try {
                const res = await fetchCouponListByProductIds({ userId: this.userId, productIds: productIds.join(',') })
                this.receiveCouponList = initFormatCouponList(res.data.receiveCouponList, 'search', true)
                this.ableCouponList = initFormatCouponList(res.data.ableCouponList, 'receive', true)
                this.couponTabs = this.makeCouponTabs()
            } catch (e) {
                console.log(e)
            }
        },

        // 获取购物车信息
        async fetchCartInfo() {
            try {
                const res = await fetchCartInfo({ userId: this.userId })
                this.expiredProducts = res.data.products
                this.shopList = res.data.shopList
                // 获取优惠券列表
                if (this.shopList.length > 0) {
                    // 获取优惠券列表
                    this.fetchCouponList()
                }
                return res
            } catch (e) {
                return e
            } finally {
                this.isRequest = false
            }
        },

        // 确认删除
        async onConfirmRemove({ index }) {
            if (!index) return (this.removeModal = false)
            const ids = this.getCheckedProductIds()
            const cartIds = this.shopList.reduce((prev, item) => {
                item.productList.forEach(prod => {
                    if (ids.includes(prod.productId.toString())) {
                        prev.push(prod.cartId)
                    }
                })
                return prev
            }, [])
            try {
                await this.removeFromCart(cartIds)
                this.fetchCartInfo()
            } catch (e) {
                console.log(e)
            } finally {
                this.isDeleted = false
                this.removeModal = false
            }
        },

        // 选中/取消全部商品
        onCheckedAll() {
            if (this.isChekedAll) {
                this.$refs.supplierArea.forEach(item => item.unSelectAll())
            } else {
                this.$refs.supplierArea.forEach(item => item.selectAll())
            }
        },

        // 选中商品变化
        checkedProductChange(e) {
            this.changeRef = e
            this.handleCartManager()
        },

        // 修改商品checked属性
        updatePorudctChecked(row) {
            const shopInfo = this.shopList.find(item => row.shopId === item.shopId)
            if (!shopInfo) return
            shopInfo.productList.forEach(item => {
                if (row.checkedList.includes(item.productId.toString())) {
                    this.$set(item, 'checked', true)
                } else {
                    this.$set(item, 'checked', false)
                }
            })
        },

        // 购物车数据处理器
        handleCartManager() {
            if (!this.changeRef) return
            this.updatePorudctChecked(this.changeRef)
            // 保存选中商品id与供应商id的k-v关系
            this.$set(this.checkedShopMap, this.changeRef.shopId, this.changeRef.checkedList)
            this.isChekedAll = this.validateIsChekedAll()
            // 获取已选商品列表
            this.checkedProductList = totalAllCheckedProduct(this.shopList)
            // 计算商品总价
            this.allPrice = computeTotalPrice(this.checkedProductList)
            const couponUtils = new CouponUtils(this.receiveCouponList, this.checkedProductList)
            this.currentCoupon = couponUtils.bestCoupon
            this.nextCoupon = couponUtils.secondCoupon
            this.couponTipText = makeCouponUseTip(this.currentCoupon, this.nextCoupon, this.allPrice)
        },

        // 商品数量变化
        async onCountChange(e) {
            await this.$store.dispatch('cart/updateProductCount', {
                cartId: e.cartId,
                productCount: e.count
            })
            await this.fetchCartInfo()
            this.handleCartManager()
        },

        // 验证是否全选
        validateIsChekedAll() {
            return this.shopList.every(item => {
                const checkedList = this.checkedShopMap[item.shopId] || []
                return item.productList.length === checkedList.length
            })
        },

        // 获取已选商品id列表
        getCheckedProductIds() {
            const list = []
            for (let key in this.checkedShopMap) {
                list.push(...this.checkedShopMap[key])
            }
            return list
        }
    }
}
</script>

<style scoped lang="scss">
.goods-total {
    @extend .cm-flex-between;
    background: #f7f7f7;
    padding: 0 24rpx;
    height: 80rpx;
    .total {
        font-size: 30rpx;
        color: #333;
    }
}

.receive-coupon {
    @extend .cm-flex-between;
    background: #fff;
    padding: 0 24rpx;
    height: 80rpx;
    .tip-text {
        font-size: 26rpx;
        color: #ff457b;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.supplier-area {
    margin-bottom: 24rpx;
}

.remove-view {
    position: relative;
    width: 100vw;
    height: 100vh;
    box-sizing: border-box;

    .shop-list {
        height: 100%;
        background-color: #f7f7f7;
        box-sizing: border-box;
    }

    .icon {
        margin-right: 6rpx;
        text {
            display: inline-block;
            font-size: 30rpx;
            margin-left: 4rpx;
            color: #333;
        }
    }

    .navbar {
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        z-index: 98;
        min-height: 100rpx;
        box-sizing: border-box;
        padding: 0 24rpx;
        background: #fff;
        border-top: 1rpx solid #eee;

        .content {
            height: 100rpx;
            @extend .cm-flex-between;
            .control {
                width: 444rpx;
                @extend .cm-flex-between;
            }
        }
    }
}
</style>
