<script setup>
import order from "./component/order.vue";
import shop from "./component/shop.vue";
import padding from "@/components/padding.vue";
import pupop from "./component/pupop.vue";
import classify from "./component/classify.vue";
import pay from "@/components/pay.vue";
import { ref, reactive, nextTick, onMounted, onUnmounted } from "vue";
import { cartCreateApi, orderCheckApi } from "@/api/store.js";
import { saleStoreListApi } from "@/api/shop.js";
import { useUserStore } from "@/store/user.js";
import { useRoute } from "vue-router";
import mitt from "@/utils/mitt.js";
import moment from "moment";
import { printTicket } from "@/utils/EscPos.js";
import { ElMessage } from "element-plus";

const pupopRef = ref(null);
const orderRef = ref(null);
const shopRef = ref(null);
const payRef = ref(null);

const storeList = ref([]);
const priceKey = reactive({
    off_activity: "",
    op_price: "",
    price: ""
})

const userStore = useUserStore();
const route = useRoute();

const where = ref({
    page_no: 1,
    page_size: 30,
});


const loading = ref(false)
const getStoreList = (data = {}, reload = false) => {
    where.value = {
        ...where.value,
        ...data,
    };
    if (reload) {
        storeList.value = [];
        where.value.page_no = 1;
        loadEnd.value = false;
    }
    loading.value = true;
    saleStoreListApi({
        ...where.value,
        store_id: userStore.userInfo?.store_id
    }).then((res) => {
        loading.value = false;
        for (let key in res.data.extend) {
            priceKey[key] = res.data.extend[key]
        }
        if (res.data?.lists?.length < where.value.page_size) loadEnd.value = true;
        storeList.value = storeList.value.concat(res.data.lists);
        if (
            data.store_name_code &&
            storeList.value.length == 1 &&
            isAllDigits(data.store_name_code)
        ) {
            shopRef.value.code = "";
            shopRef.value.inputBlur();
            changeItem(storeList.value[0]);
        }
        where.value.page_no++;
    });
};

const loadEnd = ref(false);
const loadMore = (data) => {
    if (loadEnd.value) return;
    getStoreList(data);
};

function isAllDigits(str) {
    return /^\d+$/.test(str);
}

const cartAddInfo = (item, change = "") => {
    console.log(item, change);
    let q = {
        product_id: item.product_id,
        cart_num: item.cart_num,
    };
    cartCreateApi(q).then((res) => {
        orderRef.value.getList();
    });
};

const changeItem = (item, change) => {
    pupopRef.value.setForm(item, "add");
    pupopRef.value.show(true);
};

const editPupop = (item) => {
    pupopRef.value.setForm(item, "edit");
    pupopRef.value.show(true);
};

const orderForm = ref({});
// 结算
const checkOut = () => {
    let cart_id = orderRef.value.list.map((item) => item.id);
    let query = {
        cart_id: cart_id,
        uid: orderRef.value?.userInfo?.uid || "",
    };
    if (orderRef.value.discounts > 0) {
        query.deduction_price = orderRef.value.discounts.toFixed(2);
        query.pay_type = "micropay";
    }
    orderCheckApi(query).then((res) => {
        orderForm.value = res.data.order;
        payRef.value.setForm({
            data: res.data.order,
            cart_id: cart_id,
            uid: orderRef.value?.userInfo?.uid || "",
            is_storage: orderRef.value?.is_storage ? 1 : 0,
        });
    });
};

const goPay = () => {
    if(orderRef.value?.is_storage && !orderRef.value?.userInfo?.uid) return ElMessage.error("选择用户才可以存货");
    checkOut();
    payRef.value.drawer = true;
};

const paySuccess = (data = null) => {
    // data = {
    //   out_trade_no: "PF171568087790938356", //单号
    //   create_time: "2024-05-14 17:59:05", //下单时间
    //   trade_type: "MICROPAY", //支付方式
    //   transaction_id: "4200002159202405159003084211", //支付单号
    // }
    //   if(data) onPrint(data);
    setTimeout(() => {
        orderRef.value.resetView();
    })
};

// 打印小票
const onPrint = (data) => {
    let goods = [];
    orderRef.value.list.forEach((item) => {
        goods.push({
            name: item.goods_name, //商品名称
            sell: item.sell, //单价
            nums: item.cart_num, //数量
            unit_name: item.unit_name, //单位
            total: item.goods_total_price, //小计
        });
    });
    let paytype = "现金支付";
    if (data.pay_type == 13) paytype = "支付宝支付";
    if (data.pay_type == 9) paytype = "微信支付";
    let obj = {
        mer_name: userStore.userInfo.mer_name, //商户名称
        service_phone: userStore.userInfo.service_phone, //客服电话
        number: data.out_trade_no, //单号
        create_time: data.create_time, //下单时间
        total_price: orderForm.value.total, //总价
        pay_price: orderForm.value.total, //实付
        pay_type: paytype, //支付方式
        pay_number: data.transaction_id, //支付单号
        goods: goods, //商品列表
    };
    if (goods.length > 0 && data.out_trade_no) {
        let str = printTicket(obj);
        console.log(str);
        uni.getEnv((res) => {
            if (res.app) {
                APPprint(content);
                setTimeout(() => {
                    isPrint = false;
                }, 4000);
            }
        });
        uni.postMessage({
            data: {
                type: "print",
                content: str,
            },
        });
    }
}

// 键盘事件
const aF9 = () => {
    if (route.name != "saleHome") return;
    if (!payRef.value.drawer && orderRef.value.list.length > 0) goPay();
    else payRef.value.beforeClose();
};
onMounted(() => {
    getStoreList();
    mitt.on("F9", aF9);
});

onUnmounted(() => {
    mitt.off("F9", aF9);
});
</script>

<template>
    <div class="my-card">
        <order ref="orderRef" @goPay="goPay" @editPupop="editPupop" />
        <padding />
        <shop ref="shopRef" style="flex: 1" :storeList="storeList" :priceKey="priceKey" :loading="loading" @getStoreList="getStoreList"
            @changeItem="changeItem" @loadMore="loadMore" />
        <pupop ref="pupopRef" :priceKey="priceKey" @changeItem="cartAddInfo" />
        <padding />
        <classify ref="classifyRef" @getStoreList="getStoreList" />
        <pay ref="payRef" @paySuccess="paySuccess" />
    </div>
</template>

<style lang="scss">
.my-card {
    display: flex;
}

/* 修改滚动条的样式 */
::-webkit-scrollbar {
    width: 0.315rem;
    /* 设置滚动条的宽度 */
}

/* 设置滚动条的轨道样式 */
::-webkit-scrollbar-track {
    background-color: #f1f1f1;
    /* 设置轨道的背景色 */
    margin: 1.25rem 0;
}

/* 设置滚动条的滑块样式 */
::-webkit-scrollbar-thumb {
    background-color: #ccc;
    /* 设置滑块的背景色 */
    border-radius: 0.315rem;
    /* 设置滑块的圆角 */
}

/* 设置滚动条鼠标悬停时的滑块样式 */
::-webkit-scrollbar-thumb:hover {
    background-color: #999;
    /* 设置鼠标悬停时滑块的背景色 */
}
</style>
