<template>
	<view class="container">
		<wd-form ref="form" :model="formValue">
			<wd-cell-group border>
				<wd-input
					v-model="formValue.username"
					label="中文姓名"
					label-width="100px"
					prop="username"
					clearable
					placeholder="请输入姓名"
					:rules="[{ required: false, validator: validatorName, message: '请输入姓名' }]"
				/>
				<wd-input
					v-model="formValue.sfzh"
					label="身份证"
					label-width="100px"
					prop="sfzh"
					clearable
					placeholder="请输入身份证件号码"
					:rules="[
						{
							required: false,
							validator: validatorNum,
							message: '请输入身份证件号码'
						}
					]"
				/>
				<wd-input
					v-model="formValue.mobile"
					label="手机号"
					label-width="100px"
					prop="mobile"
					clearable
					placeholder="请输入手机号码"
					:rules="[
						{
							required: false,
							validator: validatorPhone,
							message: '请输入手机号码'
						}
					]"
				/>
				<wd-input
					v-model="formValue.cardNumber"
					label="学号"
					label-width="100px"
					prop="mobile"
					class="custom-input" 
					clearable 
					placeholder=""
				/>
				<!-- 模拟右侧占位符的文本 -->
				<text class="placeholder-text" v-if="!formValue.cardNumber">（填学号，便于发放校补）</text>
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" block @click="handleSubmit">保存</wd-button>
			</view>
		</wd-form>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { myRequest } from '@/utils/api.ts'

console.log(uni.getStorageSync('carUserInfo').id,'新增')
// 表格绑定数据
const formValue = ref({
	uid: uni.getStorageSync('carUserInfo').id ,
	username: '',
	sfzh: '',
	mobile: '',
	cardNumber:''
})

// 表格DOM
const form = ref(null)

onLoad((options) => {
	if (options.info) {
		uni.setNavigationBarTitle({
			title: '修改乘客信息'
		})
		formValue.value = JSON.parse(decodeURIComponent(options.info))
	} else {
		uni.setNavigationBarTitle({
			title: '添加乘客信息'
		})
	}
})

// 保存按钮回调
function handleSubmit() {
	form.value
		.validate()
		.then(({ valid, errors }) => {
			if (valid) {
				if (formValue.value.id) {
					// 修改请求
					submitEditReq()
				} else {
					// 新增请求
					submitAddReq()
				}
			}
		})
		.catch((error) => {
			console.log(error, 'error')
		})
}

// 新增请求
const submitAddReq = async () => {
	const res = await myRequest({
		url: '/ctUserinsert.action',   
		method: 'post', 
		data: formValue.value,
	})
	// console.log(res)
	if (res.code == 200) {
		uni.showToast({
			title: res.message,
			icon: 'success'
		})
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/commonPeople/commonPeople'
			})
		}, 1500)
	}
}

// 修改请求
const submitEditReq = async () => {
	const res = await myRequest({
		url: '/ctUserupdate.action',
		method: 'post',
		data: formValue.value
	})
	// console.log(res)
	if (res.code == 200) {
		uni.showToast({
			title: res.message,
			icon: 'success'
		})
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/commonPeople/commonPeople'
			})
		}, 1500)
	}
}

// 姓名验证规则
const validatorName = (val) => {
	const result = val.replace(/\s+/g, '')
	if (result) {
		if (result.length > 1 && result.length < 5) {
			return Promise.resolve()
		} else {
			return Promise.reject('姓名为2-4个字符')
		}
	}
}

// 身份证号码验证规则
const validatorNum = (val) => {
	if (val) {
		// 去除空格
		const cleanedId = val.replace(/\s+/g, '')

		// 基本格式校验：18位，前17位数字，最后一位可以是数字或X
		const idReg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
		if (!idReg.test(cleanedId)) {
			return Promise.reject('请输入有效的18位身份证号码')
		}

		// 校验码验证
		// 加权因子
		const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
		// 校验码对应值
		const parityBits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

		let sum = 0
		const code = cleanedId.toUpperCase() // 转为大写

		// 计算前17位与对应因子乘积的和
		for (let i = 0; i < 17; i++) {
			sum += parseInt(code.charAt(i)) * factors[i]
		}

		// 计算校验码
		const checkCode = parityBits[sum % 11]

		// 验证校验码
		if (code.charAt(17) !== checkCode) {
			return Promise.reject('身份证号码校验无效')
		}

		// 验证出生日期
		const year = parseInt(code.substr(6, 4))
		const month = parseInt(code.substr(10, 2))
		const day = parseInt(code.substr(12, 2))
		const birthDate = new Date(year, month - 1, day)

		if (birthDate.getFullYear() !== year || birthDate.getMonth() + 1 !== month || birthDate.getDate() !== day) {
			return Promise.reject('身份证号码中的出生日期无效')
		}

		return Promise.resolve()
	}
}

// 时间号码验证规则
const validatorPhone = (val) => {
	const phoneReg = /^1[3-9]\d{9}$/
	if (val) {
		if (phoneReg.test(val)) {
			return Promise.resolve()
		} else {
			return Promise.reject('手机号码格式错误')
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	box-sizing: border-box;
	padding: 20rpx 0;
	height: 100vh;
	background-color: #fff;
	
	.custom-input {
	  width: 100%;
	  height: 80rpx;
	  line-height: 80rpx;
	  padding-right: 200rpx; /* 给右侧占位文本留空间 */
	  border: 1px solid #eee;
	  border-radius: 8rpx;
	  font-size: 28rpx;
	}
	
	.placeholder-text {
	  position: absolute; /* 绝对定位到输入框右侧 */
	  right: 30rpx;
	  top: 31%;
	  font-size: 26rpx;
	  color: #999; /* 模拟原生placeholder颜色 */
	  pointer-events: none; /* 避免遮挡输入框点击 */
	}

	.footer {
		position: absolute;
		left: 40rpx;
		right: 40rpx;
		bottom: 100rpx;

		:deep(.wd-button) {
			background-color: #ff8205;
		}
	}
}
</style>
