<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { cartListApi, cartDeleteApi, cartCreateApi } from "@/api/store.js";
import price from "./price.vue";
import mitt from "@/utils/mitt.js";
import { useUserStore } from "@/store/user.js";
import userList from "@/components/userList.vue";
import { ElMessage } from "element-plus";

const list = ref([]);
const allPrice = ref(0); //商品总价
const costPrice = ref(0); //商品原价
const discounts = ref(0); //优惠金额

const userStore = useUserStore();
const userListRef = ref(null);


const clearAll = () => {
    let id = [];
    list.value.map((item) => {
        id.push(item.id);
    });
    if (id.length == 0) return;
    deleteShop(id);
};

const deleteOne = (id) => {
    list.value = list.value.filter((item) => item.id != id);
    deleteShop([id]);
};

const deleteShop = (arr) => {
    cartDeleteApi({
        id: arr,
    }).then((res) => {
        getList();
    });
};

const userInfo = ref({
    uid: ''
})
const setUser = (row) => {
    userInfo.value = row;
    userInfo.value.uid = row.id;
    getList();
    emit("getStoreList", {uid: row.id}, true);
}

const extend = ref({});
const getList = () => {
    allPrice.value = 0;
    costPrice.value = 0;
    discounts.value = 0;
    cartListApi({
        uid: userInfo.value.uid
    }).then((res) => {
        extend.value = res.data.extend;
        list.value = res.data.lists || [];
        // if (!extend.value?.pay_price) userInfo.value.uid = "";
        // if (res.data?.lists?.length > 0) {
        // list.value = res.data.lists;
        // allPrice.value = res.data?.lists.reduce((previous, current) => {
        //     return previous + Number(current.total_price);
        // }, 0)
        // costPrice.value = allPrice.value;
        // } else list.value = [];
    });
};
getList();

const emit = defineEmits(["goPay", "editAttr", "getStoreList"]);

const goPay = () => {
    emit("goPay");
};

const changeCartNum = (val, old) => {
    cartCreateApi({
        product_id: val.product_id,
        cart_num: val.cart_num
    }).then((res) => {
        getList();
        // allPrice.value = 0;
        // list.value.forEach((item) => {
        //     allPrice.value += item.price * item.cart_num;
        // });
        // costPrice.value = allPrice.value;
    }).catch((err) => {
        let match = err?.msg?.match(/\b\d+(\.\d+)?\b/);
        if (match) {
            val.cart_num = +match[0];
        } else val.cart_num = 1;
    });
};

const editAttr = (data) => {
    emit("editPupop", data);
};


const changeAllPrice = (price) => {
    discounts.value = costPrice.value - price;
    allPrice.value = +price;
    nextTick(() => {
        setTimeout(() => {
            showPrice(false);
        }, 150);
    });
};

const nowPrice = ref(0);
const priceRef = ref(null);
const showPrice = (type = true) => {
    priceRef.value.show(type, costPrice.value);
};

const is_storage = ref(false)

const resetView = () => {
    is_storage.value = false;
    getList();
}

defineExpose({
    getList,
    resetView,
    list,
    discounts,
    allPrice,
    userInfo,
    is_storage
});

// 键盘事件
const ainsert = () => {
    if (priceRef.value.dialogVisible) priceRef.value.dialogVisible = false;
    else showPrice();
};
const adelete = () => {
    if (list.value.length > 0) clearAll();
};
onMounted(() => {
    mitt.on("insert", ainsert);
    mitt.on("delete", adelete);
});

onUnmounted(() => {
    mitt.off("insert", ainsert);
    mitt.off("delete", adelete);
});
</script>

