import { getMyOrders } from '@/api/fulfiller'
import { getServiceList } from '@/api/service'

export default {
    data() {
        return {
            currentTab: 0,
            tabs: ['待接送/服务', '配送/服务中', '已完成', '已拒绝'],
            typeFilterOptions: ['全部类型'],
            currentTypeFilterIdx: 0,
            activeDropdown: 0,
            hasTimeFilter: false,
            currentMonth: '2026年2月',
            weekDays: ['日', '一', '二', '三', '四', '五', '六'],
            calendarDays: [],
            selectedDateRange: [],
            allOrderList: [],
            serviceList: [],
            searchContent: '',
            startServiceTime: '',
            endServiceTime: '',
            showPetModal: false,
            currentPetInfo: {},
            showNavModal: false,
            navTargetItem: null,
            navTargetPointType: '',
            activeCallItem: null,
            showRemarkInput: false,
            remarkText: ''
        }
    },
    created() {
        this.initCalendar();
    },
    async onLoad() {
        await this.loadServiceList()
        await this.loadOrders()
    },
    onShow() {
        this.loadOrders()
    },
    watch: {
        currentTab() {
            this.loadOrders()
        },
        currentTypeFilterIdx() {
            this.loadOrders()
        }
    },
    computed: {
        orderList() {
            return this.allOrderList;
        }
    },
    methods: {
        async loadServiceList() {
            try {
                const res = await getServiceList()
                this.serviceList = res.data || []
                this.typeFilterOptions = ['全部类型', ...this.serviceList.map(s => s.name)]
            } catch (err) {
                console.error('获取服务类型失败:', err)
            }
        },
        async loadOrders() {
            try {
                const statusMap = { 0: 2, 1: 3, 2: 5, 3: null }
                const serviceId = this.currentTypeFilterIdx > 0 ? this.serviceList[this.currentTypeFilterIdx - 1]?.id : undefined
                const params = {
                    status: statusMap[this.currentTab],
                    content: this.searchContent || undefined,
                    service: serviceId,
                    startServiceTime: this.startServiceTime || undefined,
                    endServiceTime: this.endServiceTime || undefined
                }
                console.log('订单列表请求参数:', params)
                const res = await getMyOrders(params)
                console.log('订单列表响应:', res)
                const orders = res.rows || []
                console.log('订单数量:', orders.length)
                this.allOrderList = orders.map(order => this.transformOrder(order, this.currentTab))
            } catch (err) {
                console.error('获取订单列表失败:', err)
                this.allOrderList = []
            }
        },
        transformOrder(order, tabIndex) {
            const service = this.serviceList.find(s => s.id === order.service)
            const serviceText = service?.name || '未知'
            const serviceIcon = service?.icon || '/static/icons/car.svg'
            const mode = service?.mode || 0
            const isRoundTrip = mode === 1

            // 根据 Tab 索引强制指定状态文字，忽略后端缺失的 status 字段
            let statusText = '接单'
            if (tabIndex === 0) {
                statusText = '接单' // 待接送/服务
            } else if (tabIndex === 1) {
                statusText = isRoundTrip ? '出发' : '开始' // 配送/服务中
            } else if (tabIndex === 2) {
                statusText = '已完成' // 已完成
            } else if (tabIndex === 3) {
                statusText = '已拒绝' // 已拒绝
            }
            return {
                id: order.id,
                type: isRoundTrip ? 1 : 2,
                typeText: serviceText,
                typeIcon: serviceIcon,
                statusText: statusText,
                price: (order.price / 100).toFixed(2),
                timeLabel: isRoundTrip ? '取货时间' : '服务时间',
                time: order.serviceTime || '',
                petAvatar: '/static/dog.png',
                petName: order.petName || '',
                petBreed: order.breed || '',
                startLocation: order.fromAddress || '',
                startAddress: order.fromAddress || '',
                startDistance: '0km',
                endLocation: (order.customerName || '') + ' ' + (order.customerPhone || ''),
                endAddress: order.toAddress || '',
                endDistance: '0km',
                serviceContent: order.remark || '',
                remark: order.remark || ''
            }
        },
        getDisplayStatus(item) {
            if (item.statusText === '已完成') return '已完成';
            if (item.statusText === '已拒绝') return '已拒绝';
            if (item.statusText === '接单') {
                return item.type === 1 ? '待接送' : '待服务';
            }
            return item.type === 1 ? '配送中' : '服务中';
        },
        getStatusClass(item) {
            let display = this.getDisplayStatus(item);
            if (display === '已完成') return 'finish';
            if (display === '已拒绝') return 'reject';
            if (display === '配送中' || display === '服务中') return 'processing';
            return 'highlight';
        },
        goToDetail(item) {
            uni.navigateTo({ url: `/pages/orders/detail?id=${item.id}` });
        },
        showPetProfile(item) {
            this.currentPetInfo = {
                ...item,
                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;
        },
        openNavigation(item, pointType) {
            this.navTargetItem = item;
            this.navTargetPointType = pointType;
            this.showNavModal = true;
        },
        closeNavModal() {
            this.showNavModal = false;
        },
        chooseMap(mapType) {
            let item = this.navTargetItem;
            let pointType = this.navTargetPointType;
            let name = pointType === 'start' ? item.startLocation : item.endLocation;
            let address = pointType === 'start' ? item.startAddress : item.endAddress;
            this.showNavModal = false;
            uni.openLocation({
                latitude: 30.52,
                longitude: 114.31,
                name: name || '目的地',
                address: address || '默认地址',
                success: function () {
                    console.log('打开导航成功: ' + mapType);
                }
            });
        },
        toggleCallMenu(item) {
            if (this.activeCallItem === item) {
                this.activeCallItem = null;
            } else {
                this.activeCallItem = item;
            }
        },
        closeCallMenu() {
            this.activeCallItem = null;
        },
        doCall(type) {
            let phoneNum = ''
            if (type === 'merchant') {
                phoneNum = '18900008451'
            } else if (type === 'customer') {
                phoneNum = '13800000001'
            }
            if (phoneNum) {
                uni.makePhoneCall({ phoneNumber: phoneNum })
            }
            this.activeCallItem = null;
        },
        reportAbnormal(item) {
            uni.navigateTo({ url: '/pages/orders/anomaly?orderId=' + (item.id || '') });
        },
        toggleDropdown(idx) {
            if (this.activeDropdown === idx) {
                this.activeDropdown = 0;
            } else {
                this.activeDropdown = idx;
            }
        },
        closeDropdown() {
            this.activeDropdown = 0;
        },
        selectType(index) {
            this.currentTypeFilterIdx = index;
            this.closeDropdown();
        },
        initCalendar() {
            let days = [];
            for (let i = 1; i <= 28; i++) {
                days.push(i);
            }
            this.calendarDays = days;
            this.selectedDateRange = [2, 4];
        },
        prevMonth() { uni.showToast({ title: '上个月', icon: 'none' }); },
        nextMonth() { uni.showToast({ title: '下个月', icon: 'none' }); },
        selectDateItem(day) {
            if (this.selectedDateRange.length === 2) {
                this.selectedDateRange = [day];
            } else if (this.selectedDateRange.length === 1) {
                let start = this.selectedDateRange[0];
                if (day > start) {
                    this.selectedDateRange = [start, day];
                } else if (day < start) {
                    this.selectedDateRange = [day, start];
                } else {
                    this.selectedDateRange = [];
                }
            } else {
                this.selectedDateRange = [day];
            }
        },
        getDateClass(day) {
            if (this.selectedDateRange.length === 0) return '';
            if (this.selectedDateRange.length === 1) {
                return day === this.selectedDateRange[0] ? 'is-start' : '';
            }
            let start = this.selectedDateRange[0];
            let end = this.selectedDateRange[1];
            if (day === start) return 'is-start';
            if (day === end) return 'is-end';
            if (day > start && day < end) return 'is-between';
            return '';
        },
        resetTimeFilter() {
            this.hasTimeFilter = false;
            this.selectedDateRange = [];
            uni.showToast({ title: '已重置服务时间', icon: 'none' });
            this.closeDropdown();
        },
        confirmTimeFilter() {
            if (this.selectedDateRange.length === 0) {
                uni.showToast({ title: '请先选择日期', icon: 'none' });
                return;
            }
            let text = this.selectedDateRange.length === 2 ?
                `${this.selectedDateRange[0]}日-${this.selectedDateRange[1]}日` :
                `${this.selectedDateRange[0]}日`;
            uni.showToast({ title: '已应用: ' + text, icon: 'none' });
            this.hasTimeFilter = true;
            this.closeDropdown();
        },
        getMainActionText(item) {
            return '查看详情';
        },
        mainAction(item) {
            uni.navigateTo({ url: `/pages/orders/detail?id=${item.id}` });
        },
        openRemarkInput() {
            this.remarkText = '';
            this.showRemarkInput = true;
        },
        closeRemarkInput() {
            this.showRemarkInput = false;
            this.remarkText = '';
        },
        submitRemark() {
            const text = this.remarkText.trim();
            if (!text) {
                uni.showToast({ title: '备注内容不能为空', icon: 'none' });
                return;
            }
            const now = new Date();
            const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
            if (!this.currentPetInfo.petLogs) {
                this.$set(this.currentPetInfo, 'petLogs', []);
            }
            this.currentPetInfo.petLogs.unshift({
                date: dateStr,
                content: text,
                recorder: '我'
            });
            uni.showToast({ title: '备注已添加', icon: 'success' });
            this.closeRemarkInput();
        }
    }
}
