<template>
    <view style="width: 100%;">
        <view class="u-wrap">
            <view class="u-menu-wrap">
                <view class="right-cates">
                    <view class="right-cates-list">
                        <block v-for="(item, index) in lineList">
                            <u-image :width="item?.imageWidth" :height="item?.imageHeight" mode="scaleToFill"
                                :src="baseUrl + item.url"></u-image>
                        </block>
                        <view style="height: 50px;" />
                    </view>
                </view>
            </view>

            <!-- 导航 -->
            <uni-goods-nav class="goods-nav" :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick"
                @buttonClick="buttonClick" />
        </view>

        <!-- 设置标题 -->
        <set-title ref="setTitleRef" />

        <!-- model提示框 -->
        <u-modal v-model="model.show" :content="model.content" show-cancel-button @confirm="onConfirm"></u-modal>
    </view>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {
    addProductLineCart,
    productLineCollect,
    delProductLineCollect,
    getProductLineIndex,
} from '@/api/productLine';
import config from '@/utils/config';
import setTitle from './components/setTitle.vue';

let baseUrl = config.baseUrl;
let lineList: any = ref([]); //右侧tabber数据
let setTitleRef = ref();
let star = ref(); // 控制收藏
let itemHeight = ref(40)

let model = ref({
    show: false,
    content: '确定重置所选产品？',
});
let flag = ref(false);

let options = ref([
    {
        icon: 'upload',
        text: '导入'
    },
    {
        icon: star.value ? 'star-filled' : 'star',
        text: '收藏',
    },
    {
        icon: 'plusempty',
        text: '设置名称',
    },
]);
let buttonGroup = ref([
    {
        text: '加入购物车',
        backgroundColor: '#ff0000',
        color: '#fff',
    },
    {
        text: '立即购买',
        backgroundColor: '#ffa200',
        color: '#fff',
    },
]);

let lineId = ref(); // 修改的产品线id
let windowHeight = ref() // 屏幕的高度
let isUpload = ref(false) // 判断是否是产品线
let collectData = ref({})

onLoad(() => {
    uploadLine()
});

let fromTop = ref() //  + 到顶部的距离
// 动态获取 + 到顶部的距离
let getInfo = () => {
    nextTick(() => {
        let query = uni.createSelectorQuery().in(this).select('.add');
        query.boundingClientRect((res: any) => {
            fromTop.value = res?.top + 90
            // console.log(res, 'Top.value', res?.top);
        }).exec()
    })
}

// 修改产品线数据初始化
let initProductLine = (lineId: number) => {
    // 获取产品线详细数据
    getProductLineIndex({ lineId }).then((res: any) => {
        if (res.data.code === 200) {
            handleEditProductLineData(res.data.data)
        }
    });
};

// 处理要修改的数据
let handleEditProductLineData = (editData: any) => {
    lineList.value = []
    // 处理子组件数据更新延迟问题
    nextTick(() => {
        // 处理数据
        editData.cartList.forEach((item: any) => {
            item['name'] = item.goodsName;
            item['show'] = false;
            item['url'] = item.picUrl;
            item['status'] = 1;
        });
        // 合并数据
        lineList.value = [...editData.cartList, ...lineList.value]
        if (editData.cartList.length >= 15) itemHeight.value = 28
        if (editData.lineName)
            setTitleRef.value.title = editData.lineName;

        if (!editData.isUpload) heightChange()
        else getImageInfo()
        flag.value = true;
    });
}

// 控制列表的高度
let heightChange = () => {
    nextTick(() => {
        getInfo()
        getImageInfo()
        setTimeout(() => {
            if (windowHeight.value - fromTop.value < 100) {
                if (itemHeight.value === 25) return
                itemHeight.value = itemHeight.value - 5
            }
        }, 50)
    })
}

// 获取图片尺寸
let getImageInfo = () => {
    lineList.value.forEach((item: any) => {
        uni.getImageInfo({
            src: baseUrl + item.url,
            success(res: any) {
                item['imageWidth'] = res.width * 0.3
                item['imageHeight'] = res.height * 0.3
            }
        })
    })
}

// 商品加入购物车等左侧事件
let onClick = (e: any) => {
    if (e.index === 2) {
        setTitleRef.value.showTitle = true;
    } else if (e.index === 1) {
        // 收藏
        if (!star.value) {
            if (JSON.stringify(collectData) === '{}') {
                // 初次收藏
                complete().then((data: any) => {
                    productLineCollect(data).then((res: any) => {
                        if (res.data.code === 200) {
                            collectData.value = {
                                type: 2,
                                valueId: res.data.data.valueId,
                            }
                            star.value = true;
                            options.value[0].icon = 'star-filled';
                            uni.showToast({
                                title: '收藏成功',
                                icon: 'none',
                            });
                        }
                    });
                });
            } else {
                // 收藏取消后收藏
                delProductLineCollect(collectData).then((res: any) => {
                    if (res.data.code === 200) {
                        star.value = true;
                        options.value[0].icon = 'star-filled';
                        uni.showToast({
                            title: '收藏成功',
                            icon: 'none',
                        });
                    }
                });
            }
        } else {
            // 取消收藏
            delProductLineCollect(collectData).then((res: any) => {
                if (res.data.code === 200) {
                    star.value = false;
                    options.value[0].icon = 'star';
                    uni.showToast({
                        title: '取消收藏',
                        icon: 'none',
                    });
                }
            });
        }
    } else {
        uploadLine()
    }
};

