<template>
	<view class="user-edit-page">
		<nav-bar title="编辑用户" bgColor="#fff" color="#000"></nav-bar>

		<view v-if="loading" class="loading-state">
			<view class="spinner"></view>
			<text class="loading-txt">同步资料中...</text>
		</view>

		<block v-else>
			<!-- 头像上传 -->
			<view class="avatar-section">
				<view class="avatar-wrap" @click="chooseAvatar">
					<image v-if="avatarDisplayUrl" :src="avatarDisplayUrl" class="avatar-img" mode="aspectFill"></image>
					<view v-else class="avatar-placeholder">
						<view class="avatar-icon">
							<view class="head"></view>
							<view class="body"></view>
						</view>
					</view>
					<text class="avatar-tip">点击修改头像</text>
				</view>
			</view>

			<!-- 基本资料 -->
			<view class="section-title">基本资料</view>
			<view class="form-card">
				<view class="form-item">
					<text class="form-label require">姓名</text>
					<input class="form-input" v-model="form.name" placeholder="请输入姓名" />
				</view>
				<view class="form-item">
					<text class="form-label require">手机号</text>
					<input class="form-input" v-model="form.phone" type="number" placeholder="请输入手机号" />
				</view>
				<view class="form-item" @click="showGenderSelect = true">
					<text class="form-label">性别</text>
					<view class="picker-value" :class="{'placeholder': form.gender === undefined}">
						{{ getGenderLabel }}
					</view>
					<view class="right-arrow"></view>
				</view>
			</view>

			<!-- 居住信息 -->
			<view class="section-title">居住信息</view>
			<view class="form-card">
				<view class="form-item" @click="openStationModal">
					<text class="form-label require">所属站点</text>
					<view class="picker-value" :class="{'placeholder': form.stationId === undefined}">
						{{ getStationLabel }}
					</view>
					<view class="right-arrow"></view>
				</view>
				<view class="form-item">
					<text class="form-label require">详细住址</text>
					<input class="form-input" v-model="form.address" placeholder="请输入街道/门牌号" />
				</view>
				<view class="form-item" @click="showHouseTypeSelect = true">
					<text class="form-label">房屋类型</text>
					<view class="picker-value" :class="{'placeholder': !form.houseType}">
						{{ getHouseTypeLabel }}
					</view>
					<view class="right-arrow"></view>
				</view>
				<view class="form-item" @click="showEntryMethodSelect = true">
					<text class="form-label require">入门方式</text>
					<view class="picker-value" :class="{'placeholder': !form.entryMethod}">
						{{ getEntryMethodLabel }}
					</view>
					<view class="right-arrow"></view>
				</view>
				<view class="form-item" v-if="form.entryMethod === 'password'">
					<text class="form-label require">开门密码</text>
					<input class="form-input" v-model="form.entryPassword" placeholder="请输入密码" />
				</view>
				<view class="form-item" v-if="form.entryMethod === 'key'">
					<text class="form-label require">钥匙位置</text>
					<input class="form-input" v-model="form.keyLocation" placeholder="如：地毯下" />
				</view>
			</view>

			<!-- 其他 -->
			<view class="section-title">其他</view>
			<view class="form-card">
				<view class="form-item vertical">
					<text class="form-label">备注说明</text>
					<textarea class="form-textarea" v-model="form.remark" placeholder="请输入备注" />
				</view>
			</view>

			<!-- 底部固定操作栏 -->
			<view class="footer-bar">
				<button class="save-btn" :loading="saving" @click="onSave">保存修改</button>
			</view>
		</block>

		<!-- 站点选择弹窗 @Author: Antigravity -->
		<view class="center-modal-mask" v-if="showStationModal" @click="showStationModal = false" @touchmove.stop.prevent>
			<view class="center-modal-content station-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">所属站点修改</text>
					<view class="close-btn" @click="showStationModal = false"></view>
				</view>
				<view class="step-indicator">
					<view class="step-item" :class="{ 'active': currentStep === 0 }" @click="currentStep = 0">{{ selectedCityName || '城市' }}</view>
					<view class="step-divider">/</view>
					<view class="step-item" :class="{ 'active': currentStep === 1 }" @click="selectedCityId ? currentStep = 1 : null">{{ selectedAreaName || '区域' }}</view>
					<view class="step-divider">/</view>
					<view class="step-item" :class="{ 'active': currentStep === 2 }" @click="selectedAreaId ? currentStep = 2 : null">{{ selectedStationName || '站点' }}</view>
				</view>
				<scroll-view scroll-y class="modal-list-scroll">
					<view class="list-item" v-for="item in currentList" :key="item.id" @click="onStepSelect(item)">
						<text class="item-text">{{ item.name }}</text>
						<view class="checkmark" v-if="isStepChecked(item)"></view>
					</view>
					<view class="empty-tip" v-if="currentList.length === 0">暂无数据</view>
				</scroll-view>
			</view>
		</view>

		<center-select v-model="showGenderSelect" title="性别修改" :options="genderOptions" :value="form.gender" @select="(item) => form.gender = item.value" />
		<center-select v-model="showHouseTypeSelect" title="房屋类型" :options="houseTypeOptions" :value="form.houseType" @select="(item) => form.houseType = item.value" />
		<center-select v-model="showEntryMethodSelect" title="入门方式" :options="entryMethodOptions" :value="form.entryMethod" @select="onEntryMethodChangeDetail" />
	</view>
