<template>
    <div class="page shop-cart-page" :class="{ page_red: theme === 1 }">
        <scroll-view
            class="page__scroll"
            :scroll-y="true"
            @scrolltolower="getMoreGoods"
        >
            <ul class="menu">
                <li
                    class="menu__item"
                    :class="{ 'menu__item--active': sort === 'SaleDesc' }"
                    @click="setSort('SaleDesc')"
                >
                    <div class="menu__text">销量</div>
                </li>
                <li
                    class="menu__item"
                    :class="{ 'menu__item--active': sort === 'NewDesc' }"
                    @click="setSort('NewDesc')"
                >
                    <div class="menu__text">新品</div>
                </li>
                <li
                    class="menu__item"
                    :class="{
                        'menu__item--active':
                            sort === 'Price' || sort === 'PriceDesc',
                    }"
                    @click="setSort('Price')"
                >
                    <div class="menu__text">价格</div>
                    <div
                        class="menu__sort"
                        :class="{
                            'menu__sort--up': sort === 'Price',
                            'menu__sort--down': sort === 'PriceDesc',
                        }"
                    ></div>
                </li>
            </ul>
            <ul class="goods">
                <li
                    class="goods__item"
                    v-for="(item, index) in goodsList"
                    :key="index"
                >
                    <my-image class="goods__img" :src="item.image"  @click="jumpGoodsDetail(item)"></my-image>
                    <div class="goods__title"  @click="jumpGoodsDetail(item)">{{ item.name }}</div>
                    <div class="goods__coupon" v-if="item.coupon"  @click="jumpGoodsDetail(item)">
                        {{ item.coupon }}
                    </div>
                    <div class="goods__price">
                        <div class="goods__present"   @click="jumpGoodsDetail(item)">
                            <span class="goods__rmb">¥</span>
                            <span class="goods__big">{{
                                item.price / 100
                            }}</span>
                        </div>
                        <div class="goods__original"   @click="jumpGoodsDetail(item)" v-if="item.tagPrice !== 0">
                            {{ "¥" + item.tagPrice / 100 }}
                        </div>
                    </div>
                    <!-- 登录 -->
                    <div class="btns">
                        <block
                            v-if="user.login && !item.skus.length && item.cart"
                        >
                            <button
                                class="button button2"
                                @click.stop="setCaetNum(item)"
                            >
                                <div class="goods__remove"></div>
                            </button>
                            <span class="cart-num">{{ item.cart.count }}</span>
                        </block>
                        <button
                            v-if="user.login && !item.skus.length"
                            class="button"
                            @click.stop="addSpec(item, 'cart', $event)"
                        >
                            <div class="goods__add"></div>
                        </button>
                        <button
                            v-else-if="user.login && item.skus.length"
                            class="button"
                            @click.stop="openSpec(item, 'cart', $event)"
                        >
                            <div class="goods__add-text">选规格</div>
                        </button>
                        <!-- <f-input-number
                        class="num-input"
                        v-else-if="ifCart(item)"
                        v-model="ifCart(item).count"
                        :showMinText="false"
                        :mini="true"
                        :max="ifCart(item).stock"
                        @change="setCaetNum(item, $event)"
                    ></f-input-number> -->
                        <!-- 未登录 -->
                        <button
                            v-if="!user.login && !item.skus.length"
                            class="button"
                            open-type="getUserInfo"
                            lang="zh_CN"
                            @getuserinfo.stop="openSpec(item, 'cart', $event)"
                        >
                            <div class="goods__add"></div>
                        </button>
                        <button
                            v-if="!user.login && item.skus.length"
                            class="button"
                            lang="zh_CN"
                            open-type="getUserInfo"
                            @getuserinfo.stop="openSpec(item, 'cart', $event)"
                        >
                            <div class="goods__add-text">选规格</div>
                        </button>
                    </div>
                </li>
            </ul>
            <div class="more-text" v-if="goodsList.length && !isHaveMore">
                - 没有更多了 -
            </div>
            <div class="null" v-if="loading && !goodsList.length">
                <img
                    class="null__img"
                    src="/static/common/goods_null_2.jpg"
                    alt
                />
                <div class="null__title">抱歉！没有找到相关商品~</div>
            </div>
        </scroll-view>
        <!-- <g-spec ref="spec" :goods="goods" :spec="'cart'"></g-spec> -->
        <g-spec-modal ref="spec" :goods="goods" :spec="'cart'" @change="modalCartChange()"></g-spec-modal>
        <shop-cart ref="shopCart" @change="cartChange()"></shop-cart>
    </div>
