<template>
    <view style="width: 100%;">
        <view class="u-wrap">
            <view class="u-menu-wrap">
                <view class="right-cates">
                    <view class="right-cates-list">
                        <u-cell-group>
                            <u-cell-item icon="" :title="item.goodsName" :arrow="false"
                                v-for="(item, index) in lineList">
                                <!-- <template #title>
                                    {{ item.goodsName }}
                                </template> -->
                                <template #right-icon>
                                    <view style="margin-left: 30rpx;">
                                        <u-tag v-show="item.size" :text="item.size" type="info" size="mini"
                                            style="margin-right: 10rpx;" />
                                        <u-tag v-show="item.SDTrack" :text="item.SDTrack" type="info" size="mini"
                                            style="margin-right: 10rpx;" />
                                        <u-tag v-show="item.Segs" :text="item.Segs" type="info" size="mini" />
                                    </view>

                                </template>
                            </u-cell-item>
                        </u-cell-group>
                        <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 { onBackPress, onReady } from '@dcloudio/uni-app';
import {
    addProductLineCart,
    productLineCollect,
    delProductLineCollect,
    getLineSpecification,
    getProductLineReAdd
} 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 model = ref({
    show: false,
    content: '确定重置所选产品？',
});

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 lineName = ref(); // 修改的产品线名称
let collectData = ref({})
let specificationData = ref([] as any)

onReady(() => {
    lineList.value = []
    setTitleRef.value.title = ''
    uni.$on('importProductLineData', (res: any) => {
        if (res.data.lineId) {
            lineId.value = res.data.lineId
            lineName.value = res.data.lineName
        } else lineId.value = null // 判断是否为导入产品线
        let dataArr = [] as any
        // 集合goodsId数组
        res.data.cartList.map((item: any) => {
            if (item.goodsId) dataArr.push(item.goodsId)
        })
        // 获取规格键值集合
        getLineSpecification(dataArr).then((res: any) => {
            if (res.data.code === 200) specificationData.value = res.data.data
        })
        handleEditProductLineData(res.data)
        // console.log(res.data);
    })
})

// 匹配规格 SDTrack: 单轨/双轨 size: 长度（MM) Segs: 分段数
let matchSpecifications = () => {
    lineList.value.forEach((line: any) => {
        for (let spec in specificationData.value) {
            if (line.goodsId == spec) {
                for (let item in specificationData.value[spec])
                    if (item === "长度（MM)" || item === "单轨/双轨" || item === "分段数") {
                        specificationData.value[spec][item].map((i: any) => {
                            let index = line.specifications.indexOf(i.value)
                            if (index !== -1) {
                                switch (i.specification) {
                                    case '长度（MM)':
                                        line['size'] = i.value
                                        break;
                                    case '单轨/双轨':
                                        line['SDTrack'] = i.value
                                        break;
                                    case '分段数':
                                        line['Segs'] = i.value
                                        break;
                                }
                            }
                        })
                    }
            }
        }
    })
}

// 处理要修改的数据
let handleEditProductLineData = (editData: any) => {
    lineList.value = []
    // 处理子组件数据更新延迟问题
    nextTick(() => {
        // 合并数据
        lineList.value = [...editData.cartList, ...lineList.value]
        setTimeout(() => {
            matchSpecifications()
        }, 50)
        getImageInfo()
    });
}

// 获取图片尺寸
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 === 1) {
        setTitleRef.value.showTitle = true;
        if (lineName.value) setTitleRef.value.title = lineName.value
    } else {
        // 收藏
        if (!star.value) {
            if (JSON.stringify(collectData.value) === '{}') {
                // 初次收藏
                if (lineName.value) setTitleRef.value.title = lineName.value
                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.value).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.value).then((res: any) => {
                if (res.data.code === 200) {
                    star.value = false;
                    options.value[0].icon = 'star';
                    uni.showToast({
                        title: '取消收藏',
                        icon: 'none',
                    });
                }
            });
        }
    }
};

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

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

// 立即购买
let buyNow = () => {
    if (lineName.value) setTitleRef.value.title = lineName.value
    complete().then((data: any) => {
        // 判断是否有失效商品
        if (
            data.item.some((item: any) => {
                return !item.isSubmit && item.deleted;
            })
        )
            return uni.showToast({
                title: '请先删除带红色图标的失效商品',
                icon: 'none',
            });
        data['isUpload'] = true
        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 onConfirm = () => {
    model.value.show = false;
};

// 返回刷新页面
onBackPress((options: any) => {
    // if (options.from === 'backbutton') {
    //     uni.navigateBack()
    // }
    setTimeout(() => {
        uni.reLaunch({ url: './productLine' })
    }, 50)
})

</script>

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

:deep(.u-cell_title) {
    // min-width: 100px;
    // max-width: 200px;
    width: 150px;
}

.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: 100%;
        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;
    z-index: 999;
}
</style>
