import { getMyProfile, getPendingOrders, acceptOrder, getOrderCount } from '@/api/fulfiller'
import { getServiceList } from '@/api/service'
import { isLoggedIn } from '@/utils/auth'

export default {
    data() {
        return {
            taskList: [],
            currentFilter: 'default', // default, distance, time
            filterCondition: '筛选条件',
            sortDistance: 'asc', // asc, desc
            sortTime: 'asc',
            scrollTop: 0, // Track scroll position
            isFilterShow: false,
            tempFilter: {
                service: null,
                distance: '全部',
                amount: '全部'
            },
            activeFilter: {
                service: null,
                distance: '全部',
                amount: '全部'
            },
            workStatus: 'working', // working | resting
            showConfirmModal: false,
            showPetModal: false,
            currentPetInfo: {},
            showRejectModal: false,
            rejectReason: '',
            currentOrder: null,
            showAcceptConfirmModal: false,
            showNavModal: false,
            navTargetItem: null,
            navTargetPointType: '',
            profile: null,
            profileLoading: false,
            serviceList: [],
            orderStats: {
                total: 0,
                reject: 0,
                award: 0,
                punishment: 0
            }
        }
    },
    onPageScroll(e) {
        this.scrollTop = e.scrollTop;
    },
    onLoad() {
        // Initial load
        this.checkWorkStatus();
        this.loadServiceList();
        this.loadTaskList();
    },
    onShow() {
        this.checkWorkStatus();
        if (isLoggedIn()) {
            this.loadProfile()
            this.loadOrderStats()
        }
    },
    methods: {
        async loadProfile() {
            if (this.profileLoading) return
            this.profileLoading = true
            try {
                const res = await getMyProfile()
                this.profile = res.data || null
            } catch (err) {
                console.error('获取个人信息失败:', err)
            } finally {
                this.profileLoading = false
            }
        },
        async loadServiceList() {
            try {
                const res = await getServiceList()
                this.serviceList = res.data || []
            } catch (err) {
                console.error('获取服务类型失败:', err)
            }
        },
        async loadOrderStats() {
            try {
                const res = await getOrderCount()
                this.orderStats = res.data || { total: 0, reject: 0, award: 0, punishment: 0 }
            } catch (err) {
                console.error('获取订单统计失败:', err)
            }
        },
        checkWorkStatus() {
            const status = uni.getStorageSync('workStatus');
            if (status) {
                this.workStatus = status;
            } else {
                // Default to working if not set
                this.workStatus = 'working';
                uni.setStorageSync('workStatus', 'working');
            }
        },
        toggleFilter() {
            if (this.workStatus === 'resting') return; // Disable filter when resting? Or keep it? User didn't specify, but usually disabled. Let's keep it enabled for now as they might look at filters before working.
            this.isFilterShow = !this.isFilterShow;
        },
        goToWorkStatus() {
            uni.navigateTo({
                url: '/pages/home/work-status'
            });
        },
        startWork() {
            this.showConfirmModal = true;
        },
        confirmStartWork() {
            this.workStatus = 'working';
            uni.setStorageSync('workStatus', 'working');
            this.loadTaskList();
            this.showConfirmModal = false;
            uni.showToast({ title: '已开始接单', icon: 'success' });
        },
        closeConfirmModal() {
            this.showConfirmModal = false;
        },
        showPetProfile(item) {
            this.currentPetInfo = item;
            this.showPetModal = true;
        },
        closePetProfile() {
            this.showPetModal = false;
        },
        openRejectModal(item) {
            this.currentOrder = item;
            this.rejectReason = '';
            this.showRejectModal = true;
        },
        closeRejectModal() {
            this.showRejectModal = false;
            this.currentOrder = null;
        },
        confirmReject() {
            if (!this.rejectReason.trim()) {
                uni.showToast({ title: '请输入拒绝理由', icon: 'none' });
                return;
            }
            // Add actual API call here
            uni.showToast({ title: '已拒绝接单', icon: 'success' });
            this.showRejectModal = false;
        },
        openAcceptModal(item) {
            this.currentOrder = item;
            this.showAcceptConfirmModal = true;
        },
        closeAcceptModal() {
            this.showAcceptConfirmModal = false;
            this.currentOrder = null;
        },
        async confirmAccept() {
            if (!this.currentOrder?.id) return
            try {
                await acceptOrder(this.currentOrder.id)
                uni.showToast({ title: '接单成功', icon: 'success' })
                this.showAcceptConfirmModal = false
                this.currentOrder = null
                this.loadTaskList()
                this.loadProfile()
            } catch (err) {
                console.error('接单失败:', err)
                uni.showToast({ title: '接单失败', icon: 'none' })
            }
        },
        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, // Mock lat
                longitude: 114.31, // Mock lng
                name: name || '目的地',
                address: address || '默认地址',
                success: function () {
                    console.log('打开导航成功: ' + mapType);
                }
            });
        },
        selectService(type) {
            this.tempFilter.service = type;
        },
        selectDistance(type) {
            this.tempFilter.distance = type;
        },
        selectAmount(type) {
            this.tempFilter.amount = type;
        },
        resetFilter() {
            this.tempFilter = {
                service: null,
                distance: '全部',
                amount: '全部'
            };
        },
        confirmFilter() {
            this.activeFilter = { ...this.tempFilter };
            this.isFilterShow = false;
            uni.showToast({ title: '筛选已生效', icon: 'none' });
            // Add filtering logic here if needed
        },
        closeFilter() {
            this.isFilterShow = false;
        },
        goToDetail(item) {
            console.log('Go to detail', item);
        },
        async loadTaskList() {
            try {
                const params = {
                    service: this.activeFilter.service,
                    minPrice: this.getMinPrice(),
                    maxPrice: this.getMaxPrice(),
                    pageNum: 1,
                    pageSize: 20
                }
                const res = await getPendingOrders(params)
                this.taskList = (res.rows || []).map(item => this.transformOrder(item))
            } catch (err) {
                console.error('获取订单列表失败:', err)
                uni.showToast({ title: '加载失败', icon: 'none' })
                this.taskList = []
            }
        },
        getMinPrice() {
            const amount = this.activeFilter.amount
            if (amount === '100以下') return 0
            if (amount === '100-200') return 10000
            if (amount === '200-500') return 20000
            if (amount === '500以上') return 50000
            return undefined
        },
        getMaxPrice() {
            const amount = this.activeFilter.amount
            if (amount === '100以下') return 10000
            if (amount === '100-200') return 20000
            if (amount === '200-500') return 50000
            return undefined
        },
        transformOrder(item) {
            const service = this.serviceList.find(s => s.id === item.service)
            const serviceText = service?.name || '未知'
            const serviceIcon = service?.icon || ''
            const mode = service?.mode || 0
            const isRoundTrip = mode === 1
            return {
                id: item.id,
                type: isRoundTrip ? 1 : item.service,
                typeText: serviceText,
                typeIcon: serviceIcon,
                price: (item.price / 100).toFixed(2),
                timeLabel: isRoundTrip ? '取货时间' : '服务时间',
                time: item.serviceTime,
                petAvatar: '/static/dog.png',
                petName: item.petName,
                petBreed: item.breed,
                petGender: 'M',
                petAge: '',
                petWeight: '',
                petPersonality: '',
                petHobby: '',
                petRemark: '',
                petTags: [],
                petLogs: [],
                startLocation: isRoundTrip ? item.fromAddress : '',
                startAddress: isRoundTrip ? item.fromAddress : '',
                startDistance: '0km',
                endLocation: item.customerName + ' ' + item.customerPhone,
                endAddress: item.toAddress,
                endDistance: '0km',
                serviceContent: '',
                remark: item.remark || ''
            }
        },
        setFilter(type) {
            this.currentFilter = type;
            if (type === 'distance') {
                this.sortDistance = this.sortDistance === 'asc' ? 'desc' : 'asc';
                uni.showToast({ title: `按距离${this.sortDistance === 'asc' ? '升序' : '降序'}`, icon: 'none' });
            } else if (type === 'time') {
                this.sortTime = this.sortTime === 'asc' ? 'desc' : 'asc';
                uni.showToast({ title: `按时间${this.sortTime === 'asc' ? '升序' : '降序'}`, icon: 'none' });
            }
        },
        showFilterDropdown() {
            this.toggleFilter();
        }
    }
}
