<template>
    <div class="shop-cart page_red" >
        <div class="cart-list" v-if="showList">
            <div class="bg" @click="closeList"></div>
            <div class="main">
                <div class="head">
                    <div class="l" @click="selectAllGoods">
                        <img
                            v-if="allSelect"
                            class="select"
                            :src="
                                theme === 2
                                    ? '/static/icon/select.png'
                                    : '/static/icon/select_red.png'
                            "
                        />
                        <div v-else class="select--null"></div>
                        <div class="text">全选</div>
                    </div>
                    <div class="r">
                        <!-- <i class="iconfont iconremove remove"></i>
                        <span>清空购物车</span> -->
                        <span class="close" @click="closeList">×</span>
                    </div>
                </div>
                <ul class="cart">
                    <li
                        class="cart__item"
                        v-for="(item, index) in cartList"
                        :key="index"
                    >
                        <img
                            v-if="item.active"
                            class="cart__select"
                            :src="
                                theme === 2
                                    ? '/static/icon/select.png'
                                    : '/static/icon/select_red.png'
                            "
                            @click.stop="selectGoods(item)"
                            alt
                        />
                        <div
                            v-else
                            class="cart__select--null"
                            @click.stop="selectGoods(item)"
                        ></div>
                        <div class="cart__left" @click="jumpGoodsDetail(item)">
                            <img
                                class="cart__img"
                                :src="item.productImage"
                                mode="aspectFill"
                            />
                            <div
                                v-if="
                                    item.stock <= 0 || item.productStatus !== 1
                                "
                                class="cart__disabled"
                            >
                                <div class="cart__disabled--text">
                                    {{
                                        item.productStatus === 0
                                            ? "已下架"
                                            : item.productStatus === 2
                                            ? "未开售"
                                            : "售罄"
                                    }}
                                </div>
                            </div>
                        </div>
                        <div class="cart__content">
                            <div class="cart__top">
                                <div
                                    class="cart__title"
                                    @click="jumpGoodsDetail(item)"
                                >
                                    {{ item.productName || "" }}
                                </div>
                                <div class="cart__price">
                                    {{ "¥" + (item.price || "0.00") }}
                                </div>
                            </div>
                            <div class="cart__spec">
                                {{ item.skuName || "" }}
                            </div>
                            <div class="cart__bottom">
                                <f-input-number
                                    v-model="item.count"
                                    :max="item.stock"
                                    @change="setCaetNum(item)"
                                ></f-input-number>
                                <i
                                    class="iconfont iconremove cart__remove"
                                    @click.stop="remove(item)"
                                ></i>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
        <div class="cart-column">
            <div class="column-l" v-if="!cartList.length">
                <div class="cart-contact" @click="changeDeliveryType">
                    <img
                        :src="
                            theme === 2
                                ? '/static/icon/change.png'
                                : '/static/icon/change_red.png'
                        "
                    />
                    <span class="text">{{
                        deliveryType === 0 ? "配送到家" : "门店自提"
                    }}</span>
                </div>
                <div class="cart-price-box">
                    <img
                        class="icon"
                        :src="
                            theme === 2
                                ? '/static/tabBar/icon_green_3_select.png'
                                : '/static/tabBar/icon_green_3_select_red.png'
                        "
                    />
                    <div class="money">￥<span class="num">0</span></div>
                    <div class="distribution">
                        {{ showDelivery }}
                        <!-- {{
                            deliveryConfig.deliveryMinAmount
                                ? "满￥" +
                                  deliveryConfig.deliveryMinAmount +
                                  "起送"
                                : "免配送费"
                        }} -->
                    </div>
                </div>
            </div>
            <div class="column-l active" v-if="cartList.length">
                <div class="cart-contact" @click="changeDeliveryType">
                    <img
                        :src="
                            theme === 2
                                ? '/static/icon/change.png'
                                : '/static/icon/change_red.png'
                        "
                    />
                    <span class="text">{{
                        deliveryType === 0 ? "配送到家" : "门店自提"
                    }}</span>
                </div>
                <div class="cart-price-box" @click="toggleList">
                    <span class="list-num">{{ cartNum }}</span>
                    <img
                        class="icon"
                        :src="
                            theme === 2
                                ? '/static/tabBar/icon_green_3_select.png'
                                : '/static/tabBar/icon_green_3_select_red.png'
                        "
                    />
                    <div class="price">
                        <div class="price1">￥{{ shopPrice }}</div>
                        <div class="price2" v-if="oldPrice !== shopPrice">
                            ￥{{ oldPrice }}
                        </div>
                    </div>
                    <div class="distribution" v-if="otherPrice">
                        {{ otherPrice }}
                    </div>
                </div>
            </div>
            <div class="column-r" v-if="minChaPrice > 0 || cartList.length===0 ">{{ tipStr }}</div>
            <div
                class="column-r submit"
                v-if="minChaPrice <= 0 && cartList.length>0"
                @click="submit"
            >
                去结算
            </div>
        </div>
    </div>