// 商品加入购物车等右侧事件
let buttonClick = (e: any) => {
    switch (e.index) {
        case 0:
            addCart();
            break;
        case 1:
            buyNow();
            break;
    }
};

// 加入购物车
let addCart = () => {
    complete().then((data: any) => {
        // 判断是否有失效商品
        if (
            data.item.some((item: any) => {
                return !item.isSubmit && item.deleted;
            })
        )
            return uni.showToast({
                title: '请先删除带红色图标的失效商品',
                icon: 'none',
            });
        // console.log(data, '加入购物车成功');
        // 添加到购物车
        addProductLineCart(data).then((res: any) => {
            if (res.data.code === 200) {
                uni.showToast({
                    title: '加入购物车成功',
                    icon: 'none',
                });
                lineList.value = []
                setTitleRef.value.title = ''
            }
        });
    });
};

// 立即购买
let buyNow = () => {
    complete().then((data: any) => {
        // 判断是否有失效商品
        if (
            data.item.some((item: any) => {
                return !item.isSubmit && item.deleted;
            })
        )
            return uni.showToast({
                title: '请先删除带红色图标的失效商品',
                icon: 'none',
            });
        addProductLineCart(data).then((res: any) => {
            if (res.data.code === 200) {
                if (!uni.getStorageSync('addressId')) {
                    uni.setStorage({
                        key: 'addressId',
                        data: 0,
                    });
                }
                let storage: any = {
                    cartId: 0,
                    couponId: 0,
                };
                Object.keys(storage).forEach((prop: any) => {
                    const el: any = storage[prop];
                    uni.setStorage({
                        key: prop,
                        data: el,
                    });
                });
                uni.navigateTo({
                    url: '../order/checkout?type=' + 'productline' + '&buyNowId=' + res.data.data,
                });
            }
        });
    });
};

// 点击 收藏，加入购物车，立即购买 前逻辑
let complete = () => {
    return new Promise((resolve, reject) => {
        if (lineList.value.length === 0)
            return uni.showToast({
                title: '请先选择产品',
                icon: 'none',
            });
        if (!setTitleRef.value.title)
            return uni.showToast({
                title: '请先设置标题',
                icon: 'none',
            });
        let lineData: any = [...lineList.value]; // 拷贝
        lineData.length = lineData.length - 1; // 删除最后一个数据
        let data = {
            item: lineData,
            title: setTitleRef.value.title,
        };
        resolve(data);
    })
};


// 重置产品线
let reset = () => (model.value.show = true);

// 导入产品线
let uploadLine = () => {
    uni.chooseFile({
        count: 0,
        extension: ['.xlsx'],
        success(res: any) {
            flag.value = false;
            uni.showLoading({
                title: '加载中'
            })
            uni.uploadFile({
                url: baseUrl + '/wx/productLine/upload',
                filePath: res.tempFilePaths[0],
                name: 'file',
                header: { Authorization: uni.getStorageSync('token') },
                success(uploadFileRes: any) {
                    uni.hideLoading()
                    let res = JSON.parse(uploadFileRes.data)
                    if (res.code === 200) {
                        // 判断是否为导入产品线
                        isUpload.value = res.data.isUpload
                        // 清空标题
                        setTitleRef.value.title = '';
                        lineId.value = null
                        // console.log(res.data.isUpload);
                        handleEditProductLineData(res.data)
                    }
                },
                fail() {
                    uni.hideLoading()
                    uni.showToast({
                        title: '导入失败',
                        icon: 'none'
                    })
                }
            })
        }
    })
}

//确认重置
let onConfirm = () => {
    model.value.show = false;
};

</script>

<style lang="scss" scoped>
$nav-heigth: var(--window-bottom);

.add {
    position: absolute;
    width: 180px;
    height: 40px;
    background-color: #fff;
    z-index: 0;
    text-align: center;
    line-height: 45px;
    margin-top: 20rpx;
}

.left-cates {
    width: 190px;
}

.right-cates {
    flex: 1;
    display: flex;
    flex-direction: row;
    justify-content: center;
    // align-items: center;
    background-color: #fff;
    min-height: 100vh;

    .right-cates-list {
        width: 80px;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        text-align: center;
        align-items: center;
    }
}

.u-wrap {
    // height: calc(100vh);
    /* #ifdef H5 */
    // height: calc(100vh - var(--window-top));
    // min-height: 100vh;
    // max-height: 2000px;
    /* #endif */
    display: flex;
    flex-direction: column;
}

.u-menu-wrap {
    flex: 1;
    display: flex;
    overflow: hidden;
    justify-content: space-between;
}

.goods-nav {
    position: fixed;
    bottom: $nav-heigth;
    width: 100%;
    display: inline;
    transform: none;
}
</style>