<template>
    <div class="my-order">
        <div class="user-nav">
            <div class="user-info">
                <el-avatar class="avatar" :src="userInfo.avatar" />
                <div class="info" v-if="userInfo.uid">
                    <div class="flex-bewteen">
                        <div>手机号: {{ userInfo.mobile || userInfo.account }}</div>
                        <el-button type="primary" link class="change-user"
                            @click="userListRef.open(userInfo.uid)">切换用户<el-icon>
                                <ArrowRight />
                            </el-icon></el-button>
                    </div>
                    <div class="flex-bewteen" style="align-items: flex-start;">
                        <div class="user-money">
                            <div style="margin-right: 0.5rem;">采购款: <span style="color: #f70;">{{
                                userInfo.purchase_funds }}</span></div>
                            <div style="margin-right: 0.5rem;">礼品券: <span style="color: #f70;">{{ userInfo.integral
                                    }}</span></div>
                            <div>余额: <span style="color: #f70;">{{ userInfo.now_money }}</span></div>
                        </div>
                        <el-button style="margin-top:0.2rem;" link @click="setUser({id: ''})">
                            重置<el-icon>
                                <RefreshLeft />
                            </el-icon>
                        </el-button>
                    </div>
                </div>
                <div class="info" v-else style="align-items: center;display:flex;justify-content: space-between;">
                    <div class="flex-bewteen" style="width:100%;">
                        <div style="font-size: 1.2rem;">游客</div>
                        <el-button type="primary" link class="change-user" @click="userListRef.open()">切换用户<el-icon>
                                <ArrowRight />
                            </el-icon></el-button>
                    </div>
                </div>
            </div>
            <userList ref="userListRef" @setUser="setUser" />
        </div>
        <div class="header-nav">
            <div class="nav-item">
                已选购 <span>{{ list.length }}</span> 款
            </div>
            <div class="nav-item-clear" @click="clearAll">
                <el-icon>
                    <Delete />
                </el-icon>清空 (Delete)
            </div>
        </div>
        <div class="order-list">
            <el-empty v-if="list.length == 0" description="请点击右侧添加商品" />
            <div v-else class="order-item" v-for="(item, index) in list" :key="index">
                <el-image loading="lazy" class="order-item-img" :src="item.image"></el-image>
                <div class="order-item-info">
                    <div class="order-item-title">
                        <div class="title">{{ item.store_name }}</div>
                        <div class="delete" @click="deleteOne(item.id)">删除</div>
                    </div>
                    <div class="order-item-sku">
                        <span>{{ item.unit_name }}</span>
                    </div>
                    <div class="order-item-price">
                        <div>
                            ¥<span>{{ item.price }}</span>
                        </div>
                        <div>
                            <el-input-number v-model="item.cart_num" :min="+item.batch > 0 ? +item.batch : 1" :step="1"
                                step-strictly @change="changeCartNum(item)" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="order-footer">
            <div class="order-total">
                <div class="price" style="flex-direction: column; align-items: flex-start;">
                    <div class="total-item" style="flex-shrink: 0;">
                        合计:
                        <span>¥<span style="font-size: 1.4rem">
                                {{ extend.pay_price || '0.00' }}</span></span>
                    </div>
                    <div v-if="extend.msg" class="total-item" style="padding-right: 0;line-height: 0.8rem;"><span
                            style="font-size: 0.8rem">{{ extend.msg }}</span></div>
                    <!-- <div class="total-item">
                        优惠:
                        <span
                        >¥<span>{{ discounts.toFixed(2) }}</span></span
                        >
                    </div> -->
                </div>
                <div class="update-price">
                    <el-switch v-model="is_storage" size="large" inline-prompt active-text="存货" inactive-text="不存" />
                </div>
            </div>
            <div class="order-btn">
                <el-button class="btn" type="primary" @click="goPay" :disabled="list.length == 0">{{ "立即结账 (F9)" }}</el-button>
            </div>
        </div>
        <price ref="priceRef" @changeAllPrice="changeAllPrice"></price>
    </div>
</template>

<style scoped lang="scss">
.my-order {
    border-radius: 1.2rem;
    height: 100%;
    background-color: #fff;
    width: 30rem;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .user-nav {
        .user-info {
            padding: 1rem;
            margin: 1rem;
            margin-bottom: 0;
            border: 2px solid #f70;
            background-color: rgba($color: #f70, $alpha: 0.1);
            border-radius: 0.5rem;
            display: flex;

            .avatar {
                width: 3rem;
                height: 3rem;
                flex-shrink: 0;
            }

            .info {
                flex: 1;
                margin-left: 1rem;
                color: #666;

                .flex-bewteen {
                    display: flex;
                    justify-content: space-between;
                }

                .change-user {
                    font-size: 1rem;
                }

                .user-money {
                    display: flex;
                    flex: 1;
                    flex-wrap: wrap;

                    &>div {
                        flex-shrink: 0;
                    }
                }
            }
        }
    }

    .header-nav {
        display: flex;
        justify-content: space-between;
        padding: 1rem;
        height: 1.5rem;
        border-bottom: 1px solid #eee;

        span {
            color: #ff4a00;
        }

        .nav-item-clear {
            display: flex;
            align-items: center;
            font-size: 0.8rem;
            cursor: pointer;
        }
    }

    .order-list {
        flex: 1;
        overflow-y: auto;
        padding-bottom: 10rem;

        .order-item {
            display: flex;
            padding: 1rem;
            border-bottom: 1px solid #eee;

            .order-item-img {
                width: 5rem;
                height: 5rem;
                border-radius: 0.5rem;
            }

            .order-item-info {
                flex: 1;
                box-sizing: border-box;
                padding-left: 0.75rem;
                display: flex;
                flex-direction: column;
                justify-content: space-between;

                &>div {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }

                .order-item-title {
                    .title {
                        width: 18rem;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                    }

                    .delete {
                        color: #1890ff;
                        cursor: pointer;
                    }
                }

                .order-item-sku {
                    cursor: pointer;
                    font-size: 0.8rem;
                    color: #999;
                }
            }
        }
    }

    .order-footer {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 20;
        width: 100%;
        box-shadow: 0 -1px 0.625rem #eee;
        background-color: #fff;

        .order-total {
            height: 3.5rem;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #eee;
            align-items: center;

            .price {
                display: flex;
                align-items: center;

                .total-item {
                    padding-right: 1.5rem;

                    span {
                        color: #f5222d;
                    }
                }
            }

            .update-price {
                .btn {
                    border-radius: 3rem;
                }
            }
        }

        .order-btn {
            height: 3.2rem;
            padding: 1rem 1.5rem;

            .btn {
                width: 100%;
                height: 100%;
                font-size: 1.2rem;
                border-radius: 3rem;
            }
        }
    }
}
</style>
