<template>
	<view class="page bg-fff">
		<view class="size-22 color-ffb flex-rowl tip">
			<image class="icon" :src="configList.my_information_statement.paramValueImage"></image>
			<view>
				<up-parse :content="configList.my_information_statement.paramValueArea" containerStyle="{
          color: '#FFBF60',
          fontSize: '22rpx',
          lineHeight: '40rpx',
        }"></up-parse>
			</view>
		</view>
		<view class="info">
			<view class="title mt24">
				基本资料
			</view>
			<view class="flex-colc">
				<button class="btn-avatar" :plain="true" :hairline="false" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<view class="flex-colc">
						<image class="head" :src="form.headImage" mode="aspectFill"></image>
						<!-- <image class="head" :src="form.headImage" mode="widthFix"></image> -->
						<text class="size-28 color-999 mt10">点击更换头像</text>
					</view>
				</button>
			</view>
			<view class="form">
				<up-form label-position="left" :model="baseFormData" :rules="baseRules" ref="baseFormRef" labelWidth="200rpx">
                    <up-form-item label="昵称" prop="userName">
                        <up-input inputAlign="right" v-model="baseFormData.userName" placeholder="请输入" border="none" fontSize="28rpx"></up-input>
                    </up-form-item>
                    <up-form-item label="手机号" prop="userTelephone">
                        <up-input inputAlign="right" v-model="baseFormData.userTelephone" placeholder="请输入" border="none" fontSize="28rpx"></up-input>
                    </up-form-item>
                    <up-form-item label="性别" prop="sex">
                        <view class="flex-rowr" @click="openSexSelectPopup">
                            <text>{{ baseFormData.sex || '请选择' }}</text>
                            <up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
                        </view>
                    </up-form-item>
                </up-form>
			</view>
		</view>

		<view class="info">
			<view class="title mt24 flex-rowl">
				展示信息
				<text class="size-22 color-ffb fw700">(重要)</text>
			</view>
			<view class="form">
                <up-form label-position="left" :model="formData" :rules="rules" ref="dFormRef" labelWidth="200rpx">
                    <up-form-item label="个人简介" prop="userBrief">
                        <up-input v-model="formData.userBrief" 
                        placeholder="请输入个人简介" border="none" 
                        inputAlign="right"
                        fontSize="28rpx">
                        </up-input>
                    </up-form-item>
                    <up-form-item label="养宠经验" prop="experience">
                        <up-input inputAlign="right" v-model="formData.experience" placeholder="请输入养宠经验" 
                        border="none" fontSize="28rpx">
                            <template #suffix>
                                年
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item label="服务记录" prop="serviceRecord">
                        <view class="flex-rowr" @click="jumpToServeRecord">
                            <text>{{ `${serviceCount}条` }}</text>
                            <up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
                        </view>
                    </up-form-item>
                </up-form>
			</view>
		</view>

		<view class="info">
			<view class="title mt24 flex-rowl">
				服务资料
			</view>
			<view class="form">
				<up-form label-position="left" :model="serveFormData" ref="serveFormRef" labelWidth="200rpx">
					<up-form-item label="服务宠物类型" prop="type">
						<view class="flex-rowr" @click="openTypeSelectPopup">
							<text>{{ typeDesc }}</text>
							<up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
						</view>
					</up-form-item>
					<up-form-item label="增值服务" prop="serve">
						<view class="flex-rowr" @click="openServeSelectPopup">
							<text>{{ serveDesc }}</text>
							<up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
						</view>
					</up-form-item>
				</up-form>
			</view>
		</view>

		<view class="size-24 color-ffb flex-rowc mt32 pb28">
			伴宠师查看服务酬劳、服务时长等规则
		</view>

		<popupTypeSelect ref="popupTypeSelectRef" v-model="form.type" @confirm="fetchUpdate" ></popupTypeSelect>

		<popupServeSelect ref="popupServeSelectRef" v-model="serveFormData.serve" @confirm="fetchUpdate" ></popupServeSelect>

		<popupSexSelect ref="popupSexSelectRef" v-model="baseFormData.sex" @confirm="fetchUpdate" ></popupSexSelect>

		<view class="uni-btn-color"
		@click="submit">
			保存
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, nextTick } from "vue";
	import { useStore } from 'vuex'
	import { onShow } from '@dcloudio/uni-app'
	import { ossUpload } from '@/utils/oss-upload/oss/index.js'

	import popupTypeSelect from "./popupTypeSelect.vue";
	import popupServeSelect from "./popupServeSelect.vue";
	import popupSexSelect from "./popupSexSelect.vue";
	import { serviceLogList } from '@/api/serviceLog'
	import {
		binBaseInfo,
	} from "@/api/home.js"
	import { getUserOne, udpateUser } from '@/api/userTeacher'
	import { updateUserInfo } from '@/api/user/user'

	const store = useStore()

	const configList = computed(() => {
		return store.getters.configList
	})
	const userInfo = computed(() => {
		return store.getters.userInfo
	})

	const serviceCount = ref(0)

	const baseFormData = reactive({
		userName: '',
		userTelephone: '',
		sex: ''
	})

	const baseRules = {
		userName: {
			type: 'string',
			required: true,
			message: '请输入昵称',
			trigger: ['blur', 'change']
		},
		userTelephone: {
			type: 'string',
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change']
		},
		sex: {
			type: 'string',
			required: true,
			message: '请选择性别',
			trigger: ['blur', 'change']
		}
	}

	const baseFormRef = ref(null)

	const formData = reactive({
		introduction: '',
		experience: '',
		serviceRecord: '',
		userBrief : '',
	})

	const rules = {
		introduction: {
			type: 'string',
			required: true,
			message: '请输入个人简介',
			trigger: ['blur', 'change']
		},
		experience: {
			type: 'string',
			required: true,
			message: '请输入养宠经验',
			trigger: ['blur', 'change']
		}
	}

	const dFormRef = ref(null)

	const form = reactive({
		headImage: null,
		type: [],
        id : 0,
	})

	const serveFormData = reactive({
		serve: []
	})

	const serveFormRef = ref(null)

	const fetchUserInfo = async () => {
		try {
			const data = await getUserOne(userInfo.value.userId)
			
			if (data) {
				// 设置基本资料
				baseFormData.userName = userInfo.value.userName || ''
				baseFormData.userTelephone = data.phone || userInfo.value.userTelephone || ''
				baseFormData.sex = data.sex == 0 ? '男' : '女'
				
				// 设置展示信息
				formData.userBrief = data.userBrief || ''
				formData.experience = data.experience || ''
                
				form.headImage = userInfo.value.userImage || ''
				form.id = data.id || 0
				
				// 设置服务资料
				if (data.petType) {
					form.type = data.petType.split ? data.petType.split(',').map(n => parseInt(n)) : [parseInt(data.petType)]
				}
				
				// 设置增值服务
				if (data.license) {
					serveFormData.serve = data.license.split(';').map(item => parseInt(item))
				}
			}
		} catch (err) {
			console.log('--err', err)
		}
	}

	const fetchUpdate = () => {
		// 表单数据已更新，无需额外处理
	}

	const onChooseAvatar = (res) => {
		ossUpload(res.target.avatarUrl)
		.then(url => {
			form.headImage = url

			fetchUpdate()
		})
	}

	const jumpToServeRecord = () => {
		uni.navigateTo({
			url: "/otherPages/authentication/serve/record"
		})
	}

	const popupTypeSelectRef = ref()
	const openTypeSelectPopup = () => {
		popupTypeSelectRef.value.open()
	}
	
	const popupSexSelectRef = ref()
	const openSexSelectPopup = () => {
		popupSexSelectRef.value.open()
	}
	const petTypeOptions = computed(() => {
		return store.getters.petTypeOptions
	})
	const typeDesc = computed(() => {
		const typeIds = form.type
		if (!typeIds.length) {
			return '请选择'
		}
		

		let descArr = typeIds.map(typeId => {
            let t = petTypeOptions.value.find(item => item.id === typeId)
			return t && t.title
		})

		return descArr.join('、')
	})

	const popupServeSelectRef = ref()
	const increaseServiceOptions = computed(() => {
		return store.getters.increaseServiceOptions
	})
	const openServeSelectPopup = () => {
		popupServeSelectRef.value.open()
	}
	const serveDesc = computed(() => {
		const serveIds = serveFormData.serve
		if (!serveIds.length) {
			return '请选择'
		}
		
		let descArr = serveIds.map(serveId => {
			return increaseServiceOptions.value.find(option => option.id == serveId)?.title
		})

		return descArr.join('、')
	})
	
	function getCountSerivce(){
		serviceLogList({ userId: userInfo.value.userId })
		.then(res => {
			serviceCount.value = res.length
		})
	}
	const getBaseInfo = () => {
		binBaseInfo(userInfo.value.userId).then(res => {
			baseInfo.value = res.data
			uni.setStorageSync(JSON.stringify(res.data))
		})
	}
	
	function submit(){
		// 先验证基本资料表单
		baseFormRef.value.validate().then(() => {
			// 再验证展示信息表单
			return dFormRef.value.validate()
		}).then(res => {
			const submitData = {
                id : form.id,
				phone: baseFormData.userTelephone,
				sex: baseFormData.sex == '男' ? 0 : 1,
				brief: formData.userBrief,
				experience: formData.experience,
				petType: form.type.length > 0 ? form.type.join(',') : null,
				license: serveFormData.serve.join(';'),
			}
			
			if (form.headImage) {
                updateUserInfo({
                    userImage : form.headImage,
                    userName: baseFormData.userName,
                    id : userInfo.value.id,
                    userId : userInfo.value.userId,
                }).then(() => {
                    store.dispatch('getUserInfo')
                })
			}
			
			udpateUser(submitData).then(() => {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
                setTimeout(uni.navigateBack, 1000, -1)
			}).catch(err => {
				console.error(err)
				uni.showToast({
					title: '保存失败',
					icon: 'error'
				})
			})
		}).catch(err => {
			console.log('表单验证失败', err)
		})
	}

	onShow(() => {
		getCountSerivce()
		fetchUserInfo()
		store.dispatch('fetchPetTypeOptions')
		store.dispatch('fetchIncreaseServiceOptions')
	})

	onMounted(()=> {
	})