</template>

<script setup>
/**
 * @Author: Antigravity
 */
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import navBar from '@/components/nav-bar/index.vue'
import centerSelect from '@/components/center-select/index.vue'
import { getCustomer, updateCustomer } from '@/api/archieves/customer'
import { listAreaStation } from '@/api/system/areaStation'
import { uploadFile } from '@/api/system/oss'
import customerEnums from '@/json/customer.json'

const { houseTypeOptions, entryMethodOptions } = customerEnums
const genderOptions = [{ label: '男', value: 0 }, { label: '女', value: 1 }]

const loading = ref(true)
const saving = ref(false)
const allStationNodes = ref([])
const avatarDisplayUrl = ref('')

const showGenderSelect = ref(false)
const showHouseTypeSelect = ref(false)
const showEntryMethodSelect = ref(false)
const showStationModal = ref(false)

const currentStep = ref(0)
const selectedCityId = ref(null)
const selectedCityName = ref('')
const selectedAreaId = ref(null)
const selectedAreaName = ref('')
const selectedStationId = ref(null)
const selectedStationName = ref('')

const form = reactive({
    id: undefined, name: '', phone: '', gender: undefined, areaId: undefined, stationId: undefined,
    address: '', houseType: '', entryMethod: '', entryPassword: '', keyLocation: '', remark: '', avatar: undefined
})

onLoad(async (options) => {
    try {
        loading.value = true
        const stationRes = await listAreaStation()
        allStationNodes.value = Array.isArray(stationRes) ? stationRes : (stationRes?.data || [])
        
        if (options.id) {
            const res = await getCustomer(options.id)
            if (res) {
                const data = res.data || res
                Object.assign(form, data)
                avatarDisplayUrl.value = data.avatarUrl || ''
                resolveStationNames()
            }
        }
    } catch(err) { console.error(err) } finally { loading.value = false }
})

// 根据 ID 反查名称
const resolveStationNames = () => {
	if (!form.stationId) return
	const nodes = allStationNodes.value
	const station = nodes.find(n => String(n.id) === String(form.stationId))
	if (station) {
		selectedStationId.value = station.id
		selectedStationName.value = station.name
		const area = nodes.find(n => String(n.id) === String(station.parentId))
		if (area) {
			selectedAreaId.value = area.id
			selectedAreaName.value = area.name
			const city = nodes.find(n => String(n.id) === String(area.parentId))
			if (city) {
				selectedCityId.value = city.id
				selectedCityName.value = city.name
			}
		}
	}
}

const openStationModal = () => {
	currentStep.value = 0
	showStationModal.value = true
}

