<template>
    <view class="container">
        <!-- 自定义头部 -->
        <view class="custom-header">
            <view class="header-left" @click="navBack">
                <image class="back-icon" src="/static/icons/chevron_right_dark.svg" style="transform: rotate(180deg);"></image>
            </view>
            <text class="header-title">个人资料</text>
            <view class="header-right"></view>
        </view>
        <view class="header-placeholder"></view>

        <view class="group-card">
            <view class="list-item" @click="changeAvatar">
                <text class="item-title">头像</text>
                <view class="item-right">
                    <image class="user-avatar" :src="userInfo.avatar" mode="aspectFill"></image>
                    <image class="arrow-icon" src="/static/icons/chevron_right.svg"></image>
                </view>
            </view>
            <view class="list-item" @click="editName">
                <text class="item-title">真实姓名</text>
                <view class="item-right">
                    <text class="item-value">{{ userInfo.name }}</text>
                    <image class="arrow-icon" src="/static/icons/chevron_right.svg"></image>
                </view>
            </view>
        </view>

        <view class="group-card">
           <!-- <view class="list-item">
                <text class="item-title">工作类型</text>
                <view class="tag-blue-outline">{{ userInfo.workType }}</view>
            </view> -->
            <view class="list-item" @click="showStatusPicker">
                <text class="item-title">工作状态</text>
                <view class="item-right">
                    <text class="item-value-black">{{ userInfo.workStatus }}</text>
                    <image class="arrow-icon" src="/static/icons/chevron_right.svg"></image>
                </view>
            </view>
        </view>

        <view class="group-card">
            <view class="list-item" @click="showCityPicker">
                <text class="item-title">工作城市</text>
                <view class="item-right">
                    <text class="item-value">{{ userInfo.city }}</text>
                    <image class="arrow-icon" src="/static/icons/chevron_right.svg"></image>
                </view>
            </view>
            <view class="list-item no-border">
                <text class="item-title">所属站点</text>
                <view class="item-right">
                    <text class="item-value">{{ userInfo.stationName || '未分配站点' }}</text>
                </view>
            </view>
        </view>

        <!-- 工作状态选择弹窗 -->
        <view class="popup-mask" v-if="isStatusPickerShow" @click="closeStatusPicker">
            <view class="popup-content" @click.stop>
                <view class="popup-title">选择工作状态</view>
                <view class="popup-item" @click="selectStatus('接单中')">接单中</view>
                <view class="popup-item" @click="selectStatus('休息中')">休息中</view>
                <view class="popup-cancel" @click="closeStatusPicker">取消</view>
            </view>
        </view>

        <!-- 城市选择弹窗 (级联版，与我要加入页面一致) -->
        <view class="popup-mask" v-if="isCityPickerShow" @click="closeCityPicker">
            <view class="popup-content" @click.stop>
                <view class="popup-header-row">
                    <text class="popup-btn-cancel" @click="closeCityPicker">取消</text>
                    <text class="popup-title-text">请选择工作城市</text>
                    <text class="popup-btn-confirm" @click="confirmCity">确定</text>
                </view>
                <view class="picker-body">
                    <!-- 左侧：垂直路径 -->
                    <view class="timeline-area">
                        <view 
                            class="timeline-item" 
                            v-for="(item, index) in selectedPathway" 
                            :key="index"
                            @click="jumpToStep(index)"
                        >
                            <view class="timeline-dot"></view>
                            <text>{{ item.name }}</text>
                        </view>
                        <view 
                            class="timeline-item active" 
                            v-if="selectStep === selectedPathway.length"
                        >
                            <view class="timeline-dot"></view>
                            <text>请选择</text>
                        </view>
                    </view>
                    <!-- 右侧：待选项列表 -->
                    <scroll-view scroll-y class="list-area">
                        <view 
                            class="list-item" 
                            v-for="item in currentCityList" 
                            :key="item.id"
                            @click="selectCityItem(item)"
                        >
                            {{ item.name }}
                        </view>
                        <view v-if="currentCityList.length === 0" style="padding:20rpx;color:#999">
                            无数据
                        </view>
                    </scroll-view>
                </view>
            </view>
        </view>

    </view>
</template>

<script>
// 引入 API @author steelwei
import { getMyProfile, updateAvatar, updateName, updateStatus, updateCity, uploadFile, getAreaChildren } from '@/api/fulfiller'

