<template>
	<view class="user-add-page">
		<nav-bar title="新增用户" bgColor="#fff" color="#000"></nav-bar>

		<!-- 头像上传 -->
		<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">
					<!-- CSS 手绘人像图标 @Author: Antigravity -->
					<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" @click="openRegionModal">
				<text class="form-label">所在地区</text>
				<view class="picker-value" :class="{'placeholder': !regionLabel}">
					{{ regionLabel || '请选择省/市/区' }}
				</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>

		<!-- 站点三级联动居中弹窗 @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 || (currentStep === 1 ? '请选择区域' : '区域') }}
					</view>
					<view class="step-divider">/</view>
					<view class="step-item" :class="{ 'active': currentStep === 2 }" @click="selectedAreaId ? (currentStep = 2) : null">
						{{ selectedStationName || (currentStep === 2 ? '请选择站点' : '站点') }}
					</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>

		<!-- 省市区三级联动居中弹窗 -->
		<view class="center-modal-mask" v-if="showRegionModal" @click="showRegionModal = false" @touchmove.stop.prevent>
			<view class="center-modal-content region-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">选择地区</text>
					<view class="close-btn" @click="showRegionModal = false"></view>
				</view>

				<view class="cascade-indicator">
					<text v-for="(node, idx) in regionPath" :key="idx" class="path-node" @click="backToRegionLevel(idx)">{{ node.name }}</text>
					<text class="path-node active" v-if="regionPath.length < 3">请选择</text>
				</view>

				<scroll-view scroll-y class="modal-list-scroll">
					<view
						class="list-item"
						v-for="item in currentRegionList"
						:key="item.code"
						@click="onRegionStepSelect(item)"
					>
						<text class="item-text">{{ item.name }}</text>
						<view class="checkmark" v-if="isRegionSelected(item)"></view>
					</view>
					<view class="empty-tip" v-if="currentRegionList.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 { addCustomer } from '@/api/archieves/customer'
import { getInfo } from '@/api/system/user'
import { listAreaStation } from '@/api/system/areaStation'
import { listRegionTree } from '@/api/system/region'
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 saving = ref(false)
const allStationNodes = ref([])
const avatarDisplayUrl = ref('')
const regionTree = ref([])

// 弹窗状态
const showGenderSelect = ref(false)
const showHouseTypeSelect = ref(false)
const showEntryMethodSelect = ref(false)
const showStationModal = ref(false)
const showRegionModal = 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({
    name: '', phone: '', gender: undefined, areaId: undefined, stationId: undefined,
    address: '', houseType: '', entryMethod: '', entryPassword: '', keyLocation: '', remark: '', avatar: undefined,
    regionCode: ''
})

onLoad(async () => {
    try {
        const stationRes = await listAreaStation()
        allStationNodes.value = Array.isArray(stationRes) ? stationRes : (stationRes?.data || [])
    } catch (err) { console.error('获取站点失败', err); uni.showToast({ title: typeof err === 'string' ? err : '获取站点失败', icon: 'none' }) }
    try {
        const res = await listRegionTree()
        regionTree.value = Array.isArray(res) ? res : []
    } catch (err) { console.error('获取地区数据失败', err); uni.showToast({ title: typeof err === 'string' ? err : '获取地区数据失败', icon: 'none' }) }
})

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)
	} else if (currentStep.value === 1) {
		return allStationNodes.value.filter(n => String(n.parentId) === String(selectedCityId.value))
	} else {
		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(() => {
    if (!form.stationId) return '请选择'
    return `${selectedCityName.value} - ${selectedAreaName.value} - ${selectedStationName.value}`
})

// ========== 省市区三级联动 ==========
const regionPath = ref([])
const regionLabel = ref('')

const currentRegionList = computed(() => {
    let list = regionTree.value
    for (let node of regionPath.value) {
        const found = list.find(l => l.code === node.code)
        if (found && found.children) list = found.children
        else list = []
    }
    return list
})

const openRegionModal = () => {
    regionPath.value = []
    showRegionModal.value = true
}

const backToRegionLevel = (idx) => { regionPath.value = regionPath.value.slice(0, idx) }

const onRegionStepSelect = (item) => {
    regionPath.value.push({ code: item.code, name: item.name })
    if (!item.children || item.children.length === 0 || regionPath.value.length >= 3) {
        const fullLabel = regionPath.value.map(p => p.name).join(' / ')
        form.regionCode = regionPath.value.map(p => p.code).join('/')
        regionLabel.value = fullLabel
        showRegionModal.value = false
    }
}

const isRegionSelected = (item) => {
    const level = regionPath.value.length
    return regionPath.value[level]?.code === item.code
}

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)
                uni.showToast({ title: typeof err === 'string' ? err : '头像上传失败', icon: 'none' })
            }
        }
    })
}

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 {
        const submitData = { ...form }
        let tenantId = uni.getStorageSync('tenantId') || (await getInfo())?.user?.tenantId
        if (tenantId) submitData.tenantId = tenantId
        await addCustomer(submitData)
        uni.showToast({ title: '新增成功', icon: 'success' })
        setTimeout(() => uni.navigateBack(), 1000)
    } catch(err) { uni.showToast({ title: typeof err === 'string' ? err : '新增用户失败', icon: 'none' }) } finally { saving.value = false }
}
</script>

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

.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-tip { font-size: 22rpx; color: #999; }

/* CSS 手绘人像图标 @Author: Antigravity */
.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%); }
}

.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; gap: 0; }
.form-item.vertical .form-textarea { width: 100%; height: 160rpx; margin-top: 16rpx; background: #f9f9f9; padding: 20rpx; box-sizing: border-box; border-radius: 12rpx; font-size: 28rpx; color: #333; line-height: 1.6; }

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

/* CSS 绘制右箭头 @Author: Antigravity */
.right-arrow {
	width: 14rpx; height: 14rpx; border-right: 3rpx solid #ccc; border-top: 3rpx solid #ccc; transform: rotate(45deg); flex-shrink: 0;
}

.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; &::after { border: none; } }

/* 居中弹窗通用样式 @Author: Antigravity */
.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; }
/* X 关闭图标 @Author: Antigravity */
.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: 60vh; padding: 0 32rpx; }
.list-item { 
	display: flex; align-items: center; justify-content: space-between; padding: 32rpx 0; border-bottom: 2rpx solid #f9f9f9; 
	.item-text { font-size: 30rpx; color: #333; }
}
/* 对勾 @Author: Antigravity */
.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; font-size: 26rpx; }

/* 省市区级联样式 */
.region-modal {
    max-height: 75vh;
}

.cascade-indicator {
    display: flex;
    align-items: center;
    padding: 20rpx 32rpx;
    background: #fdfdfd;
    border-bottom: 2rpx solid #f9f9f9;
    gap: 8rpx;
    flex-wrap: wrap;
}

.cascade-indicator .path-node {
    font-size: 24rpx;
    color: #999;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
    background: #f5f5f5;
}

.cascade-indicator .path-node.active {
    color: #ff9500;
    font-weight: bold;
    background: #fff5e6;
}
</style>
