<template>
	<view class="personal-info">
		<view class="personal-info-box">
			<!-- 上传 -->
			<view class="upload">
				<view class="upload-box">
					<up-upload @afterRead="
				      async (e) => {
				        await afterRead(e);
				        getImage();
				      }
				    " name="1" :maxCount="1" :previewImage="false" :deletable="false" :multiple="false">
						<view class="upload-block">
							<up-avatar size="144rpx" shape="circle" :src="userInfo.avatar" mode="aspectFill"></up-avatar>
							<view class="upload-block-edit flex-center">
								<image src="@/static/images/edit@2x.png" mode=""></image>
							</view>
						</view>
					</up-upload>
				</view>
			</view>
			<view class="personal-list">
				<view class="flex-center-between border-bottom personal-info-item">
					<text class="label_width">昵称</text>
					<up-input class="title-input" placeholder="请输入" type="text" confirmType="完成" maxlength="10"
						:adjustPosition="false" border="none" :showWordLimit="true" v-model="userInfo.nickname" inputAlign="right"></up-input>
				</view>
				<view class="flex-center-between border-bottom personal-info-item">
					<text class="label_width">手机号</text>
					<text class="gray">{{telEncrypt(userInfo.phone)}}</text>
				</view>
			</view>
			<view class="personal-list">
				<view class="flex-center-between border-bottom personal-info-item" @click="pickerSexShow = true">
					<text class="label_width">性别</text>
					<view class="flex-center-between">
						<text>{{sexText}}</text>
						<image style="width: 32rpx;height: 32rpx;" src="/static/images/right.png" mode=""></image>
					</view>
				</view>
				<view class="flex-center-between border-bottom personal-info-item">
					<text class="label_width">地址</text>
					<picker mode="multiSelector" @change="bindRegionChange" @columnchange="bindMultiPickerColumnChange"
						:value="valueRegion" :range="multiArray">
						<view class='flex-center-between'>
							<view class="picker line1">{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view>
							<image style="width: 32rpx;height: 32rpx;" src="/static/images/right.png" mode=""></image>
						</view>
					</picker>
					
				</view>
				<view class="flex-center-between border-bottom personal-info-item">
					<text class="label_width">年龄</text>
					<up-input class="title-input" placeholder="请输入年龄" fontSize="28rpx" type="text" confirmType="完成" maxlength="3"
						:adjustPosition="false" border="none" :showWordLimit="true" v-model="userInfo.age" inputAlign="right"></up-input>
				</view>
			</view>
			<view class="personal-list">
				<view class="flex-center-between border-bottom personal-info-item">
					<text class="label_width">个人简介</text>
					<up-input class="title-input" placeholder="请输入个人简介" fontSize="28rpx" type="text" confirmType="完成" maxlength="50"
						:adjustPosition="false" border="none" :showWordLimit="true" v-model="userInfo.mark" inputAlign="right"></up-input>
				</view>
				<!-- <view class="flex-center-between border-bottom personal-info-item" @tap.stop="setPayword">
					<text class="label_width">支付密码</text>
					<text>* * * * * *</text>
				</view> -->
			</view>
			
			
		</view>
		<view class="footer">
			<view @click="submitFn" class="submit-btn">提交</view>
		</view>

		<up-picker @confirm="changeSex" @cancel="pickerSexShow = false" :show="pickerSexShow" :columns="[
        [
          { label: '男', id: 1 },
          { label: '女', id: 2 },
          { label: '保密', id: 3 },
        ],
      ]" keyName="label" valueName="id"></up-picker>
		
		<!-- 页面内 容结束 -->
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		nextTick
	} from "vue";
	import {
		useImageUpload
	} from "@/hooks/useImageUpload";
	import {
		useAppStore
	} from "@/stores/app";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		useToast
	} from "@/hooks/useToast";
	import {
		getUserInfo,
		userEdit,
		registerpayPasswordAPI
	} from "@/api/user";
	import {
		getCity
	} from "@/api/api.js";
	import Cache from "@/utils/cache";
	import {
		telEncrypt
	} from "@/utils/util.js";
	const paypopRef = ref(null);
	const {
		Toast
	} = useToast();
	const {
		imageList,
		afterRead,
		deletePic,
		uploadLoading
	} = useImageUpload({
		pid: 5,
		model: "book",
	});
	const appStore = useAppStore();
	const userInfo = ref({
		avatar: "",
		nickname: "",
		addres: "",
		mark: "",
		sex: "",
		age: "",
	});
	const pickerSexShow = ref(false);
	const sexText = computed(() => {
		return userInfo.value.sex == 1 ?
			"男" :
			userInfo.value.sex == 2 ?
			"女" :
			userInfo.value.sex == 3 ?
			"保密" :
			"未知";
	});

	//省市区选择
	const district = ref([]);
	const multiArray = ref([
		[],
		[],
		[]
	]);
	const multiIndex = ref([0, 0, 0]);
	const region = ref(["省", "市", "区"]);
	const valueRegion = ref([0, 0, 0]);

	onLoad(() => {
		fetchUserInfo();
		getCityList();
	});

	const changeSex = (e) => {
		userInfo.value.sex = e.value[0].id;
		pickerSexShow.value = false;
	};
	// 设置支付密码
	const setPayword = () => {
		nextTick(() => {
			paypopRef.value.Open();
		});
	};
	const handlerPwd = async (e) => {
		const res = await registerpayPasswordAPI({
			account: appStore.userInfo.phone,
			payPassword: e,
		});
		uni.showToast({
			title: "修改成功",
			duration: 2000,
		});
	};
	// 获取用户头像
	async function getImage() {
		if (imageList.value.length > 0) {
			if (imageList.value[0].status == "success") {
				userInfo.value.avatar = imageList.value[0].info.url;
			} else {
				Toast({
					title: "上传失败"
				});
			}
		}
		imageList.value = [];
	}

	function submitFn() {
		change();
	}

	const change = async () => {
		await userEdit(userInfo.value);
		Toast({
			title: "修改成功",
			endtime: 1500
		});
		appStore.USERINFO();
		setTimeout(() => {
			uni.navigateBack();
		}, 1600);
	};
	// 获取用户信息
	async function fetchUserInfo() {
		try {
			const {
				data
			} = await getUserInfo(appStore.uid);
			userInfo.value = data;
			userInfo.value.addres = userInfo.value.addres || "";
			const list = userInfo.value.addres.split("-");
			if (list.length > 0) {
				region.value = [list[0], list[1], list[2]];
			}
		} catch (error) {
			console.error("otherUserinfo", error);
			Toast({
				title: "获取用户信息失败"
			});
		}
	}

	function bindRegionChange(e) {
		const mi = multiIndex.value;
		const province = district.value[mi[0]] || {
			child: []
		};
		const ma = multiArray.value;
		const value = e.detail.value;
		region.value = [ma[0][value[0]], ma[1][value[1]], ma[2][value[2]]];
		userInfo.value.addres = region.value.join("-");
		valueRegion.value = [0, 0, 0];
		//   change();
		initialize();
	}

	function getCityList() {
		getCity().then((res) => {
			district.value = res.data;
			let oneDay = 24 * 3600 * 1000;
			Cache.setItem({
				name: "cityList",
				value: res.data,
				expires: oneDay * 7
			}); //设置七天过期时间
			initialize();
		});
	}

	function initialize() {
		if (district.value.length) {
			let province = [],
				city = [],
				area = [];
			let cityChildren = district.value[0].child || [];
			let areaChildren = cityChildren.length ? cityChildren[0].child || [] : [];
			district.value.forEach((item) => province.push(item.name));
			cityChildren.forEach((item) => city.push(item.name));
			areaChildren.forEach((item) => area.push(item.name));
			multiArray.value = [province, city, area];
		}
	}

	function bindMultiPickerColumnChange(e) {
		const column = e.detail.column;
		const value = e.detail.value;
		const ma = multiArray.value;
		const mi = multiIndex.value;
		mi[column] = value;
		switch (column) {
			case 0:
				const currentCity = district.value[value] || {
					child: []
				};
				const areaList = currentCity.child[0] || {
					child: []
				};
				ma[1] = currentCity.child.map((item) => item.name);
				ma[2] = areaList.child.map((item) => item.name);
				break;
			case 1:
				const cityList = district.value[mi[0]].child[mi[1]].child || [];
				ma[2] = cityList.map((item) => item.name);
				break;
			case 2:
				break;
		}
		multiArray.value = [...ma];
		multiIndex.value = [...mi];
	}
