<template>
    <uv-popup ref="popup" :round="10">
        <view class="companion-popup" v-if="type == 0">
            <view class="popup-header">
                <text class="popup-title">是否指定之前服务过的伴宠师</text>
                <view class="popup-close" @click="close">
                    <uni-icons type="close" size="20" color="#999"></uni-icons>
                </view>
            </view>
            <view class="popup-content">
                <view class="option-item" @click="selectOption('yes')">
                    <text class="option-text">是</text>
                    <view class="option-circle" :class="{'selected': selectedOption === 'yes'}">
                        <view class="option-inner" v-if="selectedOption === 'yes'"></view>
                    </view>
                </view>
                <view class="option-item" @click="selectOption('no')">
                    <text class="option-text">否</text>
                    <view class="option-circle" :class="{'selected': selectedOption === 'no'}">
                        <view class="option-inner" v-if="selectedOption === 'no'"></view>
                    </view>
                </view>
            </view>
        </view>
        <view class="companion-popup" v-else>
            <view class="popup-header">
                <text class="popup-title">请选择您喜欢的下单方式</text>
                <view class="popup-close" @click="close">
                    <uni-icons type="close" size="20" color="#999"></uni-icons>
                </view>
            </view>
            <view class="popup-content">
                <view class="option-item" @click="selectOption('系统下单')">
                    <text class="option-text">系统下单</text>
                    <view class="option-circle" :class="{'selected': selectedOption === 'yes'}">
                        <view class="option-inner" v-if="selectedOption === 'yes'"></view>
                    </view>
                </view>
                <view class="option-item" @click="selectOption('指定伴宠师')">
                    <text class="option-text">指定伴宠师</text>
                    <view class="option-circle" :class="{'selected': selectedOption === 'no'}">
                        <view class="option-inner" v-if="selectedOption === 'no'"></view>
                    </view>
                </view>
            </view>
        </view>
    </uv-popup>
</template>

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

