<template>
	<view class="bg-white px-34rpx">
		<view class="h-full pb-160rpx">
			<u--form
				labelPosition="left"
				:model="model"
				:rules="rules"
				ref="formRef"
				borderBottom
				errorType="toast"
				labelWidth="auto"
			>
				<u-form-item
					v-for="item in formList"
					:key="item.key"
					:required="item.required"
					:label="item.label"
					:prop="item.key"
				>
					<u--input
						v-if="item.type === 'string'"
						:type="item.key === 'age' ? 'number' : 'text'"
						v-model="model[item.key]"
						border="none"
						inputAlign="right"
						maxlength="300"
						:placeholder="item.placeholder"
						:readonly="model.status === 0"
					/>
					<view class="w-full" v-else-if="item.type === 'radio'">
						<u-radio-group
							class="!justify-end"
							v-model="model[item.key]"
							activeColor="#FF8CA6"
							shape="square"
							placement="row"
							:disabled="model.status === 0"
						>
							<u-radio name="0" label="男"></u-radio>
							<u-radio name="1" label="女" class="ml-50rpx"></u-radio>
						</u-radio-group>
					</view>
					<view v-else class="w-full text-right u-line-1 pl-2 text-#C0C4CC"
						>{{ item.placeholder }}
					</view>
				</u-form-item>
			</u--form>
			<u--textarea
				count
				v-model="model.intro"
				placeholder=""
				maxlength="300"
				:autoHeight="false"
				:disabled="model.status === 0"
			/>
			<view class="mt-32rpx mb-20rpx text-28rpx">
				<view class=""
					>上传身份证
					<text
						class="u-form-item__body__left__content__required text-#f56c6c ml-[-4rpx]"
						>*</text
					>
				</view>
				<view class="flex justify-between mb-32rpx mt-20rpx">
					<view
						@click="handleChooseImage('ren')"
						class="relative w-330rpx h-250rpx bg-#f2f2f2 rounded-md px-52rpx pt-30rpx pb-20rpx"
					>
						<block v-if="!imageObj.ren">
							<image class="w-full h-146rpx" :src="$assets('/zheng.png')" />
							<view class="text-24rpx mt-10rpx text-#999 w-full text-center"
								>上传身份证人像面</view
							>
						</block>
						<view
							v-else
							class="absolute top-0 left-0 right-0 bottom-0 rounded-md overflow-hidden"
						>
							<u--image
								mode="aspectFit"
								width="330rpx"
								height="250rpx"
								:duration="100"
								:src="imageObj.ren"
							/>
						</view>
					</view>
					<view
						@click="handleChooseImage('fan')"
						class="relative w-330rpx bg-#f2f2f2 rounded-md px-52rpx pt-30rpx pb-20rpx"
					>
						<block v-if="!imageObj.fan">
							<image class="w-full h-146rpx" :src="$assets('/fan.png')" />
							<view class="text-24rpx mt-10rpx text-#999 w-full text-center"
								>上传身份证国徽面</view
							>
						</block>
						<view
							v-else
							class="absolute top-0 left-0 rounded-md overflow-hidden"
						>
							<u--image
								mode="aspectFit"
								width="330rpx"
								height="250rpx"
								:duration="100"
								:src="imageObj.fan"
							/>
						</view>
					</view>
				</view>
				<text class="text-24rpx text-#999"
					>备注：申请表提交后会有工作人员主动联系您，请耐心等待</text
				>
				<agreed-comp v-model:agreed="agreed" :disabled="model.status === 0" />
			</view>

			<view
				class="fixed bg-#fff bottom-0 pb-8 left-0 right-0 text-white pt-12rpx border-t-1px border-solid border-#E5E5E5"
				><view
					@click="$u.throttle(handleSubmit, 1000)"
					class="rounded-24rpx w-660rpx h-80rpx text-center leading-80rpx hover:shadow-md mx-auto"
					:class="model.status === 0 ? 'bg-#ccc' : 'bg-#FF8CA6'"
					>{{ model.status === 0 ? '申请中' : '提交申请' }}</view
				></view
			>
		</view>
	</view>
</template>

<script setup>
import { chooseImage } from '@uni-helper/uni-promises'
import { onShow } from '@dcloudio/uni-app'