</script>
<style>
	page {
		background: #F9F7F0;
	}
</style>
<style lang="scss" scoped>
	page{
		height: 100%;
	}

	.personal-info {
		.personal-info-box {
			padding: 0 16rpx;

			.upload {
				padding: 16rpx 0;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.upload-box {
				width: 145rpx;
				height: 145rpx;
				border-radius: 50%;
				border: 1rpx solid #CCCCCC;
			}
		}

		.upload-block {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.upload-block-edit {
				bottom: 0;
				right: 12rpx;
				position: absolute;
				width: 40rpx;
				height: 40rpx;
				background: #F8C008;
				border-radius: 20rpx;
				image {
					width: 24rpx;
					height: 24rpx;
				}
			}
		}
		.personal-list {
			margin-bottom: 16rpx;
			padding: 0 16rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			&:last-child {
				margin-bottom: 0;
			}
		}

		.personal-info-item {
			min-height: 100rpx;
			border-bottom: 1rpx solid #F1F3F8; 
			&:last-child {
				border-bottom: none;
			}

			.label_width {
				width: 200rpx;
				display: inline-block;
			}
		}
	}
	.footer {
		width: 100%;
		bottom: 0;
		position: fixed;
		padding: 22rpx 32rpx 56rpx;
		background: #FFFFFF;
		.submit-btn {
			font-weight: bold;
			font-size: 32rpx;
			text-align: center;
			line-height: 88rpx;
			background: #F8C008;
			border-radius: 16rpx;
		}
	}
</style>