</template>

<script>
import MyImage from "../../components/image/index";
import ShopCart from "../../components/shop-cart/index";
import GSpec from "./spec";
import GSpecModal from "./specModal";
import FInputNumber from "../../components/form/inputNumber";

export default {
    name: "",
    components: { MyImage, GSpec, ShopCart, GSpecModal, FInputNumber },
    // 数据
    data() {
        return {
            title: "", // 标题（搜索关键字）
            categoryId: "", // 分类id
            brandId: "", // 品牌id
            sort: "SaleDesc", // 排序
            page: 1, // 页码
            goodsList: [],
            isHaveMore: true, // 是否有更多数据
            loading: false, // 是否加载完成
            goods: null, // 详情数据 加入购物车时用
            cartNum: 0, // 购物车数量
            cartList: [],
        };
    },

    onLoad() {
        const self = this;
        self.fn.shareMenu();

        if (!self.loading) {
            uni.showLoading({
                title: "加载中...",
            });
        }
    },

    async onShow() {
        const self = this;

        await self.fn.init();
        self.fn.shareMenu();
        self.title = self.$mp.query.title;
        self.categoryId = self.$mp.query.categoryId;
        self.brandId = self.$mp.query.brandId;
        self.fn.setTitle(self.title);
        self.getGoodsList();
        this.getCartLsit();
        this.$refs.shopCart.refresh();
    },

    onShareAppMessage() {
        const self = this;
        let obj = {
            ...self.$mp.query,
            shopId:this.activeShop.id,
            uid:this.user.user.id
        }

        if (this.activeShop.store) {
            obj.storeId = this.activeShop.store.id;
        }
        return {
            title: self.siteTitle,
            path: self.router.getPath(self.$mp.page.route, obj),
        };
    },

    onPullDownRefresh() {
        const self = this;
        self.getGoodsList();
        this.getCartLsit();
        this.$refs.shopCart.refresh();
    },

    // 函数
    methods: {
        // 设置排序
        setSort(val) {
            const self = this;

            if (val === "Price") {
                self.sort = self.sort === "Price" ? "PriceDesc" : "Price";
            } else {
                self.sort = val;
            }

            self.getGoodsList();
        },

        // 获取商品列表
        getGoodsList() {
            const self = this;

            let keyword = !self.categoryId && !self.brandId ? self.title : "";

            self.page = 1;
            uni.showLoading({
                title:'加载中...'
            });
            self.api
                .get("/Product/GetList", {
                    keywords: keyword,
                    typeId: self.categoryId,
                    brandId: self.brandId,
                    sort: self.sort,
                    pageIndex: self.page,
                    pageSize: 20,
                })
                .then((res) => {
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    if (res.data.data.length) {
                        self.page++;
                    } else {
                        self.isHaveMore = false;
                    }

                    self.goodsList = res.data.data;
                    self.loading = true;
                    this.setGoodsList();
                    uni.hideLoading();
                });
        },

        // 获取更多商品
        getMoreGoods() {
            const self = this;

            self.api
                .get("/Product/GetList", {
                    keywords: self.title,
                    brandId: self.brandId,
                    sort: self.sort,
                    pageIndex: self.page,
                    pageSize: 20,
                })
                .then((res) => {
                    if (res.data.data.length) {
                        self.page++;
                    } else {
                        self.isHaveMore = false;
                    }

                    self.goodsList = self.goodsList.concat(res.data.data);
                    this.setGoodsList();
                });
        },

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

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

        // 添加购物车
        getDetail(item, callback) {
            const self = this;
            self.api
                .get(
                    "/Product/Detail",
                    {
                        id: item.id,
                    },
                    {
                        pass: true,
                    }
                )
                .then((res) => {
                    if (res.data) {
                        let data = JSON.parse(res.data);
                        data.cart = item.cart;
                        self.goods = data;
                        // this.ifSpec();
                        callback();
                    } else {
                        self.fn
                            .showModal({
                                title: "商品已下架",
                                showCancel: false,
                            })
                            .then((res) => {
                                if (res.confirm) {
                                    self.router.push({
                                        path:'/pages/goods/index',
                                        isTabBer:true
                                    });
                                }
                            });
                    }
                });
        },
        // 获取购物车列表
        getCartLsit() {
            const self = this;

            self.api
                .get("/Order/GetCartList", {
                    pageIndex: 1,
                    pageSize: 100,
                })
                .then((res) => {
                    res.data.forEach((item) => {
                        item.price = item.priceFmt;
                        item.active =
                            item.stock >= item.count &&
                            item.productStatus === 1;
                    });
                    self.cartList = res.data;
                    this.setGoodsList();
                });
        },
        setGoodsList() {
            // 删除全部
            for (let item of this.goodsList) {
                item.cart = null;
            }
            // 重新赋值
            for (let item of this.goodsList) {
                for (let cart of this.cartList) {
                    if (cart.productId === item.id) {
                        if(item.skus.length === 0){
                            item.cart = cart;
                        }else{
                            if(item.cart){
                                item.cart.push(cart);
                            }else{
                                item.cart = [cart];
                            }
                        }
                    }
                }
            }
            this.goodsList = [...this.goodsList];
        },

        // 判断是否在购物车
        ifCart(val) {
            const cartList = this.cartList;
            if (cartList) {
                for (let item of cartList) {
                    if (item.productId === val.id) {
                        return item;
                    }
                }
            }
            return false;
        },
        
        cartChange(){
        },

        modalCartChange(){
            this.$refs.shopCart.refresh();
        },

        setCaetNum(item) {
            item.cart.count--
            let num = item.cart.count;
            const self = this;
            if (num > 0) {
                self.api
                    .post("/Order/UpdateItemCount", {
                        id: item.cart.id,
                        count: num,
                    })
                    .then(() => {
                        self.$refs.shopCart.refresh();
                    });
            } else {
                let id = item.cart.id;
                delete item.cart;
                self.api
                    .delete("/Order/RemoveCart", {
                        ids: [id],
                    })
                    .then(() => {
                        self.$refs.shopCart.refresh();
                    });
            }
        },

        // 打开规则选项
        openSpec(item, type, user) {
            const self = this;
            let userInfo = user.detail.userInfo;

            this.getDetail(item, () => {
                if (self.user.login) {
                    self.$refs.spec.num = 1;
                    self.$refs.spec.open(type, (res) => {
                        if (type === "cart") {
                            // self.fn.showToast("已成功加入购物车");
                            self.$refs.shopCart.refresh();
                        } else if (type === "buy") {
                            self.router.push({
                                path: "/pages/order/affirm",
                                query: {
                                    ids: res.data,
                                },
                            });
                        }
                    });
                } else {
                    if (userInfo) {
                        if (!self.user.login) {
                            self.api
                                .post("/User/UpdateUserWechatInfo", userInfo)
                                .then(() => {
                                    self.$store.commit("user/update", {
                                        login: true,
                                        userInfo: userInfo,
                                    });
                                });
                        }

                        self.$refs.spec.num = 1;
                        self.$refs.spec.open(type, (res) => {
                            if (type === "cart") {
                                // self.fn.showToast("已成功加入购物车");
                                self.$refs.shopCart.refresh();
                            } else if (type === "buy") {
                                self.router.push({
                                    path: "/pages/order/affirm",
                                    query: {
                                        ids: res.data,
                                    },
                                });
                            }
                        });
                    } else {
                        self.fn.showToast("授权失败请重试");
                    }
                }
            });
        },

        // 添加购物车
        addSpec(item) {
            const self = this;
            if (item.cart) {
                item.cart.count++;
                self.api
                    .post("/Order/UpdateItemCount", {
                        id: item.cart.id,
                        count: item.cart.count,
                    })
                    .then(() => {
                        self.$refs.shopCart.refresh();
                    })
                    .catch((res) => {
                        this.getCartLsit();
                    });
            } else {
                self.api
                    .post("/Order/AddCart", {
                        productId: item.id,
                        count: 1,
                    })
                    .then((res) => {
                        // self.fn.showToast("已成功加入购物车");
                        self.$refs.shopCart.refresh();
                    })
                    .catch((res) => {
                        this.getCartLsit();
                    });
            }
        },
    },

    // 数据计算
    computed: {
        // 判断主题  1:红色  2：绿色
        theme() {
            return this.$store.state.common.theme;
        },
        user() {
            return this.$store.state.user;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style>
page {
    height: 100%;
}
</style>

<style lang="scss" scoped>
.page {
    position: relative;
    height: 100%;

    &__scroll {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
}

.menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: px(110);
    margin-bottom: px(5);
    padding: 0 px(85);
    background-color: #fff;
    box-shadow: 0 px(-5) px(10) #333;

    &__item {
        display: flex;
        align-items: center;
    }

    &__text {
        font-size: px(40);
        color: #000;
    }

    &__item--active &__text {
        color: #27a34f;
    }

    &__sort {
        margin-left: px(15);

        &:before {
            display: block;
            content: "";
            width: 0;
            height: 0;
            margin-bottom: px(10);
            border-width: px(12);
            border-style: solid;
            border-color: transparent transparent #ccc transparent;
        }

        &:after {
            display: block;
            content: "";
            width: 0;
            height: 0;
            border-width: px(12);
            border-style: solid;
            border-color: #ccc transparent transparent transparent;
        }

        &--up:before {
            border-color: transparent transparent #27a34f transparent;
        }

        &--down:after {
            border-color: #27a34f transparent transparent transparent;
        }
    }
}

.goods {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 px(25) px(30);

    &__item {
        width: px(500);
        padding-bottom: px(30);
        margin-top: px(25);
        overflow: hidden;
        border-radius: px(15);
        background-color: #fff;
        position: relative;

        &:nth-child(2n + 1) {
            margin-right: px(30);
        }
    }
    .button {
        // overflow: visible;
        // position: absolute;
        // bottom: 0;
        // right: 0;
        // z-index: 1;
        // padding: px(10) px(30) px(30) px(10);
    }
    .btns {
        overflow: visible;
        position: absolute;
        bottom: px(30);
        right: px(30);
        z-index: 1;
        display: flex;
        align-items: center;
    }
    .cart-num {
        // padding: px(30) px(10) px(10) px(30);
        padding: 0 px(30);
        box-sizing: border-box;
        min-width: px(60);
    }
    .num-input {
        overflow: visible;
        position: absolute;
        bottom: px(20);
        right: px(20);
        z-index: 1;
    }
    &__add-text {
        height: px(60);
        line-height: px(60);
        background-color: #27a34f;
        color: #fff;
        font-size: px(30);
        padding: 0 px(20);
        border-radius: px(30);
    }
    &__add {
        background-color: #27a34f;
        width: px(60);
        height: px(60);
        border-radius: 50%;
        // box-shadow: px(1) px(2) px(6) #27A34F;
        position: relative;
        &::after,
        &::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 1;
            width: 60%;
            height: px(6);
            border-radius: px(6);
            background: #fff;
        }
        &::after {
            transform: translate(-50%, -50%);
        }
        &::before {
            transform-origin: center;
            transform: translate(-50%, -50%) rotate(90deg);
        }
    }

    &__remove {
        background-color: #fff;
        width: px(60);
        height: px(60);
        border-radius: 50%;
        border: 1px solid #999;
        position: relative;
        &::after {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 1;
            width: 60%;
            height: px(6);
            border-radius: px(6);
            background: #999;
            transform: translate(-50%, -50%);
        }
    }

    &__img /deep/ img {
        width: px(500);
        height: px(500);
    }

    &__title {
        @include omits(2);
        height: px(110);
        margin: px(20);
        font-size: px(40);
        color: #333;
    }

    &__coupon {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        height: px(40);
        padding: 0 px(15);
        margin: 0 px(20);
        font-size: px(30);
        color: #27a34f;
        border-radius: px(20);
        border: solid px(3) #27a34f;
    }

    &__price {
        display: flex;
        align-items: flex-end;
        padding: 0 px(20);
        margin-top: px(20);
    }

    &__present {
        color: #000;
    }

    &__rmb {
        font-size: px(30);
    }

    &__big {
        font-size: px(38);
    }

    &__original {
        position: relative;
        margin-left: px(20);
        font-size: px(32);
        color: #999;

        &:after {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            z-index: 1;
            width: 100%;
            height: px(1);
            transform: translateY(-100%);
            background-color: #999;
        }
    }
}

.null {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: px(115);

    &__img {
        width: px(741);
        height: px(340);
    }

    &__title {
        margin-top: px(60);
        font-size: px(42);
        color: #666;
    }
}

.more-text {
    display: flex;
    justify-content: center;
    padding-bottom: px(60);
    font-size: px(34);
    color: #999;
}
.page_red {
    .menu {
        .menu__item--active .menu__text {
            color: #27a34f;
        }
        &__sort {
            &--up:before {
                border-color: transparent transparent #27a34f transparent;
            }

            &--down:after {
                border-color: #27a34f transparent transparent transparent;
            }
        }
    }
    .goods {
        &__add-text {
            background-color: #27a34f;
        }
        &__add {
            background-color: #27a34f;
            box-shadow: px(1) px(2) px(6) #27a34f;
        }
    }
}
</style>