<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="baseInfo.info.userImage" mode="widthFix"></image>
						<!-- <image class="head" :src="form.headImage" mode="widthFix"></image> -->
						<text class="size-28 color-999 mt10">点击更换头像</text>
					</view>
				</button>
			</view>
			<view class="form">
				<!-- @input="fetchUpdate" -->
				<DForm ref="baseInfoRef" :list="state.baseInfoList" v-model="baseInfo.info"></DForm>
			</view>
		</view>

		<view class="info">
			<view class="title mt24 flex-rowl">
				展示信息
				<text class="size-22 color-ffb fw700">(重要)</text>
			</view>
			<view class="form">
				<DForm ref="displayInfoRef" :list="state.displayInfoList" @input="fetchUpdate">
					<!-- 服务记录 -->
					<template v-slot:jilu>
						<view class="flex-rowr" @click="jumpToServeRecord">
							<text>{{ `${serviceCount}条` }}</text>
							<up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
						</view>
					</template>
				</DForm>
			</view>
		</view>

		<view class="info">
			<view class="title mt24 flex-rowl">
				服务资料
			</view>
			<view class="form">
				<DForm ref="serveInfoRef" :list="state.serveInfoList" @input="fetchUpdate">
					<!-- 服务宠物类型 -->
					<template v-slot:type>
						<view class="flex-rowr" @click="openTypeSelectPopup">
							<text>{{ typeDesc }}</text>
							<up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
						</view>
					</template>
					<!-- 增值服务 -->
					<template v-slot:zenz>
						<view class="flex-rowr" @click="openServeSelectPopup">
							<text>{{ serveDesc }}</text>
							<up-icon name="arrow-right" color="#999999" size="32rpx"></up-icon>
						</view>
					</template>
				</DForm>
			</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="form.serve" @confirm="fetchUpdate" ></popupServeSelect>

		<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 DForm from "@/components/dForm/index.vue"
	import popupTypeSelect from "./popupTypeSelect.vue";
	import popupServeSelect from "./popupServeSelect.vue";
	import { serviceLogList } from '@/api/serviceLog'
	import {
		binBaseInfo,
	} from "@/api/home.js"
	import { getUserOne, udpateUser } from '@/api/userTeacher'

	const store = useStore()

	const configList = computed(() => {
		return store.getters.configList
	})
	const userInfo = computed(() => {
		return store.getters.userInfo
	})
	
	const baseInfo = ref(JSON.parse(uni.getStorageSync("baseInfo")))
	
	const serviceCount = ref(0)

	const fetchUserInfo = async () => {
		try {
			const data = await getUserOne(userInfo.value.userId)
			
			if (data) {
				const {
					name,
					sex,
					phone,
					experience,
					petType,
					increaseService
				} = data
				
				// 设置基本信息
				baseInfoRef.value.setData({
					userName: name,
					userTelephone: phone || userInfo.value.userTelephone,
					sex: sex === 0 ? '男' : '女'
				})
				
				// 设置展示信息
				displayInfoRef.value.setData({
					jianjie: data.introduction || '',
					jingyan: experience
				})
				
				// 完整更新form对象
				form.jianjie = data.introduction || ''
				form.jingyan = experience || ''
				
				// 设置服务资料
				if (petType) {
					form.type = [petType]
				}
				
				// 设置增值服务
				if (increaseService && Array.isArray(increaseService)) {
					form.serve = increaseService
				}
				
				// 确保所有表单数据同步
				nextTick(() => {
					// 更新服务资料表单
					if (serveInfoRef.value) {
						serveInfoRef.value.setData({
							type: form.type,
							zenz: form.serve
						})
					}
				})
			}
		} catch (err) {
			console.log('--err', err)
		}
	}

	const fetchUpdate = (data) => {
		if (data) {
			Object.assign(form, data)
			
			// 如果更新了jianjie或jingyan，同步更新到displayInfoRef
			if (data.jianjie !== undefined || data.jingyan !== undefined) {
				const updateData = {}
				if (data.jianjie !== undefined) updateData.jianjie = data.jianjie
				if (data.jingyan !== undefined) updateData.jingyan = data.jingyan
				displayInfoRef.value?.setData(updateData)
			}
		}
	}

	const form = reactive({
		headImage: null,
		type: [],
		serve: [],
		jianjie: '',
		jingyan: ''
	})

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

			fetchUpdate()
		})
	}

	const baseInfoRef = ref(null)
	const displayInfoRef = ref(null)
	const serveInfoRef = ref(null)

	const state = reactive({
		baseInfoList: [{
				type: "input",
				label: "昵称",
				key: "userName",
				placeholder: "请输入",
			},
			{
				type: "input",
				label: "手机号",
				key: "userTelephone",
				placeholder: "请输入",
			},
			{
				type: "select",
				label: "性别",
				key: "sex",
				placeholder: "请选择",
				options: [
					{
						name: "男",
						value : '男',
					},
					{
						name: "女",
						value : '女',
					}
				]
			}
		],
		displayInfoList: [{
				type: "input",
				label: "个人简介",
				key: "jianjie",
				placeholder: "请输入",
			},
			{
				type: "input",
				label: "养宠经验",
				unit: "年",
				key: "jingyan",
				placeholder: "请输入",
			},
			{
				type: "custom",
				label: "服务记录",
				key: "jilu",
				placeholder: "请选择",
				options: [{
						name: "男"
					},
					{
						name: "女"
					}
				]
			}
		],
		serveInfoList: [{
				type: "custom",
				label: "服务宠物类型",
				key: "type",
				placeholder: "请选择",
			},
			{
				type: "input",
				label: "基础服务",
				key: "base",
				placeholder: "宠物喂养上门遛狗",
			},
			{
				type: "custom",
				label: "增值服务",
				key: "zenz",
				placeholder: "请选择",
			}
		],
	})

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

	const popupTypeSelectRef = ref()
	const openTypeSelectPopup = () => {
		popupTypeSelectRef.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 => {
			return petTypeOptions.value.find(item => item.id === typeId).title
		})

		return descArr.join('、')
	})

	const popupServeSelectRef = ref()
	const increaseServiceOptions = computed(() => {
		return store.getters.increaseServiceOptions
	})
	const openServeSelectPopup = () => {
		popupServeSelectRef.value.open()
	}
	const serveDesc = computed(() => {
		const serveIds = form.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(baseInfo.value.userId).then(res => {
			baseInfo.value = res.data
			uni.setStorageSync('baseInfo', JSON.stringify(res.data.info))
			
			// 如果baseInfoRef已经初始化，则设置数据
			if (baseInfoRef.value) {
				baseInfoRef.value.setData(res.data.info)
			}
		})
	}
	
	function submit(){
		const data = {
			userId: userInfo.value.userId,
			name: baseInfo.value.info.userName,
			phone: baseInfo.value.info.userTelephone,
			sex: baseInfo.value.info.sex === '男' ? 0 : 1,
			experience: form.jingyan,
			introduction: form.jianjie,
			petType: form.type.length > 0 ? form.type[0] : undefined,
			increaseService: form.serve.length > 0 ? form.serve : undefined
		}
		
		udpateUser(data).then(() => {
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
		}).catch(err => {
			console.error(err)
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			})
		})
	}

	onMounted(()=> {
		// 先加载基础配置数据
		store.dispatch('fetchPetTypeOptions')
		store.dispatch('fetchIncreaseServiceOptions')
		
		// 设置基础服务文本
		nextTick(() => {
			if (serveInfoRef.value && configList.value.pet_basic_services) {
				serveInfoRef.value.setDataByKey('base', configList.value.pet_basic_services.paramValueText)
			}
		})
	})

	onShow(() => {
		// 获取数据并确保表单初始化后再设置数据
		getBaseInfo()
		getCountSerivce()
		
		// 确保组件已挂载后再获取用户信息
		nextTick(() => {
			fetchUserInfo()
		})
	})

</script>

<style lang="scss" scoped>
	
	.form{
		.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;
		}
	}

	.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: auto;	
		margin-top: 28rpx;
	}

	.btn-avatar {
		border: none;
		padding: 0;
	}

	.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 22rpx;

		:deep(.form-item){
			padding-left: 24rpx;
			padding-right: 30rpx;
			box-sizing: border-box;
		}
	}
	
	.uni-btn-color{
		border-radius: 40rpx;
		padding: 20rpx;
		margin: 40rpx;
		background: #FFBF60;
		color: #fff;
		text-align: center;
		font-size: 28rpx;
	}
</style>