</script>

<style lang="scss" scoped>
	
	.page {
		padding-top: 16rpx;
		padding-bottom: 150rpx;

		.tip {
			background-color: rgba($color: #FFBF60, $alpha: 0.16);
			padding: 13rpx 22rpx;
			margin: 0 28rpx 37rpx 28rpx;

			.icon {
				width: 36rpx;
				height: 36rpx;
				margin-right: 15rpx;
			}
		}
	}

	.info {

		& + & {
			margin-top: 50rpx;
		}

	}
	
	.head {
		width: 165rpx;
        height: 165rpx;	
		margin-top: 28rpx;
	}

	.btn-avatar {
		border: none;
		padding: 0;
        .head{
            width: 140rpx;
            height: 140rpx;
            border-radius: 50%;
        }
	}

	.title {
		font-size: 30rpx;
		font-weight: 700;
		display: flex;
		align-items: center;
		padding: 0 40rpx;

		&:before {
			display: inline-block;
			content: "";
			width: 10rpx;
			border-radius: 5rpx;
			height: 33rpx;
			background-color: #FFBF60;
			margin-right: 7rpx;
		}
	}

	.form {
		padding: 0 38rpx;

		:deep(.form-item){
			padding-left: 24rpx;
			padding-right: 30rpx;
			box-sizing: border-box;
		}
		.form-item {
			min-height: 90rpx;
			padding-top: 10rpx;
			width: 100%;
			border-bottom: 1rpx solid #f5f5f5;
		}

		.flex-rowr {
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}

		.ml10 {
			margin-left: 10rpx;
		}
	}
	
	.uni-btn-color{
		border-radius: 40rpx;
		padding: 20rpx;
		margin: 40rpx;
		background: #FFBF60;
		color: #fff;
		text-align: center;
		font-size: 28rpx;
	}
</style>