</template>

<script>
import FInputNumber from "../form/inputNumber";
export default {
    name: "ShopCart",
    components: { FInputNumber },
    props: {},

    // 数据
    data() {
        return {
            cartList: [],
            showList: false,
            cartNum: 0,
            deliveryType: 0, //0 配送到家 1 门店自提
            oldNum: null, // 旧数量
        };
    },

    // 初始化
    created() {
        this.refresh();
    },

    // 函数
    methods: {
        changeDeliveryType() {
            if (
                this.deliveryConfig.deliveryMethod.homeDelivery &&
                this.deliveryConfig.deliveryMethod.storePickUp
            ) {
                this.deliveryType = this.deliveryType === 0 ? 1 : 0;
            } else {
                this.fn.showToast("该店铺未配置其他送货方式");
            }
        },

        //手动刷新
        refresh() {
            this.deliveryType = this.$store.state.common.deliveryType || 0;
            this.getCartLsit();
            this.getCartNumber();
            const config = this.deliveryConfig;
            if (!config.deliveryMethod.homeDelivery) {
                this.deliveryType = 1;
                if (!config.deliveryMethod.storePickUp) {
                    this.deliveryType = 0;
                    this.fn.showToast("店铺配置错误，请至少选择一种配送方式");
                }
            } else {
                if (this.deliveryType === 1) {
                    if (!config.deliveryMethod.storePickUp) {
                        this.deliveryType = 0;
                    }
                }
            }
        },

        closeList() {
            this.showList = false;
        },
        toggleList() {
            this.showList = !this.showList;
        },

        // 获取购物车列表
        getCartLsit() {
            const self = this;

            self.api
                .get("/Order/GetCartList", {
                    pageIndex: 1,
                    pageSize: 100,
                })
                .then((res) => {
                    res.data.shopItemList.forEach((item) => {
                        item.price = item.priceFmt;
                        item.active =
                            item.stock >= item.count &&
                            item.productStatus === 1;
                    });
                    self.cartList = res.data.shopItemList;
                });
        },

        // 删除购物车
        remove(val) {
            const self = this;

            self.fn
                .showModal({
                    title: "删除商品",
                    content: "确定要删除该商品吗？",
                    confirmText: "删除",
                })
                .then((res) => {
                    if (res.confirm) {
                        self.api
                            .delete("/Order/RemoveCart", {
                                ids: [val.id],
                            })
                            .then(() => {
                                self.cartList.forEach((item, index) => {
                                    if (item.id === val.id) {
                                        self.cartList.splice(index, 1);
                                    }
                                });

                                self.getCartNumber();
                                self.cartChange();
                            });
                    }
                });
        },

        // 选择商品
        selectGoods(val) {
            const self = this;

            self.cartList.forEach((item, index) => {
                if (item.id === val.id) {
                    if (item.productStatus === 0) {
                        self.fn.showToast("该商品已下架");
                    } else if (item.productStatus === 2) {
                        self.fn.showToast("该商品未开售");
                    } else if (item.stock < item.count) {
                        self.fn.showToast("该商品库存不足");
                    } else {
                        item.active = !item.active;
                        self.cartList.splice(index, item);
                    }
                }
            });
        },

        // 获取购物车数量
        getCartNumber() {
            const self = this;
            self.api.get("/Order/GetCartCount").then((res) => {
                this.cartNum = res.data;
                if (res.data > 0) {
                    uni.setTabBarBadge({
                        index:2,
                        text: res.data.toString(),
                    });
                } else {
                    uni.removeTabBarBadge({
                        index: 2,
                    });
                }
            });
        },

        // 全选
        selectAllGoods() {
            const self = this;

            let select = !self.allSelect;

            self.cartList.forEach((item, index) => {
                item.active =
                    item.productStatus === 1 && item.stock >= item.count
                        ? select
                        : false;
                self.cartList.splice(index, item);
            });
        },

        // 修改购物车数量
        setCaetNum(val) {
            const self = this;
            self.api
                .post("/Order/UpdateItemCount", {
                    id: val.id,
                    count: val.count,
                })
                .then(() => {
                    self.getCartNumber();
                })
                .catch((res) => {
                    this.getCartLsit();
                });
            this.cartChange();
        },

        // 跳转到商品详情
        jumpGoodsDetail(val) {
            const self = this;

            self.router.push({
                path: "/pages/goods/detail",
                query: {
                    goodsId: val.productId,
                },
            });
        },

        // 结算
        submit() {
            const self = this;

            if (self.cartIds.length) {
                self.router.push({
                    path: "/pages/order/affirm",
                    query: {
                        ids: self.cartIds.join(","),
                        deliveryType: this.deliveryType,
                    },
                });
            } else {
                self.fn.showToast("至少选择一件商品");
            }
        },

        cartChange() {
            this.$emit("change");
        },
    },

    // 数据计算
    computed: {
        // 判断主题  1:红色  2：绿色
        theme() {
            return this.$store.state.common.theme;
        },
        // 交货设置
        deliveryConfig() {
            if(!this.$store.state.common.storeConfig.deliveryConfig){
                return this.fn.showToast('获取店铺配置错误');
            }
            return this.$store.state.common.storeConfig.deliveryConfig;
        },
        // 交货设置
        shop() {
            return this.$store.state.common.curShop;
        },

        // 起送金额
        minPrice() {
            if (this.deliveryType === 0) {
                if (this.deliveryConfig.deliveryMinAmount) {
                    return this.deliveryConfig.deliveryMinAmount;
                } else {
                    return 0;
                }
            } else {
                if (this.deliveryConfig.pickupMinAmount) {
                    return this.deliveryConfig.pickupMinAmount;
                } else {
                    return 0;
                }
            }
        },

        showDelivery() {
            if (this.deliveryType === 0) {
                return this.deliveryConfig.deliveryMinAmount
                    ? "满￥" + this.deliveryConfig.deliveryMinAmount + "起送"
                    : "免配送费";
            } else {
                return this.deliveryConfig.pickupMinAmount
                    ? "满￥" + this.deliveryConfig.pickupMinAmount + "起购"
                    : "";
            }
        },

        // 距离最低价格还差
        minChaPrice() {
            const self = this;

            let price = 0;

            self.cartList.forEach((item) => {
                if (item.active) {
                    price += item.price * item.count;
                }
            });
            let num = 0;
            if (this.deliveryType === 0) {
                num = this.deliveryConfig.deliveryMinAmount - price;
            } else {
                num = this.deliveryConfig.pickupMinAmount - price;
            }
            return parseFloat(num).toFixed(2);
        },

        allSelect() {
            const self = this;
            let select = true;

            self.cartList.forEach((item) => {
                if (
                    item.productStatus === 1 &&
                    item.stock >= item.count &&
                    !item.active
                ) {
                    select = false;
                }
            });

            if (self.cartIds.length <= 0) {
                select = false;
            }

            return select;
        },

        shopPrice() {
            let price = 0;

            this.cartList.forEach((item) => {
                if (item.active) {
                    price += item.price * item.count;
                }
            });
            return price.toFixed(2);
        },

        oldPrice() {
            let price = 0;

            this.cartList.forEach((item) => {
                if (item.active) {
                    let p = item.tagPrice / 100 || item.price;
                    price += p * item.count;
                }
            });
            return price.toFixed(2);
        },

        // totalPrice() {
        //     const self = this;

        //     let price = 0;

        //     self.cartList.forEach((item) => {
        //         if (item.active) {
        //             price += item.price * item.count;
        //         }
        //     });

        //     if (this.deliveryConfig.packageFee) {
        //         price += this.deliveryConfig.packageFee;
        //     }
        //     if (this.deliveryConfig.deliveryFee) {
        //         price += this.deliveryConfig.deliveryFee;
        //     }

        //     return parseFloat(price).toFixed(2);
        // },
        cartIds() {
            const self = this;

            let ids = [];

            self.cartList.forEach((item) => {
                if (
                    item.active &&
                    item.productStatus === 1 &&
                    item.stock >= item.count
                ) {
                    ids.push(item.id);
                }
            });

            return ids;
        },

        // 其他费用
        otherPrice() {
            let str = "";

            if (this.deliveryType === 0) {
                if (this.deliveryConfig.deliveryFee) {
                    str += `配送费￥${this.deliveryConfig.deliveryFee}`;
                }
            }
            if (this.deliveryConfig.packageFee) {
                str += ` 打包费￥${this.deliveryConfig.packageFee}`;
            }
            return str;
        },

        // 提示文字
        tipStr() {
            if (this.deliveryType === 0) {
                if (this.cartList.length) {
                    if (this.minChaPrice > 0) {
                        return `差￥${this.minChaPrice}起送`;
                    }
                } else {
                    if (this.deliveryConfig.deliveryMinAmount) {
                        return `￥${this.deliveryConfig.deliveryMinAmount}起送`;
                    } else {
                        return `￥0起送`;
                    }
                }
            } else {
                if (this.cartList.length) {
                    if (this.minChaPrice > 0) {
                        return `差￥${this.minChaPrice}起购`;
                    }
                } else {
                    if (this.deliveryConfig.pickupMinAmount) {
                        return `￥${this.deliveryConfig.pickupMinAmount}起购`;
                    } else {
                        return `￥0起购`;
                    }
                }
            }
        },
    },

    // 数据监听
    watch: {
        deliveryType(v) {
            this.$store.commit("common/update", {
                deliveryType: v,
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.cart-column {
    position: fixed;
    bottom: 1rem;
    left: px(40);
    right: px(40);
    height: px(130);
    background-color: #000000;
    border-radius: px(65);
    overflow: hidden;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 200;
    .white {
        color: #fff !important;
    }
    .column-l {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding-left: px(65);
        height: 100%;
        .money {
            font-size: px(36);
        }
        .num {
            font-size: px(48);
        }
        .distribution {
            height: px(40);
            line-height: px(40);
            margin-left: px(20);
            color: #adadad;
            padding-left: px(20);
            border-left: 1px solid #adadad;
            font-size: px(32);
        }
        .cart-price-box {
            padding-left: px(130);
            position: relative;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            height: 100%;
            .icon {
                position: absolute;
                left: px(20);
                bottom: 15%;
                z-index: 1;
                width: px(80);
                height: 70%;
            }
        }
        .list-num {
            position: absolute;
            position: absolute;
            left: px(80);
            top: px(20);
            min-width: px(44);
            height: px(44);
            line-height: px(44);
            text-align: center;
            border-radius: 50%;
            box-sizing: border-box;
            color: #fff;
            background-color: rgb(250, 81, 81);
            font-size: px(30);
            z-index: 10;
        }
        &.active {
            .cart-price-box {
                flex-direction: column;
                justify-content: center;
            }
            .distribution {
                width: 100%;
                margin-top: px(10);
                padding-left: px(0);
                border-left: none;
                margin-left: 0;
                font-size: px(30);
            }
            .price {
                width: 100%;
                display: flex;
                justify-content: flex-start;
                align-items: flex-end;
                .price1 {
                    color: #fff;
                    font-size: px(42);
                }
                .price2 {
                    color: #adadad;
                    font-size: px(32);
                    margin-left: px(20);
                    text-decoration: line-through;
                }
            }
        }
    }
    .column-r {
        width: px(250);
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #adadad;
        padding-right: px(20);
        font-size: px(34);
        @include omit(100%);
        &.submit {
            background-color: #27a34f;
            color: #fff;
            height: 100%;
            font-size: px(42);
        }
    }
}
.cart-contact {
    width: px(180);
    box-sizing: border-box;
    flex-shrink: 0;
    display: flex;
    border-right: px(4) solid #fff;
    height: 100%;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #27a34f;
    font-size: px(32);
    padding: 0;
    padding-right: px(20);
    margin: 0;
    background: transparent;
    line-height: 1.5;
    border-radius: 0;
    img {
        width: px(60);
        height: px(60);
    }
}
.cart-list {
    position: fixed;
    bottom: 2.9rem;
    left: 0;
    right: 0;
    height: 100%;
    box-sizing: border-box;
    z-index: 150;
    .bg {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
    }
    .main {
        background-color: #fff;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding-bottom: px(220);
        padding-top: px(20);
        border-radius: px(30) px(30) 0 0;
    }
    .head {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(110);
        border-bottom: 1px solid #f5f5f5;
        padding: 0 px(40);
        .r {
            color: #666;
            font-size: px(34);
            display: flex;
            justify-content: flex-start;
            align-items: center;
            line-height: 1;
            .remove {
                margin-right: px(10);
                display: inline-block;
            }

            .close {
                font-size: px(80);
                color: #999;
            }
        }
        .l {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            color: #666;
            font-size: px(36);
        }
        .select {
            width: px(60);
            height: px(60);
            margin-right: px(20);
        }
        .select--null {
            display: block;
            width: px(60);
            height: px(60);
            border: solid px(8) #d7d7d7;
            border-radius: 50%;
        }
    }
}
.cart {
    background-color: #fff;
    max-height: 60vh;
    overflow: auto;
    &__item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(295);
        padding: 0 px(30);
        & ~ .cart__item {
            border-top: 1px solid #f5f5f5;
        }
    }

    &__select {
        width: px(60);
        height: px(60);

        &--null {
            content: "";
            display: block;
            width: px(60);
            height: px(60);
            border: solid px(8) #d7d7d7;
            border-radius: 50%;
        }
    }

    &__left {
        position: relative;
        overflow: hidden;
        margin-left: px(20);
        border-radius: px(5);
        border: solid px(3) #e5e5e5;
    }

    &__img {
        width: px(230);
        height: px(235);
    }

    &__disabled {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.2);
    }

    &__disabled--text {
        display: flex;
        justify-content: center;
        align-items: center;
        width: px(150);
        height: px(150);
        font-size: px(40);
        color: #fff;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.6);
    }

    &__content {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        height: px(230);
        margin-left: px(20);
    }

    &__top {
        display: flex;
        justify-content: space-between;
    }

    &__title {
        @include omits(2);
        flex: 1;
        height: px(100);
        font-size: px(38);
        color: #333;
    }

    &__price {
        margin-left: px(60);
        font-size: px(34);
        color: #333;
    }

    &__spec {
        margin: px(10) 0;
        font-size: px(34);
        color: #999;
    }

    &__bottom {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
    }

    &__remove {
        font-size: px(60);
        color: #666;
    }
}

.page_red {
    .cart-column {
        .column-r {
            &.submit {
                background-color: #27a34f;
            }
        }
    }

    .cart-contact {
        color: #27a34f;
    }
}
</style>