const currentList = computed(() => {
	if (currentStep.value === 0) return allStationNodes.value.filter(n => String(n.parentId) === '0' || !n.parentId)
	if (currentStep.value === 1) return allStationNodes.value.filter(n => String(n.parentId) === String(selectedCityId.value))
	return allStationNodes.value.filter(n => String(n.parentId) === String(selectedAreaId.value))
})

const onStepSelect = (item) => {
	if (currentStep.value === 0) {
		selectedCityId.value = item.id; selectedCityName.value = item.name
		selectedAreaId.value = null; selectedAreaName.value = ''
		selectedStationId.value = null; selectedStationName.value = ''
		currentStep.value = 1
	} else if (currentStep.value === 1) {
		selectedAreaId.value = item.id; selectedAreaName.value = item.name
		selectedStationId.value = null; selectedStationName.value = ''
		currentStep.value = 2
	} else {
		selectedStationId.value = item.id; selectedStationName.value = item.name
		form.stationId = item.id; form.areaId = selectedAreaId.value
		showStationModal.value = false
	}
}

const isStepChecked = (item) => {
	if (currentStep.value === 0) return selectedCityId.value === item.id
	if (currentStep.value === 1) return selectedAreaId.value === item.id
	return selectedStationId.value === item.id
}

const getStationLabel = computed(() => form.stationId ? `${selectedCityName.value} - ${selectedAreaName.value} - ${selectedStationName.value}` : '请选择')
const getGenderLabel = computed(() => genderOptions.find(o => o.value === form.gender)?.label || '请选择')
const getHouseTypeLabel = computed(() => houseTypeOptions.find(o => o.value === form.houseType)?.label || '请选择')
const getEntryMethodLabel = computed(() => entryMethodOptions.find(o => o.value === form.entryMethod)?.label || '请选择')

const onEntryMethodChangeDetail = (item) => {
	form.entryMethod = item.value
	form.entryPassword = ''; form.keyLocation = ''
}

// 选择并上传头像
const chooseAvatar = () => {
    uni.chooseImage({
        count: 1, 
        sizeType: ['compressed'],
        success: async (res) => {
            try {
                uni.showLoading({ title: '上传中...' })
                const uploadRes = await uploadFile(res.tempFilePaths[0])
                form.avatar = uploadRes.ossId
                avatarDisplayUrl.value = uploadRes.url
                uni.hideLoading()
                uni.showToast({ title: '修改成功', icon: 'success' })
            } catch (err) {
                uni.hideLoading()
                console.error('头像上传失败', err)
            }
        }
    })
}

const onSave = async () => {
    if (!form.name) return uni.showToast({ title: '请输入姓名', icon: 'none' })
    if (!form.phone) return uni.showToast({ title: '请输入手机号', icon: 'none' })
    if (!form.stationId) return uni.showToast({ title: '请选择所属站点', icon: 'none' })
    if (!form.address) return uni.showToast({ title: '请输入详细住址', icon: 'none' })
    if (!form.entryMethod) return uni.showToast({ title: '请选择入门方式', icon: 'none' })

    saving.value = true
    try {
        await updateCustomer(form)
        uni.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => uni.navigateBack(), 1000)
    } catch(err) { } finally { saving.value = false }
}
</script>

