<template>
    <view class="companion-select-page">
        <!-- 顶部警告提示 -->
        <view class="warning-tip">
            <view class="warning-icon">
                <uni-icons type="info" size="16" color="#A94F20"></uni-icons>
            </view>
            <view class="warning-text">
                <text>指定之前服务过的伴宠师，需要额外收10元哦！（可多选，最终由系统根据伴宠师的接单时间安排，为您安排您喜欢的伴宠师！</text>
            </view>
        </view>

        <!-- 伴宠师列表 -->
        <scroll-view scroll-y class="companion-scroll">
            <view class="companion-list">
                <view v-for="(item, index) in companionList" :key="index" class="companion-wrapper"
                    :class="{ 'selected': selectedCompanionIds.includes(item.userId) }">
                    <!-- 左侧选中标记 -->
                    <view class="select-icon" @click="selectCompanion(item)">
                        <view class="checkbox-circle" :class="{ 'checked': selectedCompanionIds.includes(item.userId) }">
                            <view class="checkbox-inner" v-if="selectedCompanionIds.includes(item.userId)"></view>
                        </view>
                    </view>

                    <!-- 使用CompanionItem组件 -->
                    <view class="companion-item-wrapper">
                        <companion-item :item="item" @click="handleItemClick" @like="handleItemLike">
                        </companion-item>
                    </view>
                </view>

                <!-- 无数据提示 -->
                <view class="no-data" v-if="companionList.length === 0">
                    <image src="/static/images/personal/no-data.png" mode="aspectFit"></image>
                    <text>暂无伴宠师数据</text>
                </view>
            </view>
        </scroll-view>

        <!-- 底部按钮 -->
        <view class="footer-buttons">
            <view class="cancel-btn" @click="cancel">
                <text>取消</text>
            </view>
            <view class="confirm-btn" @click="confirm">
                <text>确定{{ selectedCompanionIds.length > 0 ? `(${selectedCompanionIds.length})` : '' }}</text>
            </view>
        </view>
    </view>
</template>

<script>
import CompanionItem from '@/components/CompanionItem/CompanionItem.vue'
import { getTecByUser, getOrderDetail, getTeacherDetail } from '@/api/order/order.js'
import { getOpenIdKey } from '@/utils/auth'
import { getAddressDetails } from '@/api/system/address.js'
import { mapState } from 'vuex'
import positionMixin from '@/mixins/position'


