<template>
  <view>
    <up-form labelPosition="left" :model="modelForm" :rules="rulesForm" ref="formRef">
      <up-form-item label="姓名" prop="name" borderBottom labelWidth="70">
        <up-input v-model="modelForm.name" border="none" placeholder="请输入姓名"></up-input>
      </up-form-item>
      <up-form-item label="性别" prop="sex" borderBottom @click="() => (sexFlag = true)" labelWidth="70">
        <up-input v-model="displaySex" disabled disabledColor="#ffffff" placeholder="请选择性别" border="none"></up-input>
        <template #right>
          <up-icon name="arrow-right"></up-icon>
        </template>
      </up-form-item>
      <up-form-item label="关系" prop="label" borderBottom @click="() => labelFlag = true" labelWidth="70">
        <up-input v-model="modelForm.label" disabled disabledColor="#ffffff" placeholder="请选择关系"
          border="none"></up-input>
        <template #right>
          <up-icon name="arrow-right"></up-icon>
        </template>
      </up-form-item>
      <up-form-item label="年龄" prop="age" borderBottom labelWidth="70">
        <up-input v-model="modelForm.age" border="none" placeholder="请输入年龄"></up-input>
      </up-form-item>
      <up-form-item label="手机号" prop="telephone" borderBottom labelWidth="70">
        <up-input v-model="modelForm.telephone" border="none" placeholder="请输入手机号"></up-input>
      </up-form-item>
      <up-form-item label="地区" prop="area" borderBottom @click="()=> addressShow = true" labelWidth="70">
        <pickerAddress @change="addressChange"
          :selectValue="[ modelForm.provinceInd, modelForm.cityInd, modelForm.districtInd ]">
          <view class="inp"
            :class="modelForm.provinceName&&modelForm.cityName&&modelForm.districtName?'':'address-inp'">
            {{modelForm.provinceName ? modelForm.provinceName:'省'}} /
            {{modelForm.cityName ? modelForm.cityName:'市'}} /
            {{modelForm.districtName ? modelForm.districtName:'区'}}
          </view>
        </pickerAddress>
        <template #right>
          <up-icon name="map" size="22" @click="onCityWx"></up-icon>
        </template>
      </up-form-item>
      <up-form-item label="地址" prop="address" borderBottom labelWidth="70">
        <up-input v-model="modelForm.address" border="none" placeholder="请输入地址"></up-input>
      </up-form-item>
      <up-form-item label="门牌号" prop="detailAddress" borderBottom labelWidth="70">
        <up-input v-model="modelForm.detailAddress" border="none" placeholder="请输入地址"></up-input>
      </up-form-item>
    </up-form>
    <up-action-sheet :show="sexFlag" :actions="sexOptions" @select="sexSelect"
      @close="sexFlag = false"></up-action-sheet>
    <up-action-sheet :show="labelFlag" :actions="relaTionsHip" @select="sexSelectsHip"
      @close="labelFlag = false"></up-action-sheet>
    <view class="Wrapper-Btn">
      <up-button @click="handleQux" type="error" :plain="true" :hairline="true" text="取消"
        :customStyle="hadlClickEdit"></up-button>
      <up-button type="error" @click="handleSubmit" text="编辑" :customStyle="hadlClickEdit" />
    </view>
  </view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		useraDdress,
	} from "@/api/userSettings.js"
	// import pickerAddress from '@/components/pickerAddress/pickerAddress.vue' // 地区选择器组件
	import pickerAddress from '@/pages_mine/components/pickerAddress/pickerAddress.vue' // 地区选择器组件
	import {
		splitAddress
	} from '@/utils/adress'
	const formRef = ref(null)


	// 获取页面传递的参数
	onLoad((options) => {
		if (options) {
			options.cityName = decodeURIComponent(decodeURIComponent(options.cityName || ''));
			options.districtName = decodeURIComponent(decodeURIComponent(options.districtName || ''));
			options.label = decodeURIComponent(decodeURIComponent(options.label || ''));
			options.provinceName = decodeURIComponent(decodeURIComponent(options.provinceName || ''));
			options.name = decodeURIComponent(decodeURIComponent(options.name || ''));
      options.address = decodeURIComponent(decodeURIComponent(options.address || ''));
      options.detailAddress = decodeURIComponent(decodeURIComponent(options.detailAddress || ''));
			modelForm.value = {
				...modelForm.value,
				...options,
				sex: options.sex ? Number(options.sex) : '',
				age: options.age ? Number(options.age) : '',
				provinceName: options.provinceName || '',
				cityName: options.cityName || '',
				districtName: options.districtName || '',
				districtCode:options.districtCode,
				provinceCode:options.provinceCode
			};
		}
	});

	const modelForm = ref({
		name: '',
		sex: '',
		label: '',
		age: '',
		telephone: '',

		provinceName: '', // 省
		provinceCode: '',
		provinceInd: 0,

		cityName: '', // 市
		cityCode: '',
		cityInd: 0,

		districtName: '',
		districtCode: '',
		districtInd: 0,

		address: ''
	})
	// 回显把provinceName,cityName,districtName字段拼接
	const rulesForm = ref({
		name: {
			type: 'string',
			required: true,
			message: '请填写姓名',
			trigger: ['blur', 'change'],
		},
		sex: {
			type: 'number',
			required: true,
			message: '请选择性别',
			trigger: ['change']
		},
		label: {
			type: 'string',
			required: true,
			message: '请选择关系',
			trigger: ['change'],
		},
		userInfo: {
			type: 'string',
			required: true,
			message: '请填写年龄',
			trigger: ['blur', 'change'],
		},
		telephone: {
			type: 'string',
			required: true,
			message: '请填写手机号',
			trigger: ['blur', 'change'],
		},
	})

	let sexFlag = ref(false)
	let labelFlag = ref(false)
	let addressShow = ref(false)
	let index = ref(0)


	const sexOptions = ref([{
		name: '男',
		value: 0,
	}, {
		name: '女',
		value: 1,
	}, ]);

	const relaTionsHip = ref([{
			name: '父母'
		}, {
			name: '子女'
		},
		{
			name: '兄弟'
		},
		{
			name: '朋友'
		},
		{
			name: '同学'
		},
		{
			name: '同事'
		},
		{
			name: '配偶'
		}
	]);

	const displaySex = computed({
		get() {
			const option = sexOptions.value.find(item => item.value === modelForm.value.sex)
			return option ? option.name : ''
		},
		set(newValue) {
			const option = sexOptions.value.find(item => item.name === newValue)
			if (option) {
				modelForm.value.sex = option.value
			}
		}
	})
	// 性别选择处理
	function sexSelect(e) {
		modelForm.value.sex = e.value; // 确保是 0 或 1
		console.log('Selected sex:', e.value, 'Model sex:', modelForm.value.sex);
		sexFlag.value = false;
		// 手动触发验证
		formRef.value.validateField('sex');
	}

	function sexSelectsHip(e) {
		modelForm.value.label = e.name;
		labelFlag.value = false;
	}

	function addressChange(info) {
		console.log('地区选择器返回的完整数据:', info);
		console.log('地区编码:', info.code);
		if (!info || !info.data) {
			console.error('Invalid address change info:', info);
			return;
		}

		if (!Array.isArray(info.data) || info.data.length < 3) {
			console.error('Invalid address data:', info.data);
			return;
		}

		const code = Array.isArray(info.code) ? info.code : ['', '', ''];

		let indexArray;
		if (Array.isArray(info.index)) {
			indexArray = info.index;
		} else if (info.index && typeof info.index[Symbol.iterator] === 'function') {
			indexArray = Array.from(info.index);
		} else {
			indexArray = [0, 0, 0];
		}

		modelForm.value.provinceName = info.data[0] || '';
		modelForm.value.provinceCode = code[0] || '';
		modelForm.value.provinceInd = indexArray[0] || 0;

		modelForm.value.cityName = info.data[1] || '';
		modelForm.value.cityCode = code[1] || '';
		modelForm.value.cityInd = indexArray[1] || 0;

		modelForm.value.districtName = info.data[2] || '';
		modelForm.value.districtCode = code[2] || '';
		modelForm.value.districtInd = indexArray[2] || 0;
	}

	function onCityWx(row) {
		console.log('地区选点', row);
		wx.chooseLocation({
			success: function(res) {
				const result = splitAddress(res.address);
				console.log(res, result);
				modelForm.value.provinceName = result.province
				modelForm.value.cityName = result.city
				modelForm.value.districtName = result.district
				modelForm.value.address = result.detail
				modelForm.value.longitude = res.longitude
				modelForm.value.latitude = res.latitude


			},
			fail: function(err) {
				console.log(err);
				uni.showToast({
					title: '获取地址失败',
					icon: 'error',
				});
			},
		})
	}

	// 提交编辑
	async function handleSubmit() {
		try {
			// 1. 验证表单
			await formRef.value.validate();

			// 2. 准备提交数据
			const submitData = {
				...modelForm.value,
				sex: modelForm.value.sex,
			};

			// 3. 显示加载中提示（可选）
			uni.showLoading({
				title: '提交中...',
				mask: true
			});

			// 4. 调用接口
			const response = await useraDdress(submitData);

			// 5. 隐藏加载中
			uni.hideLoading();

			// 6. 处理响应
			if (response.code === 200) {
				await new Promise((resolve) => {
					uni.showToast({
						title: '编辑成功',
						icon: 'success',
						duration: 1500, // 默认1500ms
						mask: true,
						success: () => {
							// 等待Toast显示完成
							setTimeout(() => resolve(), 1500);
						}
					});
				});

				// 7. 跳转页面
				uni.navigateTo({
					url: '/pages_mine/pages/selectAddress/index'
				});
			} else {
				uni.showToast({
					title: response.msg || '编辑失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			console.error('编辑失败', error);
			uni.showToast({
				title: '编辑失败: ' + (error.message || '未知错误'),
				icon: 'none'
			});
		}
	}
	const handleQux = () => {
		uni.navigateBack({
			delta: -1
		})
	}
	const hadlClickEdit = {
		width: '240rpx',
		marginTop: '30rpx'
	}
</script>

<style scoped>
	.Wrapper-Btn {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>