<template>
	<view class="apply-page">
		<view class="form-section">
			<view class="form-row" @click="showCityPicker = true">
				<text class="label">城市</text>
				<text class="value" :class="{ placeholder: !cityText }">
					{{ cityText || '选择城市' }}
				</text>
				<image class="chevron" src="@/static/workbench/right.png" mode=""></image>
			</view>
			<view class="form-row" @click="openCenterPicker">
				<text class="label">运营中心</text>
				<text class="value" :class="{ placeholder: !form.centerName }">
					{{ form.centerName || '选择' }}
				</text>
				<image class="chevron" src="@/static/workbench/right.png" mode=""></image>
			</view>
			<view class="reason-block">
				<text class="label">申请原因</text>
				<textarea class="reason-input" v-model="form.reason" placeholder="请输入原因" maxlength="500"
					@input="onReasonInput" />
				<text class="char-count">{{ form.reason.length }}/500</text>
			</view>
		</view>


		<view class="footer-bar">
			<view class="submit-btn" @click="onSubmit">申请开通</view>
		</view>

		<!-- 省 / 市 二级联动 -->
		<u-popup :show="showCityPicker" mode="bottom" border-radius="16rpx 16rpx 0 0"
			:style="{ height: '600rpx', zIndex: 9999, }">
			<u-picker :key="pickerKey" :defaultIndex="defaultCityIndex" :show="showCityPicker" ref="uPicker"
				confirmColor="#fff" title="选择城市" keyName="name" :columns="cityColumns"
				@confirm="onSelect" @change="changeHandler" @cancel="showCityPicker = false"></u-picker>

		</u-popup>

		<!-- 运营中心 -->
		<u-picker :show="showCenterPicker" :defaultIndex="defaultCenterIndex" title="运营中心" :columns="[centerOptions]" keyName="name"
			@confirm="onCenterConfirm" @cancel="showCenterPicker = false" confirmColor="#fff"></u-picker>
	</view>
</template>

<script>
import {
	PROVINCE_CITY_TREE,
	getCitiesByProvince,
	getCentersByCity,
} from './mock.js'
import { saveCity } from '@/api/workbench.js'
import { provinceCityTree, regionList } from '@/api/newLogin.js'

export default {
	data() {
		return {
			defaultCityIndex: [0, 0],
			defaultCenterIndex: [0],
			pickerKey: 1,
			form: {
				province: '',
				city: '',
				provinceCode: '',
				cityCode: '',
				centerId: '',
				centerName: '',
				reason: '',
			},
			showCityPicker: false,
			showCenterPicker: false,
			cityColumns: [],
			centerOptions: [],
			provinceIndex: 0,
			allCityList: [],
		}
	},
	computed: {
		cityText() {
			if (!this.form.province || !this.form.city) return ''
			if (this.form.province === this.form.city) return this.form.city
			return `${this.form.province} ${this.form.city}`
		},
	},
	onLoad() {
		this.getCity()
	},
	methods: {
		initCityPicker() {
			const provinces = PROVINCE_CITY_TREE.map(p => ({ name: p.name }))
			const cities = getCitiesByProvince(provinces[0]?.name || '').map(c => ({ name: c.name }))
			this.cityColumns = [provinces, cities]
		},
		//获取城市
		getCity() {
			provinceCityTree().then(res => {
				console.log(res, '获取城市')
				this.allCityList = res.data.data
				const provinces = res.data.data.map(p => ({ name: p.name, code: p.code }))
				const cities = this.getCitiesByProvince(this.form.provinceName || provinces[0]?.name || '').map(c => ({ name: c.name, code: c.code }))
				this.cityColumns = [provinces, cities]
			});
		},
		//选择城市
		onSelect(e) {
			if (!e.value[0]) return
			this.form.province = e.value[0]?.name || ''
			this.form.city = e.value[1]?.name || ''
			this.form.provinceCode = e.value[0]?.code || ''
			this.form.cityCode = e.value[1]?.code || ''
			this.form.centerName = ''
			this.showCityPicker = false
		},
		//滚动选择器
		changeHandler(e) {
			console.log(e, 'e')
			const {
				columnIndex,
				value,
				values, // values为当前变化列的数组内容
				index,
				picker = this.$refs.uPicker
			} = e
			// 当第一列值发生变化时，变化第二列(后一列)对应的选项
			if (columnIndex === 0) {
				// picker为选择器this实例，变化第二列对应的选项
				const provinceName = this.allCityList[index]?.name
				const cities = this.getCitiesByProvince(provinceName).map(c => ({ name: c.name, code: c.code }))
				picker.setColumnValues(1, cities)

			}


		},
		getCitiesByProvince(provinceName) {
			const province = this.allCityList.find(p => p.name === provinceName)
			return province ? province.children : []
		},
		onCityColumnChange(e) {
			const { columnIndex, index } = e
			if (columnIndex !== 0) return
			this.provinceIndex = index
			const provinceName = PROVINCE_CITY_TREE[index]?.name
			const cities = getCitiesByProvince(provinceName).map(c => ({ name: c.name }))
			this.cityColumns = [
				this.cityColumns[0],
				cities,
			]
		},
		//选择运营中心
		async openCenterPicker() {
			if (!this.form.province || !this.form.city) {
				uni.showToast({ title: '请先选择城市', icon: 'none' })
				return
			}
			await regionList({ parentCode: this.form.provinceCode, cityCode: this.form.cityCode }).then(res => {
				if (res.data.code == 200) {
					this.centerOptions = res.data.data.map(c => ({ name: c.deptName, deptId: c.deptId , disabled: /^(0,)*0$/.test(c.ancestors) ? true : false }))
				}
			})
			if (!this.centerOptions.length) {
				uni.showToast({ title: '该城市暂无运营中心', icon: 'none' })
				return
			}
			this.showCenterPicker = true
		},
		//选择运营中心确认
		onCenterConfirm(e) {
			const center = e.value[0]
			if (center && center.disabled) {
				uni.showToast({
					title: '该部门不可选，请选择其他部门',
					icon: 'none'
				})
				return
			}
			this.form.centerId = center.deptId
			this.form.centerName = center.name
			this.showCenterPicker = false
		},
		onReasonInput(e) {
			const val = (e.detail.value || '').slice(0, 500)
			this.form.reason = val
		},
		onSubmit() {
			if (!this.form.province || !this.form.city) {
				uni.showToast({ title: '请选择城市', icon: 'none' })
				return
			}
			if (!this.form.centerId) {
				uni.showToast({ title: '请选择运营中心', icon: 'none' })
				return
			}
			if (!this.form.reason.trim()) {
				uni.showToast({ title: '请输入申请原因', icon: 'none' })
				return
			}
			// 提交接口待对接
			let params={
				provinceCode: this.form.provinceCode,
				provinceName: this.form.province,
				cityCode: this.form.cityCode,
				cityName: this.form.city,
				operationCenterId: this.form.centerId,
				operationCenterName: this.form.centerName,
				applyReason: this.form.reason,
				merchantId: uni.getStorageSync('userId'),
			}
			console.log(params, 'params')
			console.log(this.form, 'form')
			saveCity(params).then(res => {
				if (res.data.code == 200) {
					uni.showToast({ title: res.data.msg, icon: 'none' })
					setTimeout(() => uni.navigateBack(), 1000)
				}
			})
			
		},
	},
}
</script>

