<template>
	<view class="user padding30">
		
		<view class="padding30 bg_color_fff border_radius_20">
			<u-form labelPosition="left" :model="userInfo" :rules="rules" ref="formRef" labelWidth="auto">
				
				<u-form-item label="头像" prop="avatar" :borderBottom="true" required>
					<view class="avatar flex-center-flex-end">
						<button class="chooseAvatar" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
									<u-avatar 
									size="120rpx"
									shape="circle"
									:src="userInfo.avatar"
									mode="aspectFill"
								></u-avatar>
						</button>
					</view>
						
				</u-form-item>
				<u-form-item label="昵称" prop="nickName" :borderBottom="true" required>
					<u-input v-model="userInfo.nickName" placeholder="请输入昵称" border="none" clearable inputAlign="right" type="nickname"></u-input>
				</u-form-item>
				<u-form-item label="手机号" :borderBottom="false" required>
					<u-input v-model="userInfo.userPhone" placeholder="账号" border="none" clearable inputAlign="right" readonly></u-input>
				</u-form-item>
			</u-form>
		</view>
		<view class="foot bg_color_fff">
			<view class="order_btn paddingTB20 flex_1 text_align_center" @click="submitForm">提交</view>
		</view>
	</view>
</template>
<script setup>
import { ref,reactive } from 'vue'
import { userEdit } from "@/api/user.js";
import { telEncrypt,chooseImageOne,uploadFile } from "@/utils/util.js";
import { useToast } from "@/hooks/useToast";
const { Toast } = useToast();
import { useAppStore } from "@/stores/app";
const appStore = useAppStore();

const formRef = ref(null);
const dgtPopupRef = ref(null);
const userInfo = ref({
  userPhone: telEncrypt(appStore.userInfo?.userPhone),
  nickName: appStore.userInfo?.nickName,
  avatar: appStore.userInfo?.avatar,
});
const rules = reactive({
  "avatar": [
    { required: true, message: '请上传头像', trigger: ['blur', 'change'] },
  ],
  "nickName": [
    { required: true, message: '请输入昵称', trigger: ['blur', 'change'] },
  ]
});
// 提交表单
async function submitForm(){
  formRef.value
	.validate()
	.then((valid) => {
		console.log('submitForm',valid);
		if (valid) {
			userEdit(userInfo.value).then(async res=>{ 
				await appStore.USERINFO();
				uni.navigateBack();
			})
		} else {
			Toast({ title: "请完善个人资料" });
		}
	})
	.catch((e) => {
		console.log('error submit!!',e[0].message);
		Toast({ title: e[0]?.message || "请完善个人资料!" });
	});
};

async function uploadImage(){
  const res = await chooseImageOne('user/userAvatarUpload');
  console.log('uploadImage',res);
  if(res){
  	userInfo.value.avatar= res.data
  }
}
async function chooseAvatar(e){
	console.log('chooseAvatar',e);
	if(e.detail?.avatarUrl){
		const res = await uploadFile(e.detail?.avatarUrl,'user/userAvatarUpload');
		console.log('uploadImage',res);
		if(res){
			userInfo.value.avatar= res.data
		}
	}
	

}
</script>

<style lang="scss">
.user{ 
	.foot{
		.order_btn{
			border-radius: 50rpx;
		}
	}
	.avatar{
		width: 100%;
	}
}
</style>