export default {
    mixins: [positionMixin],
    components: {
        CompanionItem
    },
    data() {
        return {
            companionList: [],
            selectedCompanionIds: [],
            defaultTeacherId: null, // 默认选中的技师ID（用于再来一单）
            originalOrderData: null, // 原始订单数据
            orderId: null, // 订单ID
        };
    },
    computed: {
        ...mapState(['teacherLevelList']),
        // 获取当前选中的伴宠师列表
        selectedCompanions() {
            if (this.selectedCompanionIds.length === 0) return [];
            return this.companionList.filter(item => this.selectedCompanionIds.includes(item.userId));
        }
    },
    onLoad(options) {
        // 获取传递的技师ID（用于再来一单时默认选中）
        if (options.teacherId) {
            this.defaultTeacherId = options.teacherId;
        }
        // 获取订单ID（用于再来一单时获取订单详情）
        if (options.orderId) {
            this.orderId = options.orderId;
            this.loadOrderData();
        }
        // 获取选择过的伴宠师列表
        this.getServicedCompanions();
    },
    onPullDownRefresh() {
        this.getServicedCompanions()
    },
    methods: {
        // 获取服务过的伴宠师
        getServicedCompanions() {
            console.log(getOpenIdKey())
            getTecByUser({
                openId: getOpenIdKey()
            }).then(res => {
                uni.stopPullDownRefresh()
                if (res && res.code == 200) {
                    this.companionList = res.data || [];
                    
                    // 如果有默认技师ID，自动选中该技师
                    if (this.defaultTeacherId) {
                        const defaultCompanion = this.companionList.find(item => item.userId == this.defaultTeacherId);
                        if (defaultCompanion && !this.selectedCompanionIds.includes(this.defaultTeacherId)) {
                            this.selectedCompanionIds.push(this.defaultTeacherId);
                        }
                    }
                }
            }).catch(err => {
                uni.stopPullDownRefresh()
                console.error('获取服务过的伴宠师失败', err);
            });

        },

        // 加载订单数据
        async loadOrderData() {
            if (!this.orderId) return;
            
            const params = {
                openId: getOpenIdKey(),
                orderId: this.orderId
            };
            
            try {
                const res = await getOrderDetail(params);
                if (res) {
                    this.originalOrderData = res;
                } else {
                    console.error('获取订单详情失败');
                }
            } catch (error) {
                console.error('获取订单数据失败', error);
            }
        },

        // 选择伴宠师（多选）
        selectCompanion(companion) {
            const userId = companion.userId;
            const index = this.selectedCompanionIds.indexOf(userId);

            if (index > -1) {
                // 如果已选中，则取消选中
                this.selectedCompanionIds.splice(index, 1);
            } else {
                // 如果未选中，则添加到选中列表
                this.selectedCompanionIds.push(userId);
            }
        },

        // 处理伴宠师列表项点击事件
        handleItemClick(item) {
            // 点击伴宠师项时选中该伴宠师
            this.selectCompanion(item);
        },

        // 处理伴宠师列表项点赞事件
        handleItemLike(item) {
            // 这里可以添加点赞的业务逻辑
            console.log('点赞伴宠师:', item);
        },

        // 取消选择
        cancel() {
            uni.navigateBack();
        },

        // 确认选择
        confirm() {
            if (this.selectedCompanionIds.length === 0) {
                uni.showToast({
                    title: '请至少选择一个伴宠师',
                    icon: 'none'
                });
                return;
            }

            this.submit()
        },

        async submit() {
            let order = this.originalOrderData

            this.$globalData.newOrderData.originalOrderData = order

            this.$globalData.newOrderData.moreOrderPrice = 10

            // 验证地址是否存在
            if (order.addressId) {
                try {
                    const addressRes = await getAddressDetails(order.addressId);
                    if (addressRes && addressRes.id) {
                        // 地址存在，设置地址信息
                        this.$globalData.newOrderData.currentAddress = {
                            id: order.addressId,
                            name: order.receiverName,
                            phone: order.receiverPhone,
                            province: order.receiverProvince,
                            city: order.receiverCity,
                            district: order.receiverDistrict,
                            detailAddress: order.receiverDetailAddress,
                            latitude: order.latitude,
                            longitude: order.longitude,
                        }
                    } else {
                        // 地址不存在，不设置地址信息
                        console.log('地址不存在，addressId:', order.addressId);
                        this.$globalData.newOrderData.currentAddress = {};
                    }
                } catch (error) {
                    console.error('验证地址失败:', error);
                    // 验证失败时也不设置地址信息
                    this.$globalData.newOrderData.currentAddress = {};
                }
            } else {
                // 没有地址ID，不设置地址信息
                this.$globalData.newOrderData.currentAddress = {};
            }

            if (order.teacherId) {
                getTeacherDetail({
                    userId: order.teacherId
                }).then(response => {
                    if (response) {
                        let companionInfo = response
                        companionInfo.distanceText = this.calculateDistanceAddress(response.appletAddresseList)
                        this.buyInfo.teacher = companionInfo
                    }
                })
            }

            if (order.companionLevel) {
                this.$globalData.newOrderData.companionLevel =
                    this.teacherLevelList.find(item => item.paramValueNum == order.companionLevel);
            }

            // 处理提前熟悉相关数据
            if (order.needPreFamiliarize) {
                this.$globalData.newOrderData.needPreFamiliarize = ['是否提前熟悉']
            }

            // 组装宠物数据
            if (order.petVOList && order.petVOList.length > 0) {
                this.$globalData.newOrderData.currentPets = order.petVOList.map(pet => {
                    // 获取该宠物的服务日期
                    const petServices = order.orderServiceList.filter(service => service.petId === pet.id);
                    const selectedDate = petServices.map(service => ({
                        date: service.serviceDate,
                        info: "预定"
                    }));

                    return {
                        ...pet,
                        checked: ['checked'], // 默认选中
                        selectedDate,
                    };
                });
            }

            uni.navigateTo({
                url: `/pages/newOrder/serviceNew`
            });
        },

        // 查看伴宠师详情
        viewCompanionDetail(companionId) {
            // 跳转到伴宠师详情页面
            uni.navigateTo({
                url: `/pages_order/companionPetList/companionPetInfo?id=${companionId}`
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.companion-select-page {
    background-color: #F5F5F5;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    padding-bottom: 120rpx;
}


.warning-tip {
    background-color: #FFF4E5;
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;
    margin: 20rpx;

    .warning-icon {
        margin-right: 10rpx;
    }

    .warning-text {
        flex: 1;
        font-size: 24rpx;
        color: #A94F20;
        line-height: 1.4;
    }
}

.companion-scroll {
    flex: 1;
    height: calc(100vh - 250rpx);
}

.companion-list {
    padding: 10rpx;
    padding-right: 0;
}

.companion-wrapper {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    padding: 10rpx;
    display: flex;
    align-items: center;

    .select-icon {
        margin-right: 10rpx;

        .checkbox-circle {
            width: 45rpx;
            height: 45rpx;
            border: 2rpx solid #DDDDDD;
            background-color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            &.checked {
                border-color: #FFAA48;
                background-color: #FFAA48;
            }

            .checkbox-inner {
                width: 16rpx;
                height: 10rpx;
                border: 2rpx solid #FFFFFF;
                border-top: none;
                border-right: none;
                transform: rotate(-45deg);
                margin-top: -4rpx;
            }
        }
    }

    .companion-item-wrapper {
        flex: 1;
    }
}

.no-data {
    text-align: center;

    image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
    }

    text {
        font-size: 28rpx;
        color: #999;
    }
}

.footer-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 20rpx 30rpx;
    background-color: #FFFFFF;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .cancel-btn,
    .confirm-btn {
        flex: 1;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        border-radius: 44rpx;
        font-size: 30rpx;
    }

    .cancel-btn {
        background-color: #FFFFFF;
        color: #666;
        border: 1px solid #DDDDDD;
        margin-right: 20rpx;
    }

    .confirm-btn {
        background-color: #FFAA48;
        color: #FFFFFF;
        box-shadow: 0 4rpx 8rpx rgba(255, 170, 72, 0.3);
    }
}
</style>