import { getOrderInfo, getOrderLogs, uploadFile, clockIn } from '@/api/fulfiller'
import { getServiceList } from '@/api/service'

export default {
    data() {
        return {
            orderId: null,
            orderType: 1,
            orderStatus: 2,

            stepsPickup: ['到达打卡', '确认出发', '送达打卡'],
            stepsWalkWash: ['到达打卡', '开始服务', '服务结束'],

            currentStep: 1,

            orderDetail: {
                type: 1,
                price: '0.00',
                timeLabel: '服务时间',
                time: '',
                petAvatar: '/static/dog.png',
                petName: '',
                petBreed: '',
                serviceTag: '',
                startLocation: '',
                startAddress: '',
                endLocation: '',
                endAddress: '',
                serviceContent: '',
                remark: '',
                orderNo: '',
                createTime: '',
                progressLogs: []
            },

            serviceList: [],
            showPetModal: false,
            currentPetInfo: {},
            showNavModal: false,
            navTargetPointType: '',

            showUploadModal: false,
            modalMediaList: [],
            modalRemark: '',

            showSumModal: false,
            sumContent: '',
            sumDate: '',
            sumSigner: '张*哥',

            showPetRemarkInput: false,
            petRemarkText: ''
        }
    },
    computed: {
        steps() {
            return this.orderType === 1 ? this.stepsPickup : this.stepsWalkWash;
        },
        displayStatusText() {
            if (this.currentStep === 4) return '待商家确认';
            if (this.currentStep >= this.steps.length) return '已完成';
            let status = this.steps[this.currentStep];
            if (status === '已完成' || status === '完成') return '已完成';
            if (status === '已拒绝') return '已拒绝';
            if (status === '接单') {
                return this.orderType === 1 ? '待接送' : '待服务';
            }
            // 对于其他活跃状态 (出发, 到达, 送达, 开始, 结束)
            return this.orderType === 1 ? '配送中' : '服务中';
        },
        currentStatusText() {
            if (this.currentStep === 4) return '待确认';
            return this.currentStep >= this.steps.length ? '已完成' : this.steps[this.currentStep];
        },
        currentTaskTitle() {
            if (this.currentStep === 4) return '待商家确认';
            if (this.currentStep >= this.steps.length) return '订单已完成';
            let action = this.steps[this.currentStep];
            if (action === '到达打卡') return '到达打卡';
            if (action === '开始服务') return '开始服务';
            if (action === '确认出发') return '确认出发';
            if (action === '送达打卡' || action === '服务结束') return '服务完成';
            return action;
        },
        currentTaskDesc() {
            if (this.currentStep === 4) return '服务已提交，请等待商家确认完成后即可结束订单';
            if (this.currentStep >= this.steps.length) return '感谢您的服务，请注意休息';
            let action = this.steps[this.currentStep];
            if (action === '到达打卡') {
                return '打卡穿着工装消毒站门口的照片或视频';
            }
            if (this.orderType === 1) {
                if (action === '确认出发') return '拍摄宠物上车/出发时的状态照片或视频';
                if (action === '送达打卡') return '打卡确认送达的照片或视频';
            } else {
                if (action === '开始服务') return '开始服务并拍摄照片 or 视频';
                if (action === '服务结束') return '服务完成拍摄照片或视频';
            }
            return '请按要求提交照片或视频及备注';
        }
    },
    async onLoad(options) {
        if (options.id) {
            this.orderId = options.id
        }
        await this.loadServiceList()
        await this.loadOrderDetail()
    },
    methods: {
        async loadServiceList() {
            try {
                const res = await getServiceList()
                this.serviceList = res.data || []
            } catch (err) {
                console.error('获取服务类型失败:', err)
            }
        },
        async loadOrderDetail() {
            if (!this.orderId) {
                console.log('订单ID缺失')
                uni.showToast({ title: '订单ID缺失', icon: 'none' })
                return
            }
            try {
                console.log('请求订单详情，ID:', this.orderId)
                const res = await getOrderInfo(this.orderId)
                console.log('订单详情响应:', res)
                const order = res.data
                if (!order) {
                    console.log('订单数据为空')
                    uni.showToast({ title: '订单不存在', icon: 'none' })
                    return
                }
                console.log('订单数据:', order)
                this.transformOrderData(order)
                await this.loadOrderLogs()
            } catch (err) {
                console.error('获取订单详情失败:', err)
                uni.showToast({ title: '加载失败', icon: 'none' })
            }
        },
        async loadOrderLogs() {
            try {
                const res = await getOrderLogs(this.orderId)
                const logs = res.data || []
                console.log('订单日志:', logs)
                if (logs.length > 0) {
                    console.log('第一条日志详情:', JSON.stringify(logs[0]))
                }
                const progressLogs = logs.filter(log => log.logType === 1)
                this.orderDetail.progressLogs = progressLogs.map(log => ({
                    status: log.title || '',
                    time: log.createTime || '',
                    medias: log.photoUrls || [],
                    remark: log.content || ''
                }))

                // 根据打卡日志的 actionType 确定下一步骤。规则：最新的打卡记录是什么，下一步就往后延。
                // 仅筛选打卡类型的日志(logType: 1)，并按时间倒序排列，取最新的一条作为当前进度的基准
                const validLogs = logs.filter(log => log.logType === 1 && log.actionType !== undefined)
                    .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())

                if (validLogs.length > 0) {
                    const latestLog = validLogs[0]
                    const actionType = latestLog.actionType

                    // 如果日志显示待商家确认，则为无需打卡
                    if (latestLog.actionType >= 7) {
                        this.currentStep = 4 // 无需打卡状态
                    } else if (actionType === 7) {
                        this.currentStep = 3 // 已完成
                    } else if (actionType === 6) {
                        this.currentStep = 2 // 当前应进行：送达打卡/服务结束
                    } else if (actionType === 4) {
                        this.currentStep = 1 // 当前应进行：确认出发/开始服务
                    } else if (actionType === 2 || actionType === 3) {
                        this.currentStep = 0 // 已接单，当前应进行：到达打卡
                    } else {
                        this.currentStep = 0
                    }
                } else {
                    this.currentStep = 0
                }
                console.log('根据最新日志推算的当前步骤:', this.currentStep)
            } catch (err) {
                console.error('获取订单日志失败:', err)
            }
        },
        transformOrderData(order) {
            const mode = order.mode || 0
            const isRoundTrip = mode === 1

            this.orderType = isRoundTrip ? 1 : 2
            this.orderStatus = order.status || 2

            this.orderDetail = {
                type: this.orderType,
                price: (order.price / 100).toFixed(2),
                timeLabel: isRoundTrip ? '取货时间' : '服务时间',
                time: order.serviceTime || '',
                petAvatar: '/static/dog.png',
                petName: order.petName || order.contact || '',
                petBreed: order.breed || '',
                serviceTag: order.groupPurchasePackageName || '',
                startLocation: order.fromAddress || '',
                startAddress: order.fromAddress || '',
                endLocation: (order.contact || '') + ' ' + (order.contactPhoneNumber || ''),
                endAddress: order.toAddress || '',
                serviceContent: '',
                remark: '',
                orderNo: order.code || 'T' + order.id,
                createTime: order.serviceTime || '',
                progressLogs: [
                    { status: '您已接单', time: order.serviceTime || '' }
                ]
            }
        },
        updateStepByStatus() {
            if (this.orderStatus === 2) {
                this.currentStep = 0
            } else if (this.orderStatus === 3) {
                this.currentStep = 1
            } else if (this.orderStatus === 5) {
                this.currentStep = this.steps.length - 1
            } else {
                this.currentStep = 0
            }
        },
        showPetProfile() {
            // Use orderDetail basic info and mock the rest
            this.currentPetInfo = {
                ...this.orderDetail,
                petGender: 'M',
                petAge: '2岁',
                petWeight: '15kg',
                petPersonality: '活泼亲人，精力旺盛',
                petHobby: '喜欢追飞盘，爱吃肉干',
                petRemark: '肠胃较弱，不能乱喂零食；出门易爆冲，请拉紧牵引绳。',
                petTags: ['拉响警报', '不能吃鸡肉', '精力旺盛'],
                petLogs: [
                    { date: '2026-02-09 14:00', content: '今天遛弯拉了两次粑粑，精神状态很好。', recorder: '王阿姨' },
                    { date: '2026-02-08 10:30', content: '有些挑食，剩了小半碗狗粮。', recorder: '李师傅' },
                    { date: '2026-02-05 09:00', content: '建档。', recorder: '系统记录' }
                ]
            };
            this.showPetModal = true;
        },
        closePetProfile() {
            this.showPetModal = false;
        },
        openPetRemarkInput() {
            this.petRemarkText = '';
            this.showPetRemarkInput = true;
        },
        closePetRemarkInput() {
            this.showPetRemarkInput = false;
        },
        submitPetRemark() {
            if (!this.petRemarkText.trim()) {
                uni.showToast({ title: '备注内容不能为空', icon: 'none' });
                return;
            }
            const now = new Date();
            const date = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`;
            if (!this.currentPetInfo.petLogs) {
                this.currentPetInfo.petLogs = [];
            }
            this.currentPetInfo.petLogs.unshift({
                date: date,
                content: this.petRemarkText,
                recorder: '张*哥'
            });
            this.closePetRemarkInput();
            uni.showToast({ title: '备注已添加', icon: 'success' });
        },
        goToAnomaly() {
            uni.navigateTo({
                url: '/pages/orders/anomaly?orderId=' + (this.orderDetail.orderNo || '')
            });
        },
        callPhone() {
            uni.makePhoneCall({ phoneNumber: '18900008451' });
        },
        openNavigation(type) {
            this.navTargetPointType = type;
            this.showNavModal = true;
        },
        closeNavModal() {
            this.showNavModal = false;
        },
        chooseMap(mapType) {
            let pointType = this.navTargetPointType;
            let name = pointType === 'start' ? this.orderDetail.startLocation : this.orderDetail.endLocation;
            let address = pointType === 'start' ? this.orderDetail.startAddress : this.orderDetail.endAddress;

            this.showNavModal = false;

            uni.openLocation({
                latitude: 30.52, // Mock lat
                longitude: 114.31, // Mock lng
                name: name || '目的地',
                address: address || '默认地址',
                success: function () {
                    console.log('打开导航成功: ' + mapType);
                }
            });
        },
        openUploadModal() {
            this.modalMediaList = [];
            this.modalRemark = '';
            this.showUploadModal = true;
        },
        closeUploadModal() {
            this.showUploadModal = false;
        },
        handleConfirmUpload() {
            console.log('handleConfirmUpload被调用');
            this.confirmUploadModal();
        },
        async chooseModalMedia() {
            console.log('chooseModalMedia被调用');
            uni.chooseImage({
                count: 5 - this.modalMediaList.length,
                success: async (res) => {
                    console.log('选择图片成功，文件路径:', res.tempFilePaths);
                    uni.showLoading({ title: '上传中...' });
                    try {
                        for (const filePath of res.tempFilePaths) {
                            console.log('上传文件:', filePath);
                            const uploadRes = await uploadFile(filePath);
                            console.log('上传响应:', uploadRes);
                            if (uploadRes.code === 200) {
                                this.modalMediaList.push({
                                    url: uploadRes.data.url,
                                    ossId: uploadRes.data.ossId,
                                    localPath: filePath
                                });
                                console.log('上传成功，url:', uploadRes.data.url);
                            }
                        }
                        uni.hideLoading();
                        console.log('当前modalMediaList:', this.modalMediaList);
                        uni.showToast({ title: '上传成功', icon: 'success' });
                    } catch (err) {
                        uni.hideLoading();
                        console.error('上传失败:', err);
                        uni.showToast({ title: '上传失败', icon: 'none' });
                    }
                },
                fail: (err) => {
                    console.error('选择图片失败:', err);
                }
            });
        },
        removeModalMedia(index) {
            this.modalMediaList.splice(index, 1);
        },
        getCurrentTime() {
            const now = new Date();
            const y = now.getFullYear();
            const m = String(now.getMonth() + 1).padStart(2, '0');
            const d = String(now.getDate()).padStart(2, '0');
            const h = String(now.getHours()).padStart(2, '0');
            const min = String(now.getMinutes()).padStart(2, '0');
            return `${y}/${m}/${d} ${h}:${min}`;
        },
        async confirmUploadModal() {
            console.log('confirmUploadModal被调用，文件数量:', this.modalMediaList.length);
            if (this.modalMediaList.length === 0) {
                uni.showToast({ title: '请上传至少一张图片或视频', icon: 'none' });
                return;
            }

            try {
                uni.showLoading({ title: '提交中...' });
                const uploadedMedias = this.modalMediaList.map(item => item.url);
                const ossIds = this.modalMediaList.map(item => item.ossId);

                console.log('准备打卡，ossIds:', ossIds);

                const currentAction = this.steps[this.currentStep];
                let clockInType = 4;
                if (currentAction === '到达打卡') {
                    clockInType = 4;
                } else if (currentAction === '确认出发' || currentAction === '开始服务') {
                    clockInType = 6;
                } else if (currentAction === '送达打卡' || currentAction === '服务结束') {
                    clockInType = 7;
                }

                const clockInData = {
                    orderId: this.orderId,
                    photos: ossIds,
                    content: this.modalRemark || '',
                    type: clockInType,
                    title: this.currentTaskTitle
                };

                console.log('打卡数据:', clockInData);
                await clockIn(clockInData);
                uni.hideLoading();

                this.closeUploadModal();
                uni.showToast({ title: '打卡成功', icon: 'success' });

                await this.loadOrderDetail();
            } catch (err) {
                uni.hideLoading();
                console.error('打卡失败:', err);
                uni.showToast({ title: '打卡失败，请重试', icon: 'none' });
            }
        },
        copyOrderNo() {
            uni.setClipboardData({
                data: this.orderDetail.orderNo,
                success: () => {
                    uni.showToast({ title: '复制成功', icon: 'none' });
                }
            });
        },
        openSumModal() {
            // 初始化日期
            const now = new Date();
            const y = now.getFullYear();
            const m = String(now.getMonth() + 1).padStart(2, '0');
            const d = String(now.getDate()).padStart(2, '0');
            this.sumDate = `${y}/${m}/${d}`;

            // 预设服务内容模板
            if (!this.sumContent) {
                this.sumContent =
                    '1. 精神/身体状态：\n' +
                    '2. 进食/饮水：\n' +
                    '3. 排泤情况：\n' +
                    '4. 卫生情况：\n' +
                    '5. 互动情况：\n' +
                    '6. 特殊情况/备注：';
            }
            this.showSumModal = true;
        },
        closeSumModal() {
            this.showSumModal = false;
        },
        submitSumModal() {
            if (!this.sumContent.trim()) {
                uni.showToast({ title: '请填写服务内容', icon: 'none' });
                return;
            }
            this.closeSumModal();
            uni.showToast({ title: '小结已提交', icon: 'success' });
        }
    }
}
