<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" @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 no-border" @click="showCityPicker">
                <text class="item-title">所属站点</text>
                <view class="item-right">
                    <text class="item-value">{{ userInfo.stationFullName || '未分配站点' }}</text>
                    <image class="arrow-icon" src="/static/icons/chevron_right.svg"></image>
                </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
import { getMyProfile, updateAvatar, updateStatus, updateCity } from '@/api/fulfiller/fulfiller'
import { uploadFile } from '@/api/fulfiller/app'
import { getAreaStationList } from '@/api/system/areaStation'

export default {
    data() {
        return {
            userInfo: {
                name: '',
                workType: '',
                workStatus: '',
                city: '',
                avatar: '/static/touxiang.png',
                stationName: '',
                stationFullName: ''
            },
            isStatusPickerShow: false,
            isCityPickerShow: false,

            // 城市站点级联选择器
            selectStep: 0,
            selectedPathway: [],
            currentCityList: [],
            selectedCityId: null,
            fullTree: [] // 树形结构数据
        }
    },
    onLoad() {
        this.loadUserInfo();
        uni.$on('updateName', (newName) => {
            this.userInfo.name = newName;
        });
    },
    onUnload() {
        uni.$off('updateName');
    },
    methods: {
        // 加载用户信息
        async loadUserInfo() {
            uni.showLoading({ title: '加载中...' });
            try {
                const res = await getMyProfile();
                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 || '',
                    stationFullName: '加载中...'
                };

                // 异步查找完整路径
                if (data.stationId) {
                    if (this.fullTree.length === 0) {
                        await this.loadAreaStationTree();
                    }
                    this.userInfo.stationFullName = this.findStationFullName(data.stationId, this.fullTree) || data.stationName || '未分配站点';
                } else {
                    this.userInfo.stationFullName = '未分配站点';
                }
            } catch (error) {
                console.error('加载用户信息失败:', error);
                uni.showToast({ title: error.message || error.msg || '加载信息失败', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },

        // 格式化状态
        formatStatus(status) {
            const statusMap = {
                'busy': '接单中',
                'resting': '休息中',
                'disabled': '已禁用'
            };
            return statusMap[status] || status;
        },

        // 查找站点完整路径 (城市/区域/站点)
        findStationFullName(stationId, tree) {
            if (!stationId || !tree || tree.length === 0) return '';

            let path = [];
            const dfs = (nodes, targetId, currentPath) => {
                for (let node of nodes) {
                    if (node.id === targetId) {
                        path = [...currentPath, node.name];
                        return true;
                    }
                    if (node.children && node.children.length > 0) {
                        if (dfs(node.children, targetId, [...currentPath, node.name])) {
                            return true;
                        }
                    }
                }
                return false;
            };

            dfs(tree, stationId, []);
            return path.join('/');
        },

        navBack() {
            uni.navigateBack({ delta: 1 });
        },

        // 修改头像
        changeAvatar() {
            uni.chooseImage({
                count: 1,
                success: async (res) => {
                    const tempFilePath = res.tempFilePaths[0];

                    // 上传图片到服务器
                    uni.showLoading({ title: '上传中...' });
                    try {
                        const uploadRes = await uploadFile(tempFilePath);
                        const { url, ossId } = uploadRes.data;

                        // 调用接口更新头像
                        await updateAvatar(ossId);
                        this.userInfo.avatar = url;
                        uni.showToast({ title: '修改成功', icon: 'success' });
                    } catch (error) {
                        console.error('修改头像失败:', error);
                        uni.showToast({ title: error.message || error.msg || '上传失败', icon: 'none' });
                    } finally {
                        uni.hideLoading();
                    }
                }
            });
        },

        editName() {
            uni.navigateTo({
                url: `/pages/mine/settings/profile/edit-name/index?name=${this.userInfo.name}`
            });
        },

        showStatusPicker() {
            this.isStatusPickerShow = true;
        },

        closeStatusPicker() {
            this.isStatusPickerShow = false;
        },

        // 选择状态
        async selectStatus(statusText) {
            const statusMap = {
                '接单中': 'busy',
                '休息中': 'resting'
            };
            const status = statusMap[statusText];

            try {
                await updateStatus(status);
                this.userInfo.workStatus = statusText;
                uni.showToast({ title: '状态已更新', icon: 'success' });
            } catch (error) {
                console.error('修改状态失败:', error);
                uni.showToast({ title: error.message || error.msg || '状态更新失败', icon: 'none' });
            } finally {
                this.closeStatusPicker();
            }
        },

        // 城市和站点级联选择器
        async showCityPicker() {
            this.isCityPickerShow = true;
            if (this.fullTree.length === 0) {
                await this.loadAreaStationTree();
            }
            if (this.selectedPathway.length === 0) {
                this.resetCityPicker();
            }
        },
        async loadAreaStationTree() {
            try {
                uni.showLoading({ title: '加载中...' });
                const res = await getAreaStationList();
                const list = res.data || [];
                // 列表转树形结构
                let map = {};
                let roots = [];
                list.forEach(node => {
                    map[node.id] = { ...node, children: [] };
                });
                list.forEach(node => {
                    if (node.parentId === 0 || !map[node.parentId]) {
                        roots.push(map[node.id]);
                    } else {
                        map[node.parentId].children.push(map[node.id]);
                    }
                });
                this.fullTree = roots;
            } catch (err) {
                console.error('加载站点数据失败:', err);
                this.fullTree = [];
                uni.showToast({ title: err.message || err.msg || '获取站点失败', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },
        resetCityPicker() {
            this.selectStep = 0;
            this.selectedPathway = [];
            this.currentCityList = this.fullTree;
        },
        closeCityPicker() {
            this.isCityPickerShow = false;
        },
        selectCityItem(item) {
            this.selectedPathway[this.selectStep] = item;

            // 如果有下级（如城市下的区域，区域下的站点）则继续选
            if (item.children && item.children.length > 0) {
                this.selectStep++;
                this.selectedPathway = this.selectedPathway.slice(0, this.selectStep);
                this.currentCityList = item.children;
            } else {
                // 没有下级，直接确认
                this.selectedCityId = item.id;
                this.confirmCity();
            }
        },
        jumpToStep(step) {
            this.selectStep = step;
            if (step === 0) {
                this.currentCityList = this.fullTree;
            } else {
                const parent = this.selectedPathway[step - 1];
                this.currentCityList = parent ? parent.children : [];
            }
        },
        // 确认城市与站点选择
        async confirmCity() {
            if (this.selectedPathway.length === 0) {
                uni.showToast({ title: '请选择站点', icon: 'none' });
                return;
            }

            // 找出最后选中的节点 (站点)
            let stationNode = this.selectedPathway[this.selectedPathway.length - 1];
            // 将路径名称用 / 加起来
            const fullName = this.selectedPathway.map(i => i.name).join('/');

            const reqData = {
                stationId: stationNode.id
            };

            try {
                await updateCity(reqData);
                this.userInfo.stationFullName = fullName;
                uni.showToast({ title: '修改成功', icon: 'success' });
                this.closeCityPicker();
                // 重置以便下一次打开
                this.selectedPathway = [];
            } catch (error) {
                console.error('修改失败:', error);
                uni.showToast({ title: error.message || error.msg || '站点更新失败', 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;
    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;
    height: 64rpx;
    border-radius: 50%;
}

.item-value {
    font-size: 28rpx;
    color: #999;
}

.item-value-black {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

/* 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;
}

.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>