export default {
    mixins: [positionMixin],
    data() {
        return {
            selectedOption: '',
            type : 0,
            teacherId: null, // 技师ID（用于再来一单时传递）
            orderId: null, // 订单ID（用于再来一单时传递）
            originalOrderData: null, // 原始订单数据
            buyInfo: {
                teacher: null // 技师信息
            }
        }
    },
    computed: {
        ...mapState(['teacherLevelList']),
    },
    methods: {
        // 打开弹窗
        async open(teacherId = null, orderId = null) {
            this.selectedOption = '';
            this.type = 0;
            this.teacherId = teacherId;
            this.orderId = orderId;
            
            // 如果有订单ID，加载订单数据
            if (this.orderId) {
                await this.loadOrderData();
            }
            
            this.$refs.popup.open('bottom');
        },
        
        // 加载订单数据
        async loadOrderData() {
            if (!this.orderId) return;
            
            const params = {
                openId: getOpenIdKey(),
                orderId: this.orderId
            };
            
            try {
                const res = await getOrderDetail(params);
                if (res) {
                    this.originalOrderData = res;
                    console.log('获取订单详情成功:', res);
                } else {
                    console.error('获取订单详情失败');
                }
            } catch (error) {
                console.error('获取订单数据失败', error);
            }
        },
        
        // 关闭弹窗
        close() {
            this.$refs.popup.close();
        },

        // async submit() {
        //     // 如果有订单数据，处理订单数据
        //     if (this.originalOrderData) {
        //         await this.processOrderData();
        //     }

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

        // 处理订单数据，设置定位和位置信息
        async processOrderData() {
            if (!this.originalOrderData) return;
            
            uni.showLoading({
                title: '加载中...',
                mask: true
            })

            const 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: parseFloat(order.latitude) || 0,
                            longitude: parseFloat(order.longitude) || 0,
                        }
                        console.log('设置地址信息成功，包含定位:', {
                            latitude: order.latitude,
                            longitude: order.longitude
                        });
                    } else {
                        // 地址不存在，但仍然尝试从订单数据中获取定位信息
                        console.log('地址不存在，addressId:', order.addressId);
                        this.$globalData.newOrderData.currentAddress = {};
                    }
                } catch (error) {
                    // 验证失败时也不设置地址信息，但仍然尝试设置定位
                    this.$globalData.newOrderData.currentAddress = {};
                }
            } else {
                // 没有地址ID，但仍然尝试从订单数据中获取定位信息
                this.$globalData.newOrderData.currentAddress = {};
            }
            
            // 处理技师信息
            // if (order.teacherId) {
            //     try {
            //         const teacherRes = await getTeacherDetail({
            //             userId: order.teacherId
            //         });
            //         if (teacherRes) {
            //             let companionInfo = teacherRes;
            //             // 计算距离（需要当前位置信息）
            //             if (teacherRes.appletAddresseList && this.$globalData.newOrderData.latitude && this.$globalData.newOrderData.longitude) {
            //                 companionInfo.distanceText = this.calculateDistanceAddress(teacherRes.appletAddresseList);
            //             }
            //             this.buyInfo.teacher = companionInfo;
            //             // 将技师信息也设置到全局数据中
            //             this.$globalData.newOrderData.selectedTeacher = companionInfo;
            //             console.log('设置技师信息成功:', companionInfo);
            //         }
            //     } catch (error) {
            //         console.error('获取技师详情失败:', error);
            //     }
            // }
            
            // 处理伴宠师等级
            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.hideLoading();
        },

        // 选择选项
        async selectOption(option) {
            this.selectedOption = option;

            if(this.type == 1){
                if (option === '系统下单') {
                    // 如果有订单数据，处理订单数据
                    if (this.originalOrderData) {
                        await this.processOrderData();
                    }

                    this.close();
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/newOrder/serviceNew'
                        });
                    }, 300);
                } else if (option === '指定伴宠师') {
                    // 如果有订单数据，处理订单数据
                    if (this.originalOrderData) {
                        await this.processOrderData();
                    }

                    let locationInfo = this.$globalData.newOrderData.currentAddress;


                    if(!locationInfo || 
                        !locationInfo.latitude ||
                        !locationInfo.longitude
                    ){
                        this.selectLocation();
                        return
                    }

                    let address = locationInfo.province + locationInfo.city + locationInfo.district + locationInfo.detailAddress;

                    // 构建位置信息对象
                    const allInfo = {
                        isCheckLocation: true,
                        locationName: address,
                        locationLongitude: locationInfo.longitude,
                        locationLatitude: locationInfo.latitude,
                        locationAddress: address,
                        selectedDate: [],
                        isCheckTime: false,
                        selectedDateShowText: '',
                    };

                    this.$store.commit('setPosition', {
                        address: address,
                        longitude: locationInfo.longitude,
                        latitude: locationInfo.latitude,
                        date : [],
                    })

                    this.close();
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages_order/companionPetList/companionPetList?info=' + encodeURIComponent(JSON.stringify(allInfo))

                        });
                    }, 300);
                }
                return
            }
            
            // 如果选择"是"，跳转到伴宠师选择页面
            if (option === 'yes') {
                this.close();
                setTimeout(async () => {
                    // 如果有订单数据，先处理订单数据并设置定位信息
                    if (this.originalOrderData) {
                        await this.processOrderData();
                    }
                    
                    let url = '/pages_order/order/companionSelect';
                    let params = [];
                    // 如果有技师ID，添加到URL参数中
                    if (this.teacherId) {
                        params.push(`teacherId=${this.teacherId}`);
                    }
                    // 如果有订单ID，添加到URL参数中
                    if (this.orderId) {
                        params.push(`orderId=${this.orderId}`);
                    }
                    if (params.length > 0) {
                        url += `?${params.join('&')}`;
                    }
                    uni.navigateTo({
                        url: url
                    });
                }, 300);
            } else if (option === 'no') {
                this.type = 1;
                this.selectedOption = '';
            }
        },
        
        // 选择定位
        selectLocation() {
            wx.chooseLocation({
                type: 'gcj02',
                success: (res) => {
                    console.log('选择的位置：', res);
                    
                    // 构建位置信息对象
                    const allInfo = {
                        isCheckLocation: true,
                        locationName: res.address,
                        locationLongitude: res.longitude,
                        locationLatitude: res.latitude,
                        locationAddress: res.address,
                        selectedDate: [],
                        isCheckTime: false,
                        selectedDateShowText: '',
                    };

                    this.$store.commit('setPosition', {
                        address: res.address,
                        longitude: res.longitude,
                        latitude: res.latitude,
                        date : [],
                    })
                    
                    // 跳转到伴宠师列表页面，传递位置信息
                    uni.navigateTo({
                        url: `/pages_order/companionPetList/companionPetList?info=` + encodeURIComponent(JSON.stringify(allInfo))
                    })
                },
                fail: (err) => {
                    console.error('选择位置失败：', err);
                    uni.showToast({
                        title: '选择位置失败，请重试',
                        icon: 'none',
                        duration: 2000
                    })
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.companion-popup {
    position: relative;
    background-color: #FFFFFF;
    border-radius: 20rpx;
    
    .popup-header {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx 20rpx;
        position: relative;
        
        .popup-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            text-align: center;
        }
        
        .popup-close {
            position: absolute;
            right: 20rpx;
            top: 30rpx;
        }
    }
    
    .popup-content {
        padding: 20rpx 30rpx 50rpx;
        
        .option-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 100rpx;
            border-radius: 10rpx;
            background-color: #F8F8F8;
            margin-bottom: 20rpx;
            padding: 0 30rpx;
            
            // &:first-child {
            //     background-color: #FFF9E6;
                
            //     .option-text {
            //         color: #FFAA48;
            //     }
            // }
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .option-text {
                font-size: 28rpx;
                color: #333;
            }
            
            .option-circle {
                width: 36rpx;
                height: 36rpx;
                border-radius: 50%;
                border: 2rpx solid #DDDDDD;
                display: flex;
                align-items: center;
                justify-content: center;
                
                &.selected {
                    border-color: #FFAA48;
                }
                
                .option-inner {
                    width: 24rpx;
                    height: 24rpx;
                    border-radius: 50%;
                    background-color: #FFAA48;
                }
            }
        }
    }
}
</style>