<style lang="scss" scoped>
.user-edit-page { min-height: 100vh; background: #f7f8fa; padding-bottom: calc(140rpx + env(safe-area-inset-bottom)); }

.loading-state { padding-top: 15vh; display: flex; flex-direction: column; align-items: center; justify-content: center; }
.spinner { width: 44rpx; height: 44rpx; border: 4rpx solid #f3f3f3; border-top: 4rpx solid #ff9500; border-radius: 50%; animation: spin 1s linear infinite; }
.loading-txt { font-size: 24rpx; color: #999; margin-top: 20rpx; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

.avatar-section { display: flex; justify-content: center; padding: 40rpx 0 20rpx; }
.avatar-wrap { display: flex; flex-direction: column; align-items: center; gap: 12rpx; }
.avatar-img { width: 144rpx; height: 144rpx; border-radius: 50%; border: 4rpx solid #fff; box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08); }
.avatar-placeholder { width: 144rpx; height: 144rpx; border-radius: 50%; background: #f5f5f5; border: 2rpx dashed #EEEEEE; display: flex; align-items: center; justify-content: center; }
.avatar-icon {
	width: 60rpx; height: 60rpx; position: relative;
	.head { width: 30rpx; height: 30rpx; border-radius: 50%; background: #ddd; position: absolute; top: 0; left: 50%; transform: translateX(-50%); }
	.body { width: 50rpx; height: 26rpx; border-radius: 20rpx 20rpx 0 0; background: #ddd; position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); }
}
.avatar-tip { font-size: 22rpx; color: #999; }

.section-title { font-size: 30rpx; font-weight: bold; color: #333; padding: 32rpx 32rpx 16rpx; }
.form-card { background: #fff; border-radius: 24rpx; padding: 8rpx 32rpx; margin: 0 24rpx 24rpx; }
.form-item { display: flex; align-items: center; padding: 28rpx 0; border-bottom: 2rpx solid #EEEEEE; position: relative; }
.form-item:last-child { border-bottom: none; }
.form-item.vertical { flex-direction: column; align-items: stretch; }
.form-textarea { width: 100%; height: 160rpx; margin-top: 16rpx; background: #f9f9f9; padding: 20rpx; box-sizing: border-box; border-radius: 12rpx; font-size: 28rpx; }

.form-label { width: 220rpx; font-size: 28rpx; color: #333; flex-shrink: 0; }
.form-label.require::before { content: '*'; color: #f56c6c; margin-right: 4rpx; }
.form-input { flex: 1; font-size: 28rpx; color: #333; text-align: right; }
.picker-value { flex: 1; font-size: 28rpx; color: #333; text-align: right; margin-right: 16rpx; }
.picker-value.placeholder { color: #ccc; }

.right-arrow { width: 14rpx; height: 14rpx; border-right: 3rpx solid #ccc; border-top: 3rpx solid #ccc; transform: rotate(45deg); }
.footer-bar { position: fixed; bottom: 0; left: 0; right: 0; background: #fff; padding: 20rpx 32rpx calc(20rpx + env(safe-area-inset-bottom)); box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05); z-index: 100; }
.save-btn { width: 100%; height: 88rpx; background: linear-gradient(90deg, #ffd53f, #ff9500); color: #fff; border: none; border-radius: 44rpx; font-size: 32rpx; font-weight: bold; line-height: 88rpx; }

.center-modal-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); z-index: 10000; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4rpx); }
.center-modal-content { width: 620rpx; background: #fff; border-radius: 32rpx; display: flex; flex-direction: column; overflow: hidden; animation: popIn 0.3s ease-out; }
@keyframes popIn { from { transform: scale(0.85); opacity: 0; } to { transform: scale(1); opacity: 1; } }

.modal-header { padding: 32rpx; border-bottom: 2rpx solid #f2f2f2; position: relative; text-align: center; }
.modal-title { font-size: 32rpx; font-weight: bold; color: #333; }
.close-btn { 
	position: absolute; right: 30rpx; top: 32rpx; width: 40rpx; height: 40rpx;
	&::before, &::after { content: ''; position: absolute; top: 18rpx; left: 5rpx; width: 30rpx; height: 4rpx; background: #999; transform: rotate(45deg); border-radius: 4rpx; }
	&::after { transform: rotate(-45deg); }
}

.step-indicator { display: flex; align-items: center; justify-content: center; padding: 24rpx; background: #fdfdfd; border-bottom: 2rpx solid #f9f9f9; gap: 8rpx; }
.step-item { font-size: 24rpx; color: #999; max-width: 150rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.step-item.active { color: #ff9500; font-weight: bold; }
.modal-list-scroll { flex: 1; max-height: 55vh; padding: 0 32rpx; }
.list-item { display: flex; align-items: center; justify-content: space-between; padding: 32rpx 0; border-bottom: 2rpx solid #f9f9f9; }
.checkmark { width: 12rpx; height: 24rpx; border-right: 4rpx solid #ff9500; border-bottom: 4rpx solid #ff9500; transform: rotate(45deg); }
.empty-tip { padding: 80rpx 0; text-align: center; color: #ccc; }
</style>
