<template>
    <app-layout title="购物车">
        <view class="cart-tips">
            <widget-tips text="为什么会拆成多个订单?根据师傅服务能力与服务类型进行订单拆分" />
        </view>
        <view class="cart-container">
            <view class="cart-group" v-for="(item, index) in list" :key="index">
                <view class="group-title limit-line clamp-1" @click="checkGroup(index)">
                    <view class="group-checkbox">
                        <widget-check-box :size="50" :checked="item.checked" />
                    </view>
                    <view class="title">
                        <text>{{ item.name }}</text>
                    </view>
                </view>
                <view class="group-items">
                    <view class="cart-item" v-for="(v, i) in item.list" :key="i" @longpress="deleteCart(index, i)">
                        <view class="item-checkbox" @click="checkItem(index, i)">
                            <widget-check-box :size="50" :checked="v.checked" />
                        </view>
                        <view class="item-box">
                            <service-preview-item :data="v" />
                            <widget-count-modify
                                class="component-add"
                                min="1"
                                :init="v.number"
                                @change="changeNumber($event, { parentIndex: index, itemIndex: i })"
                            />
                        </view>
                    </view>
                </view>
                <view class="bottom-btn-box">
                    <view class="total-price">
                        <text class="text">合计：</text>
                        <text class="price">¥ {{ utils.formatNumber(item.total, 2) }}</text>
                    </view>
                    <view class="button" :class="{ active: item.total > 0 }" @click="createOrder(index)">
                        <text>去下单</text>
                    </view>
                </view>
            </view>
        </view>
    </app-layout>
</template>

<script>
import AppLayout from "@/components/layout/layout";
import WidgetTips from "@/components/widgets/tips";
import WidgetCheckBox from "@/components/widgets/checkbox";
import WidgetCountModify from "@/components/widgets/count-modify";
import ServicePreviewItem from "@/components/service/preview-item";
export default {
    name: "order-cart",
    data() {
        return {
            utils: this.$utils,
            list: [],
        };
    },
    components: {
        AppLayout,
        WidgetTips,
        WidgetCheckBox,
        WidgetCountModify,
        ServicePreviewItem,
    },
    onLoad() {
        this.$models.cart.list().then((list) => {
            list.forEach((item) => {
                let goods = [];
                item.good.forEach((v) => {
                    goods.push({
                        id: v.gid,
                        name: v.title,
                        times: v.post_hits,
                        cover: v.thumbnail,
                        price: v.money,
                        number: v.number,
                        checked: false,
                    });
                });
                this.list.push({
                    name: item.cate,
                    total: 0,
                    list: goods,
                    checked: false,
                });
            });
        });
    },
    onShow() {},
    onReady() {},
    onReachBottom() {},
    onPullDownRefresh() {},
    methods: {
        checkGroup(parentIndex) {
            let currentItem = this.list[parentIndex];
            let currentState = !currentItem.checked;
            currentItem.list.forEach((item, itemIndex) => {
                this.checkItem(parentIndex, itemIndex, currentState);
            });
        },
        // 选中单项
        checkItem(parentIndex, itemIndex, state) {
            let currentItem = this.list[parentIndex].list[itemIndex];
            let currentState = typeof state === "undefined" ? !currentItem.checked : state;
            if (currentItem.checked != currentState) {
                currentItem.checked = currentState;

                // 判断是否需要选中组
                let allChecked = true;
                this.list[parentIndex].list.forEach((item, index) => {
                    if (!item.checked) {
                        allChecked = false;
                    }
                });
                this.list[parentIndex].checked = allChecked;

                this.updateTotal(parentIndex);
            }
        },
        /**
         * 更新总价
         */
        updateTotal(parentIndex) {
            let currentItem = this.list[parentIndex],
                total = 0;
            currentItem.list.forEach((item) => {
                if (item.checked) {
                    total += item.price * item.number;
                }
            });
            currentItem.total = total;
        },
        /**
         * 改变数量
         */
        changeNumber(e, idx) {
            let currentItem = this.list[idx.parentIndex].list[idx.itemIndex];
            if (currentItem.number != e.value) {
                this.$models.cart.change(currentItem.id, e.type).then(() => {
                    this.$store.dispatch("cart/updateAll");
                    currentItem.number = e.value;
                    this.updateTotal(idx.parentIndex);
                });
            } else {
                this.$utils.toast("亲，不能再" + (e.type == "sub" ? "减少" : "增加") + "了~");
            }
        },
        /**
         * 删除购物车
         */
        deleteCart(parentIndex, itemIndex) {
            const that = this;
            uni.showModal({
                title: "确定删除该商品？",
                content: "数据删除后不可恢复，请谨慎操作！",
                complete(res) {
                    if (res.confirm) {
                        let parentItem = that.list[parentIndex];
                        let currentItem = parentItem.list[itemIndex];
                        that.$models.cart.delete(currentItem.id).then(() => {
                            that.$store.dispatch("cart/updateAll");
                            parentItem.list.splice(itemIndex, 1);
                            if (parentItem.list.length > 0) {
                                that.updateTotal(parentIndex);
                            } else {
                                that.list.splice(parentIndex, 1);
                            }
                        });
                    }
                },
            });
        },
        /**
         * 购物车下单
         */
        createOrder(parentIndex) {
            let orderdata = [];
            let currentItem = this.list[parentIndex];
            currentItem.list.forEach((item) => {
                if (item.checked) {
                    orderdata.push({
                        id: item.id,
                        count: item.number,
                    });
                }
            });
            if (orderdata.length > 0) {
                this.$utils.toPage("/pages/order/create?orderData=" + encodeURIComponent(JSON.stringify(orderdata)));
            }
        },
    },
};
</script>

<style lang="less" scoped>
.cart-tips {
    width: 710rpx;
    margin: 0 auto 24rpx auto;
}
.cart-container {
    width: 710rpx;
    margin: 0 auto;
}
.cart-group {
    width: 100%;
    margin-bottom: 22rpx;
    background-color: #ffffff;
}
.cart-group:last-child {
    margin-bottom: 0;
}
.group-title {
    width: 100%;
    box-sizing: border-box;
    padding: 22rpx;
    display: flex;
    align-items: center;
    .title {
        margin-left: 22rpx;
        font-size: 26rpx;
        font-weight: bold;
        color: #000000;
    }
}
.group-items {
    width: 100%;
    .cart-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 22rpx;
        margin-bottom: 50rpx;
    }
    .item-box {
        position: relative;
        width: 604rpx;
        .component-add {
            position: absolute;
            right: 0;
            bottom: 9rpx;
        }
    }
}
.bottom-btn-box {
    width: 670rpx;
    margin: 0 auto;
    border-top: 2rpx solid #e1e1e1;
    box-sizing: border-box;
    padding: 26rpx 0;
    display: flex;
    justify-content: space-between;
    .total-price {
        .text {
            font-size: 26rpx;
            color: #000000;
        }
        .price {
            font-size: 32rpx;
            color: #ec7655;
        }
    }
    .button {
        width: 183rpx;
        height: 54rpx;
        line-height: 54rpx;
        background: linear-gradient(-90deg, #8194f2, #8194f2);
        text-align: center;
        border-radius: 23rpx;
        font-size: 24rpx;
        color: #ffffff;
        opacity: 0.7;
    }
    .button.active {
        opacity: 1;
    }
}
.more {
    padding: 50rpx 0;
}
</style>