export default {
    data() {
        return {
            userInfo: {
                name: '',
                workType: '',
                workStatus: '',
                city: '',
                avatar: '/static/touxiang.png',
                stationName: ''
            },
            isStatusPickerShow: false,
            isCityPickerShow: false,
            
            // 城市级联选择器（与我要加入页面一致）
            selectStep: 0,
            selectedPathway: [],
            currentCityList: [],
            selectedCityId: null
        }
    },
    onLoad() {
        this.loadUserInfo();
        uni.$on('updateName', (newName) => {
            this.userInfo.name = newName;
        });
    },
    onUnload() {
        uni.$off('updateName');
    },
    methods: {
        // 加载用户信息 @author steelwei
        async loadUserInfo() {
            uni.showLoading({ title: '加载中...' });
            try {
                const res = await getMyProfile();
                if (res.code === 200) {
                    const data = res.data;
                    this.userInfo = {
                        name: data.realName || data.name,
                        workType: data.workType === 'full_time' ? '全职' : '兼职',
                        workStatus: this.formatStatus(data.status),
                        city: data.cityName || '',
                        avatar: data.avatarUrl || '/static/touxiang.png',
                        stationName: data.stationName || '未分配站点'
                    };
                } else {
                    uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
                }
            } catch (error) {
                console.error('加载用户信息失败:', error);
                uni.showToast({ title: '网络错误', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },
        
        // 格式化状态 @author steelwei
        formatStatus(status) {
            const statusMap = {
                'busy': '接单中',
                'resting': '休息中',
                'disabled': '已禁用'
            };
            return statusMap[status] || status;
        },
        
        navBack() {
            uni.navigateBack({ delta: 1 });
        },
        
        // 修改头像 @author steelwei
        changeAvatar() {
            uni.chooseImage({
                count: 1,
                success: async (res) => {
                    const tempFilePath = res.tempFilePaths[0];
                    
                    // 上传图片到服务器
                    uni.showLoading({ title: '上传中...' });
                    try {
                        const uploadRes = await uploadFile(tempFilePath);
                        if (uploadRes.code === 200) {
                            const { url, ossId } = uploadRes.data;
                            
                            // 调用接口更新头像 @author steelwei
                            const result = await updateAvatar(ossId);
                            if (result.code === 200) {
                                this.userInfo.avatar = url;
                                uni.showToast({ title: '修改成功', icon: 'success' });
                            } else {
                                uni.showToast({ title: result.msg || '修改失败', icon: 'none' });
                            }
                        }
                    } catch (error) {
                        console.error('修改头像失败:', error);
                        uni.showToast({ title: '上传失败', icon: 'none' });
                    } finally {
                        uni.hideLoading();
                    }
                }
            });
        },
        
        editName() {
            uni.navigateTo({
                url: `/pages/mine/settings/profile/edit-name?name=${this.userInfo.name}`
            });
        },
        
        showStatusPicker() {
            this.isStatusPickerShow = true;
        },
        
        closeStatusPicker() {
            this.isStatusPickerShow = false;
        },
        
        // 选择状态 @author steelwei
        async selectStatus(statusText) {
            const statusMap = {
                '接单中': 'busy',
                '休息中': 'resting'
            };
            const status = statusMap[statusText];
            
            try {
                const res = await updateStatus(status);
                if (res.code === 200) {
                    this.userInfo.workStatus = statusText;
                    uni.showToast({ title: '状态已更新', icon: 'success' });
                } else {
                    uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
                }
            } catch (error) {
                console.error('修改状态失败:', error);
                uni.showToast({ title: '网络错误', icon: 'none' });
            } finally {
                this.closeStatusPicker();
            }
        },
        
        // 城市级联选择器（与我要加入页面一致） @author steelwei
        async showCityPicker() {
            this.isCityPickerShow = true;
            if (this.selectedPathway.length === 0) {
                await this.resetCityPicker();
            }
        },
        async resetCityPicker() {
            this.selectStep = 0;
            this.selectedPathway = [];
            await this.loadAreaChildren(0);
        },
        closeCityPicker() {
            this.isCityPickerShow = false;
        },
        async loadAreaChildren(parentId) {
            try {
                const res = await getAreaChildren(parentId);
                // 城市选择器只显示 城市(0) 和 区域(1)，不显示站点(2)
                this.currentCityList = (res.data || [])
                    .filter(item => item.type !== 2)
                    .map(item => ({
                        id: item.id,
                        name: item.name,
                        type: item.type,
                        parentId: item.parentId
                    }));
            } catch (err) {
                console.error('加载区域数据失败:', err);
                this.currentCityList = [];
            }
        },
        async selectCityItem(item) {
            this.selectedPathway[this.selectStep] = item;
            // type: 0=城市, 1=区域
            if (item.type === 0) {
                this.selectStep++;
                this.selectedPathway = this.selectedPathway.slice(0, this.selectStep);
                await this.loadAreaChildren(item.id);
                if (this.currentCityList.length === 0) {
                    this.selectedCityId = item.id;
                    this.confirmCity();
                }
            } else {
                // 区域级(1)选完即确认
                this.selectedCityId = item.id;
                this.confirmCity();
            }
        },
        async jumpToStep(step) {
            this.selectStep = step;
            if (step === 0) {
                await this.loadAreaChildren(0);
            } else {
                const parent = this.selectedPathway[step - 1];
                if (parent) {
                    await this.loadAreaChildren(parent.id);
                }
            }
        },
        // 确认城市选择 @author steelwei
        async confirmCity() {
            if (this.selectedPathway.length === 0) {
                uni.showToast({ title: '请选择城市', icon: 'none' });
                return;
            }
            const cityName = this.selectedPathway.map(i => i.name).join(' ');
            const cityCode = String(this.selectedCityId);
            
            try {
                const res = await updateCity(cityCode, cityName);
                if (res.code === 200) {
                    this.userInfo.city = cityName;
                    uni.showToast({ title: '修改成功', icon: 'success' });
                    this.closeCityPicker();
                    // 重置选择器，下次打开重新加载
                    this.selectedPathway = [];
                } else {
                    uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
                }
            } catch (error) {
                console.error('修改城市失败:', error);
                uni.showToast({ title: '网络错误', icon: 'none' });
            }
        }
    }
}
</script>

<style>
page {
    background-color: #F8F8F8;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
.custom-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88rpx;
    padding-top: var(--status-bar-height);
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 30rpx;
    padding-right: 30rpx;
    box-sizing: content-box;
    z-index: 100;
}
.header-placeholder {
    height: calc(88rpx + var(--status-bar-height));
}
.back-icon {
    width: 40rpx;
    height: 40rpx;
}
.header-title {
    font-size: 28rpx; /* 14pt */
    font-weight: bold;
    color: #333;
}
.header-right {
    width: 40rpx;
}

.container {
    padding: 20rpx 30rpx;
}
.group-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 0 30rpx;
    margin-bottom: 30rpx;
}
.list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    border-bottom: 1px solid #F5F5F5;
}
.list-item.no-border {
    border-bottom: none;
}
.item-title {
    font-size: 28rpx;
    color: #333;
}
.item-right {
    display: flex;
    align-items: center;
}
.arrow-icon {
    width: 28rpx;
    height: 28rpx;
    opacity: 0.5;
    margin-left: 10rpx;
}
.user-avatar {
    width: 64rpx; /* Smaller avatar */
    height: 64rpx;
    border-radius: 50%;
}
.item-value {
    font-size: 28rpx;
    color: #999;
}
.item-value-black {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}
.tag-blue-outline {
    font-size: 24rpx;
    color: #2979FF;
    border: 1px solid #2979FF;
    padding: 4rpx 20rpx;
    border-radius: 30rpx;
    background-color: #fff;
}

/* Popup Styles */
.popup-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    z-index: 999;
    display: flex;
    align-items: flex-end;
}
.popup-content {
    width: 100%;
    background-color: #fff;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    padding-bottom: 30rpx; /* Safe area */
}
.popup-title {
    text-align: center;
    font-size: 28rpx;
    color: #999;
    padding: 30rpx 0;
    border-bottom: 1px solid #eee;
}
.popup-item {
    text-align: center;
    font-size: 32rpx;
    color: #333;
    padding: 30rpx 0;
    border-bottom: 1px solid #eee;
}
.popup-cancel {
    text-align: center;
    font-size: 32rpx;
    color: #333;
    padding: 30rpx 0;
    margin-top: 20rpx;
    border-top: 10rpx solid #f5f5f5;
}

.popup-header-row {
    display: flex;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1px solid #eee;
}
.popup-btn-cancel { font-size: 28rpx; color: #666; }
.popup-title-text { font-size: 32rpx; font-weight: bold; color: #333; }
.popup-btn-confirm { font-size: 28rpx; color: #FF5722; font-weight: bold; }

/* 级联城市选择器（与我要加入页面一致） */
.picker-body {
    display: flex;
    height: 500rpx;
}
.timeline-area {
    width: 240rpx;
    padding: 20rpx;
    background: #f8f8f8;
    border-right: 1px solid #eee;
    overflow-y: auto;
}
.timeline-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    font-size: 26rpx;
    color: #666;
}
.timeline-item.active {
    color: #FF5722;
    font-weight: bold;
}
.timeline-dot {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background: #ccc;
    margin-right: 12rpx;
    flex-shrink: 0;
}
.timeline-item.active .timeline-dot {
    background: #FF5722;
}
.list-area {
    flex: 1;
    height: 100%;
}
.list-area .list-item {
    padding: 24rpx 30rpx;
    font-size: 28rpx;
    color: #333;
    border-bottom: 1px solid #f5f5f5;
}
</style>