const instance = getCurrentInstance()
const { $api, $toast, $store, $u, $dialog, $Router, $loading } = instance.proxy
const userInfo = computed(() => $store.user.userInfo)
const isLogin = computed(() => !!$store.user.token)
const agreed = ref(false)
const formRef = ref(null)
const formList = ref([])
const model = ref({})
const rules = ref({})
const imageObj = ref({})
// 姓名 性别 年龄 手机号 微信号 个人介绍 常驻地点 上传身份证
const formItems = [
	{
		label: '姓名',
		placeholder: '请输入姓名',
		key: 'name',
		keyName: 'nickName',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请填写姓名'
	},
	{
		label: '性别',
		placeholder: '请选择性别',
		key: 'sex',
		keyName: 'gender',
		required: true,
		type: 'radio',
		trigger: ['blur', 'change'],
		message: '请选择性别',
		validator: {
			validator: (rule, value, callback) => {
				return value > -1
			},
			message: '请选择性别',
			trigger: ['change', 'blur']
		}
	},
	{
		label: '年龄',
		placeholder: '请输入年龄',
		key: 'age',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请输入年龄',
		validator: {
			validator: (rule, value, callback) => $u.test.digits(value),
			message: '年龄必须为数字',
			trigger: 'blur'
		}
	},
	{
		label: '手机号',
		placeholder: '请输入手机号',
		key: 'phone',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请输入手机号',
		validator: {
			validator: (rule, value, callback) => {
				return $u.test.mobile(value)
			},
			message: '手机号码格式有误',
			trigger: 'blur'
		}
	},
	// {
	// 	label: '微信号',
	// 	placeholder: '请输入微信号',
	// 	key: 'wxNumber',
	// 	required: true,
	// 	type: 'string',
	// 	trigger: ['blur', 'change'],
	// 	message: '请输入微信号'
	// },
	{
		label: '常驻地点',
		placeholder: '请输入常驻地点',
		key: 'address',
		type: 'string',
		required: true,
		trigger: ['blur', 'change'],
		message: '请填写常驻地点'
	},
	{
		label: '个人介绍',
		placeholder: '如可服务时间、可服务范围',
		key: 'intro',
		type: 'textarea',
		required: true,
		trigger: ['blur', 'change'],
		message: '请填写个人介绍'
	}
	// {
	// 	label: '上传身份证',
	// 	placeholder: '',
	// 	key: 'idCard',
	// 	type: 'string',
	// 	required: true,
	// 	trigger: ['blur', 'change'],
	// 	message: '请上传身份证'
	// }
]
onMounted(() => {
	formRef.value.setRules(rules.value)
})

const init = async () => {
	$loading(true)
	formItems.forEach((item) => {
		const { required, key, keyName, message, trigger, validator } = item
		rules.value[item.key] =
			typeof validator === 'object'
				? [{ required, message, trigger }, validator]
				: [{ required, message, trigger }]
		formList.value.push(item)
		model.value[key] = userInfo.value[keyName || key] ?? null
	})
	model.value.sex = +userInfo.value.gender
	model.value.intro = model.value.intro ?? ''
	const res = await $api.doctorInfo()
	if (res.success && typeof res.doctor === 'object' && res.doctor) {
		Object.assign(model.value, res.doctor)
		const images = res.doctor.images.split(',')
		imageObj.value.ren = images[0]
		imageObj.value.fan = images[1]
		agreed.value = true
	}
	$loading(false)
}

const handleChooseImage = async (key) => {
	if (model.value.status === 0) return
	let filePath = ''
	try {
		const ret = await chooseImage({
			count: 1
		})
		filePath = ret.tempFilePaths[0]
	} catch (error) {
		return
	}
	if (!filePath) {
		return
	}
	const res = await $api.uploadFile({
		name: 'file',
		filePath
	})
	if (res.success) {
		imageObj.value[key] = res.msg
	}
}

const handleSubmit = async () => {
	formRef.value?.validate().then(async () => {
		if (!imageObj.value.ren) {
			$toast('请上传身份证人像面!')
		} else if (!imageObj.value.fan) {
			$toast('请上传身份证国徽面!')
		} else {
			if (!agreed.value) {
				try {
					await $dialog('是否已阅读并同意《服务条款》?', {
						showCancelButton: true,
						confirmButtonText: '同意',
						cancelButtonText: '取消',
						confirmColor: '#FF8CA6'
					})

					agreed.value = true
				} catch (error) {
					return
				}
			}
			$loading(true)
			const images = []
			Object.entries(imageObj.value).forEach(([key, value]) => {
				images.push(value)
			})
			model.value.images = images.join(',')
			const res = await $api.doctorSave({
				...model.value
			})
			if (res.success) {
				$toast('提交成功')
				setTimeout(() => {
					$Router.push({
						path: '/personal'
					})
				}, 500)
			}
			$loading(false)
		}
	})
}

onShow(() => {
	if (!isLogin.value) {
		$dialog('请先登录', {
			showCancelButton: true,
			confirmButtonText: '去登录',
			cancelButtonText: '取消',
			confirmColor: '#FF8CA6'
		})
			.then(() => {
				$Router.push('/personal')
			})
			.catch(() => '')
		return
	}
})
init()
</script>

<style lang="scss" scoped>
:deep {
	.u-form-item__body {
		border-bottom: 2rpx solid #f2f2f2;
		padding: 32rpx 0 !important;
	}
	.u-form-item__body__left__content__required {
		// margin-left: 6rpx;
		font-size: 24rpx !important;
		top: 0rpx !important;
		right: -6rpx !important;
		left: auto !important;
	}
	.u-popup__content {
		border-radius: 16rpx 16rpx 0 0;
	}
	.u-textarea,
	.u-textarea__count {
		background-color: #f2f2f2 !important;
	}
	.u-popup__content {
		overflow: hidden;
	}
	.u-upload__button {
		width: 100% !important;
		height: 100% !important;
		background-color: transparent;
	}
	.u-radio-group {
		width: 230rpx;
		margin-left: auto;
		justify-content: space-between;
	}
}
</style>