<style lang="scss" scoped>
::v-deep .u-toolbar__title {
	font-weight: 500;
	font-size: 36rpx;
	color: #1D2129;
}

::v-deep .u-picker__view__column__item {
	font-weight: 400 !important;
	font-size: 28rpx;
	color: #1D2129
}

::v-deep .u-upload__success {
	display: none;
}

::v-deep .u-picker {
	bottom: 136rpx;
	background-color: #ffffff;
	position: relative;
}

::v-deep .u-toolbar__cancel__wrapper {
	width: 30rpx;
	height: 30rpx;
	position: absolute;
	right: 32rpx;
	background-image: url('/static/login/closeIcon.png');
	background-repeat: no-repeat;
	background-size: 100% 100%;

	.u-toolbar__wrapper__cancel {
		width: 30rpx;
		height: 30rpx;

		span {
			display: none;
		}

	}
}

/* 关键：穿透隐藏原生 toolbar，只留插槽内容 */
.u-toolbar {
	z-index: 9999 !important;
	display: block !important;
}

::v-deep .u-toolbar__cancel__wrapper {
	color: #666;
}

::v-deep .u-toolbar__confirm__wrapper {
	position: fixed;
	bottom: 0;
	width: 100%;
	padding: 24rpx 48rpx;

	.u-toolbar__wrapper__confirm {
		width: 654rpx;
		height: 88rpx;
		background: #333335;
		border-radius: 60rpx 60rpx 60rpx 60rpx;

		font-weight: 400;
		font-size: 32rpx;
		color: #FFFFFF;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}


.apply-page {
	min-height: 100vh;
	background: #f5f5f5;
	padding-bottom: 140rpx;
}

.form-section {
	background: #fff;
}

.form-row {
	display: flex;
	align-items: center;
	padding: 28rpx 32rpx;
	border-bottom: 1rpx solid #f5f5f5;
}

.label {
	width: 160rpx;
	flex-shrink: 0;
	font-size: 30rpx;
	color: #333;
}

.value {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #333;

	&.placeholder {
		color: #ccc;
	}
}

.chevron {
	width: 25rpx;
	height: 25rpx;
}

.reason-block {
	padding: 28rpx 32rpx;
}

.reason-input {
	width: 100%;
	min-height: 240rpx;
	margin-top: 16rpx;
	font-size: 28rpx;
	color: #333;
	line-height: 1.6;
	box-sizing: border-box;
}

.char-count {
	display: block;
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin-top: 12rpx;
}

.footer-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx 32rpx;
	padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
}

.submit-btn {
	margin: 0 auto;
	width: 654rpx;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	font-weight: 500;
	font-size: 32rpx;
	color: #FFFFFF;
	background: #333335;
	border-radius: 60rpx 60rpx 60rpx 60rpx;
}
</style>
