<template>
	<view class="lists">
		<view class="status_bar" :style="navHeight"></view>
		<view class="main" :style="mainHeight">
			<view class="middle view">
				<view class="text-block">
					<text class="middle-date">省</text>
					<view class="middle-date-des uni-list picker-year">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker class="picker-block" @change="changeArea($event,'city')" :value="regionIndex"
									range-key='BEZEI' mode="selector" :range="selectDataOptions['regionList']">
									<text class="uni-input">{{terminalAdd.REGION_TEXT || '请选择'}}</text>
								</picker>
							</view>
						</view>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
					</view>
				</view>
				<view class="text-block">
					<text class="middle-date">市</text>
					<view class="middle-date-des uni-list picker-year">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker class="picker-block" @change="changeArea($event,'street')" :value="cityIndex"
									range-key='CITY_NAME' mode="selector" :range="selectDataOptions['cityList']">
									<text class="uni-input">{{terminalAdd.CITY_TEXT || '请选择'}}</text>
								</picker>
							</view>
						</view>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
					</view>
				</view>
				<view class="text-block">
					<text class="middle-date">区</text>
					<view class="middle-date-des uni-list picker-year">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker class="picker-block" @change="changeArea($event,'q')" :value="streetIndex"
									range-key='MC_STREET' mode="selector" :range="selectDataOptions['streetList']">
									<text class="uni-input">{{terminalAdd.STREET_TEXT || '请选择'}}</text>
								</picker>
							</view>
						</view>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
					</view>
				</view>
				<view class="text-block">
					<text class="middle-date">详细地址</text>
					<input class="middle-date-des" type="text" v-model="terminalAdd.STREET" placeholder="请输入" />
				</view>
			</view>
		</view>
		<view class="bottom">
			<button class="btn" type="default" @tap="confirm">
				<text class="btn-text">提交</text>
			</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'


	import {
		findByCustomer
	} from '@/servers/purchaseList.js'
	
	import timeFormat from '@/uview-ui/libs/function/timeFormat.js'
	import { getArea } from '@/servers/address.js'
	export default {
		data() {
			return {
				isCommon: false, // 是否为普通要货申请的地址选择
				terminalAdd: {
					REGION: '',
					REGION_TEXT: '',
					CITY_CODE: '',
					CITY_TEXT: '',
					STREET_CODE: '',
					STREET_TEXT: '',
					STREET: '',
					CONTACT_PERSON: '', // 联系人
					CONTACT_NUMBER: '' // 联系电话
				},
				selectDataOptions: {
					cityList: [],
					streetList: [],
					regionList: []
				},
				regionIndex: 0,
				cityIndex: 0,
				streetIndex: 0
			}
		},
		computed: {
			...mapState(['sysinfo', 'userInfo']),
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			mainHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height - 55 }px`,
				}
			},
			scrollHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height - 44 - 156 }px`
				}
			},

		},
		onLoad(options) {
			console.log('select-address onLoad options:', options)
			// 检查是否是普通要货申请的地址选择（isCommon=true）
			if (options.isCommon === 'true' || options.isCommon === true) {
				this.isCommon = true
				console.log('设置为普通要货申请地址选择模式')
				// 如果有传入的订单数据，初始化地址信息
				if (options.order) {
					try {
						const orderData = JSON.parse(decodeURIComponent(options.order))
						console.log('解析订单数据:', orderData)
						if (orderData.region || orderData.cityCode || orderData.streetcode) {
							// 初始化地址数据
							this.terminalAdd.REGION = orderData.region || ''
							this.terminalAdd.CITY_CODE = orderData.cityCode || ''
							this.terminalAdd.STREET_CODE = orderData.streetcode || ''
							// 如果有联系人信息，也初始化
							if (orderData.contacPerson) {
								this.terminalAdd.CONTACT_PERSON = orderData.contacPerson
							}
							if (orderData.contactNumber) {
								this.terminalAdd.CONTACT_NUMBER = orderData.contactNumber
							}
							// 加载对应的省市区数据
							this.initAddressData()
						}
					} catch (e) {
						console.error('解析订单数据失败:', e)
					}
				}
			} else {
				this.isCommon = false
			}
		},
		created() {
			this.getAreaArr()
		},
		methods: {
			// 省
			async getAreaArr(){
			  // 普通要货申请不传 ZDZG 参数
			  const mode = this.isCommon ? '' : 'ZDZG'
			  await getArea('','region', mode).then(res => {
				this.selectDataOptions['regionList'] = res.DATA
			  })
			},
			// 初始化地址数据（当有初始地址时）
			async initAddressData() {
				if (this.terminalAdd.REGION) {
					// 加载省数据
					await this.getAreaArr()
					// 找到对应的省
					const regionItem = this.selectDataOptions['regionList'].find(item => item.BLAND === this.terminalAdd.REGION)
					if (regionItem) {
						this.terminalAdd.REGION_TEXT = regionItem.BEZEI
						// 加载市数据
						const cityRes = await getArea(this.terminalAdd.REGION, 'city', this.isCommon ? '' : 'ZDZG')
						this.selectDataOptions.cityList = cityRes.DATA || []
						if (this.terminalAdd.CITY_CODE) {
							const cityItem = this.selectDataOptions['cityList'].find(item => item.CITY_CODE === this.terminalAdd.CITY_CODE)
							if (cityItem) {
								this.terminalAdd.CITY_TEXT = cityItem.CITY_NAME
								// 加载区数据
								const streetRes = await getArea(this.terminalAdd.CITY_CODE, 'street', this.isCommon ? '' : 'ZDZG')
								this.selectDataOptions.streetList = streetRes.DATA || []
								if (this.terminalAdd.STREET_CODE) {
									const streetItem = this.selectDataOptions['streetList'].find(item => item.STRT_CODE === this.terminalAdd.STREET_CODE)
									if (streetItem) {
										this.terminalAdd.STREET_TEXT = streetItem.MC_STREET
									}
								}
							}
						}
					}
				}
			},
			async changeArea(e, type) {
			  if (e) {
				 console.log('picker发送选择改变，携带值为', e.detail.value)
				 const index = e.detail.value || 0
				 // 普通要货申请不传 ZDZG 参数
				 const mode = this.isCommon ? '' : 'ZDZG'
				if (type === 'city') {
				  const code = this.selectDataOptions['regionList'][index].BLAND
				  this.terminalAdd.REGION = code
				  this.regionIndex = index
				  const { DATA } = await getArea(code, type, mode)
				  this.selectDataOptions.cityList = DATA || []
				  this.terminalAdd.REGION_TEXT = this.selectDataOptions['regionList'].find(v => v.BLAND === code)?.BEZEI || ''
				  this.terminalAdd.CITY_CODE = ''
				  this.terminalAdd.STREET_CODE = ''
				  this.terminalAdd.CITY_TEXT = ''
				  this.terminalAdd.STREET_TEXT = ''
				  this.terminalAdd.STREET = ''
				  this.selectDataOptions.streetList = []
				  this.cityIndex = 0
				  this.streetIndex = 0
				} else if (type === 'street') {
				  const code = this.selectDataOptions['cityList'][index].CITY_CODE
				  this.terminalAdd.CITY_CODE = code
				  this.cityIndex = index
				  const { DATA } = await getArea(code, type, mode)
				  this.selectDataOptions.streetList = DATA || []
				  this.terminalAdd.STREET_CODE = ''
				  this.terminalAdd.STREET_TEXT = ''
				  this.terminalAdd.STREET = ''
				  this.terminalAdd.CITY_TEXT = this.selectDataOptions['cityList'].find(v => v.CITY_CODE === code)?.CITY_NAME || ''
				  this.streetIndex = 0
				} else {
				  const code = this.selectDataOptions['streetList'][index].STRT_CODE
				  this.terminalAdd.STREET_CODE = code
				  this.streetIndex = index
				  this.terminalAdd.STREET_TEXT = this.selectDataOptions['streetList'].find(v => v.STRT_CODE === code)?.MC_STREET || ''
				}
			  }
			},
			confirm() {
				if(!this.terminalAdd.REGION_TEXT){
					uni.showToast({
						title: '请选择省',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				if(!this.terminalAdd.CITY_TEXT){
					uni.showToast({
						title: '请选择市',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				if(!this.terminalAdd.STREET_TEXT){
					uni.showToast({
						title: '请选择区',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				if(!this.terminalAdd.STREET){
					uni.showToast({
						title: '请输入详细地址',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				
				// 确保所有编码字段都已保存
				if (!this.terminalAdd.REGION && this.terminalAdd.REGION_TEXT) {
					// 如果只有名称没有编码，尝试从列表中找到编码
					const regionItem = this.selectDataOptions['regionList'].find(item => item.BEZEI === this.terminalAdd.REGION_TEXT)
					if (regionItem) {
						this.terminalAdd.REGION = regionItem.BLAND
					}
				}
				if (!this.terminalAdd.CITY_CODE && this.terminalAdd.CITY_TEXT) {
					const cityItem = this.selectDataOptions['cityList'].find(item => item.CITY_NAME === this.terminalAdd.CITY_TEXT)
					if (cityItem) {
						this.terminalAdd.CITY_CODE = cityItem.CITY_CODE
					}
				}
				if (!this.terminalAdd.STREET_CODE && this.terminalAdd.STREET_TEXT) {
					const streetItem = this.selectDataOptions['streetList'].find(item => item.MC_STREET === this.terminalAdd.STREET_TEXT)
					if (streetItem) {
						this.terminalAdd.STREET_CODE = streetItem.STRT_CODE
					}
				}
				
				// 调试日志
				console.log('地址选择完成，发送数据:', this.terminalAdd)
				console.log('isCommon:', this.isCommon)
				
				// 根据 isCommon 参数决定发送哪个事件
				if (this.isCommon) {
					// 普通要货申请，发送 selectCommonAddress 事件
					uni.$emit('selectCommonAddress', {
						selectCommonAddress: { ...this.terminalAdd }
					})
				} else {
					// 终端直配，发送 selectTerminalAddress 事件
					uni.$emit('selectTerminalAddress', {
						selectTerminalAddress: { ...this.terminalAdd }
					})
				}
				uni.navigateBack()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.view {
		flex-direction: column;
	}
	.lists {
		flex: 1;
		flex-direction: column;
		background: #f0f4f5;
		// overflow-y: scroll;
	}
	
	.scroll-area {
		flex: 1;
	}
	
	.main {
		margin: 0 16rpx;
		flex-direction: column;
		border-radius: 16rpx;
		margin-top: 16rpx;
	}
	
	.middle {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 0 48rpx;
		margin-bottom: 16rpx;
	}
	.address-view{
		flex: 1;
	}
	
	.text-block {
		overflow: hidden;
		// height: 96rpx;
		// margin-bottom: 14rpx;
		border-bottom: 1px solid #f4f5f6;
	}
	.text-address {
		overflow: hidden;
		border-bottom: 1px solid #f4f5f6;
	}
	
	.text-block-last {
		margin-bottom: 0;
		border-bottom: 0;
	}
	
	.middle-date {
		flex: 2;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #999;
	}
	
	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		height: 96rpx;
		line-height: 96rpx;
		color: $text-base-color;
	}
	.middle-date-address {
		color: #333;
		font-size: 28rpx;
		flex: 3;
		padding-top: 10rpx;
		justify-content: start;
		font-size: 28rpx;
		height: 96rpx;
	}
	.middle-date-address-text {
		color: #333;
		font-size: 28rpx;
		flex: 1;
		justify-content: start;
		font-size: 28rpx;
		height: 70rpx;
		line-height: 34rpx;
		align-items: center;
	}
	.middle-date-margin-des{
		flex: 1;
		font-size: 28rpx;
		color: #333;
		margin-top: 0rpx;
		margin-bottom: 20rpx;
		width: 200%;
		text-align: left;
		justify-content: end;
	}
	.picker-year {
		position: relative;
		align-items: center;
	}
	
	.uni-list-cell {
		flex: 1;
		height: 100%;
	}
	
	.uni-list-cell-db {
		flex: 1;
	}
	
	.picker-block {
		flex: 1;
	}
	
	.uni-input {
		line-height: 100%;
		height: 100%;
		font-size: 14px;
		color: $text-base-color;
	}
	
	.icon-arrow {
		position: absolute;
		right: 22rpx;
		top: 40rpx;
		width: 7px;
		height: 10px;
		z-index: 10;
	}
	
	.remark-text {
		flex: 1;
		height: 220rpx;
		background: #f5f6f7;
		border-radius: 4px;
		padding: 12rpx 18rpx;
		margin-bottom: 40rpx;
	}
	
	.title-first {
		border-bottom: 0;
	}
	
	.title-first__text {
		font-size: 28rpx;
		color: #333333;
		font-weight: 600;
	}
	
	.receive-record-view {
		padding: 40rpx 48rpx;
	}
	
	.receive-record {
		color: #555555;
		font-size: 28rpx;
		margin-bottom: 8rpx;
		margin-top: 32rpx;
	}
	
	.receive-record-info {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	
	.record-info-title {
		color: #333;
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 16rpx;
	}
	
	.record-info-des {
		color: #999;
		font-size: 24rpx;
	}
	
	.bottom-area {
		height: 140rpx;
		margin-top: 12rpx;
	}
	
	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 10;
		width: 750rpx;
		height: 140rpx;
		padding: 0 32rpx;
		justify-content: space-between;
		align-items: center;
		background: #fff;
	}
	
	.btn {
		flex: 1;
		height: 92rpx;
		background: $wly-primary-color;
		border-radius: 46rpx;
	}
	
	.btn-l {
		margin-right: 30rpx;
		border: 1px solid $wly-primary-color;
		background-color: #fff;
	
	}
	
	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}
	
	.btn-text-l {
		color: $wly-primary-color;
	}
	.middle-date-unit {
		flex: 2;
		font-size: 28rpx;
		color: #999;
		margin-bottom: 8rpx;
		padding-top: 30rpx;
	}
	
	.middle-date-des-unit {
		flex: 3;
		font-size: 28rpx;
		min-height: 96rpx;
		color: $text-base-color;
		padding-top: 30rpx;
		justify-content: start;
	}
	.middle-date-add {
		flex: 2;
		font-size: 28rpx;
		color: #999;
		margin-bottom: 8rpx;
		padding-top: 30rpx;
	}
	
	.middle-date-des-add {
		flex: 3;
		font-size: 28rpx;
		min-height: 124rpx;
		color: $text-base-color;
		padding-top: 30rpx;
		justify-content: start;
	}
	.summary-block {
		display: flex;
		align-items: center;
	}
	.summary {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-bottom: 32rpx;
		padding: 32rpx 48rpx 140rpx;
	}
	.icon_plan {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}
	
</style>
