<template>
	<view class="container main">
		<view class="one">
			<view class="register" v-if="!user.id">
				<uni-forms ref="baseForm" :rules="rules" :modelValue="form" label-width="80px">
					<uni-forms-item label="账号" required name="account">
						<uni-easyinput v-model="form.account" placeholder="请输入账号" />
					</uni-forms-item>
					<uni-forms-item label="密码" required name="password">
						<uni-easyinput type="password" v-model="form.password" placeholder="请输入密码" />
					</uni-forms-item>
					<uni-forms-item label="确认密码" required name="ispassword">
						<uni-easyinput type="password" v-model="form.ispassword" placeholder="请输入确认密码" />
					</uni-forms-item>
					<uni-forms-item label="手机号" required name="phone">
						<uni-easyinput v-model="form.phone" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item label="电子邮箱">
						<uni-easyinput v-model="form.email" placeholder="请输入电子邮箱" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="list" v-for="(item, index) in investigate" :key="index">
				<div class="problem">
					<text v-if="item.is_must=='0'" class="t-icon t-icon-xinghao"></text>
					<span v-if="item.is_must=='0'">{{item.problem}}</span>
					<span style="margin: 0 0 0 2vw;" v-else>{{item.problem}}</span>
				</div>
				<div class="type" v-if="item.type =='0'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-data-checkbox v-model="item.reply" :localdata="item.answer"
						:map="{text:'text',value:'text'}" />
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='1'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-data-checkbox v-model="item.reply" multiple :localdata="item.answer"
						:map="{text:'text',value:'text'}" />
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='2'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-data-select v-model="item.reply" :localdata="item.answer"></uni-data-select>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='3'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-easyinput v-model="item.reply" type="number"
						:placeholder="getField(item.problem)"></uni-easyinput>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='4'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-easyinput v-model="item.reply" :placeholder="getField(item.problem)"></uni-easyinput>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='5'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<uni-easyinput type="textarea" v-model="item.reply"
						:placeholder="getField(item.problem)"></uni-easyinput>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='6'">
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
					<upload class='upload' :list="item.reply" name="reply" :count="1" @uplSuc="uplSuc($event,item)"
						@uplDel="uplDel($event,item)">
					</upload>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='7'">
					<div class="list">
						<div v-for="(aa, ina) in item.answer" :key="ina" class="name">{{aa.text}}</div>
					</div>
					<div class="list" v-for="(gg, inx) in item.reply" :key="inx">
						<div v-for="(aa, ina) in item.answer" :key="ina" class="input">
							<uni-easyinput v-model="gg[aa.text]" :clearable="false"
								:placeholder="getField(aa.text)"></uni-easyinput>
						</div>
						<uni-icons @tap="toDel(item,gg.sid)" class="icon" type="closeempty" size="20"></uni-icons>
					</div>
					<div class="add" @tap="toAdd(item)">+新增一行</div>
					<div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
				</div>
				<div class="type" v-if="item.type =='8'">
					<image class="image" v-if="item.answer&&item.answer.length>0" v-for="(as, img) in item.answer"
						:key="img" :src="getUrl(as.url)"></image>
					<div class="remark" v-if="item.remark">{{item.remark}}</div>
				</div>
			</view>
			<view class="button">
				<button type="warn" @tap="toSave">保存</button>
			</view>
		</view>
	</view>
</template>

<script>
	import upload from '../../components/upload/index.vue';
	import moment from 'moment';
	export default {
		components: {
			upload
		},
		data() {
			return {
				openid: "",
				id: '',
				user: {},
				info: {},
				investigate: [],
				form: {
					gender: '0',
					account: '',
					password: '',
					ispassword: '',
					email: '',
					role: ['User']
				},
				// 校验规则
				rules: {
					account: {
						rules: [{
							required: true,
							errorMessage: '账号不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								const reg =
									/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,16}$/g
								if (!reg.test(value)) {
									callback('请输入包含英文字母大小写、数字和特殊符号的 8-16 位组合')
								}
								return true
							}
						}]
					},
					ispassword: {
						rules: [{
								required: true,
								errorMessage: '确认密码不能为空'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value != data.password) {
										callback('两次输入的密码必须相同')
									}
									return true
								}
							}
						]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								const reg = /^1[3-9]\d{9}$/
								if (!reg.test(value)) {
									callback('请输入正确的手机号')
								}
								return true
							}
						}]
					},
				},
				errors: {}
			}
		},
		onLoad: async function(e) {
			const that = this;
			that.$set(that, `id`, e && e.id || '');
			await that.searchOpenids();
			await that.searchToken();
			await that.search();
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.baseForm.setRules(this.rules)
		},
		methods: {
			async searchOpenids() {
				const that = this;
				uni.getStorage({
					key: 'openid',
					success: function(res) {
						that.$set(that, `openid`, res.data);
					},
					fail: function(err) {
						uni.login({
							success: async function(res) {
								if (res.code) {
									const aee = await that.$app('/wechat/api/login/app',
										'GET', {
											js_code: res.code,
											config: that.$config.wx_projectkey
										})
									if (aee.errcode == '0') {
										uni.setStorage({
											key: "openid",
											data: aee.data.openid
										})
										that.$set(that, `openid`, aee.data.openid);
									} else {
										uni.showToast({
											title: aee.errmsg,
											icon: 'none'
										})
									}
								} else {
									uni.showToast({
										title: res.errMsg,
										icon: 'none'
									})
								}
							}
						});
					}
				})
			},
			// 用户信息
			searchToken() {
				const that = this;
				try {
					const res = uni.getStorageSync('token');
					if (res) {
						const user = that.$jwt(res);
						that.$set(that, `user`, user);
					}
				} catch (e) {}
			},
			// 查询
			async search() {
				const that = this;
				if (that.id) {
					let res;
					res = await that.$api(`/match/${that.id}`, 'GET', {})
					if (res.errcode == '0') {
						that.$set(that, `info`, res.data)
						if (res.data.ext_info && res.data.ext_info.length > 0) {
							for (let val of res.data.ext_info) {
								if (val.type == '2') {
									for (let s of val.answer) {
										s.value = s.text
									}
								}
							}
							that.$set(that, `investigate`, res.data.ext_info)
						}
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						});
					}
				}
			},
			getField(data) {
				let res = "请输入内容"
				if (data) res = `请输入${data}`
				return res
			},
			// 图片处理
			getUrl(e) {
				const that = this;
				if (e) return that.$config.serverFile + e
			},
			// 图片上传
			uplSuc(e, item) {
				const that = this;
				for (let val of that.investigate) {
					if (val.sid == item.sid) val.reply = [e.data]
				}
			},
			// 图片删除
			uplDel(e, item) {
				const that = this;
				for (let val of that.investigate) {
					if (val.sid == item.sid) val.reply = []
				}
			},
			// 新增一行
			toAdd(item) {
				const that = this;
				for (let val of that.investigate) {
					if (val.sid == item.sid) {
						let answer = []
						let obj = {
							sid: moment().valueOf(),
						}
						for (let s of val.answer) {
							obj[s.text] = '';
						}
						answer.push(obj)
						if (val.reply) val.reply = [...val.reply, ...answer, ]
						else val.reply = answer
					}
				}
			},
			// 删除一行
			toDel(item, sid) {
				const that = this;
				if (item && item.reply && item.reply.length > 0) {
					let answer = item.reply.filter((i) => i.sid != sid)
					for (let val of that.investigate) {
						if (val.sid == item.sid) {
							val.reply = answer
						}
					}
				}
			},
			// 自定义的验证函数
			validateObject(arr) {
				const errors = {};
				for (const obj of arr) {
					if (obj.is_must == '0') {
						if (!obj.reply || obj.reply.length == 0) {
							if (obj.type == '0' || obj.type == '1' || obj.type == '1') errors[obj.problem] =
								`请选择${obj.problem}`
							else if (obj.type == '6') errors[obj.problem] = `请上传${obj.problem}`
							else errors[obj.problem] = `请填写${obj.problem}`
						}
					}
				}
				// 如果有错误，返回错误对象
				if (Object.keys(errors).length > 0) {
					return errors
				}
				// 如果没有错误，返回null或undefined
				return null
			},
			async toSave() {
				const that = this;
				const errorsInfo = await that.validateObject(that.investigate)
				// 检查是否有错误
				if (errorsInfo) {
					that.$set(that, `errors`, errorsInfo)
					// 遍历错误对象并显示错误信息
					for (const key in errorsInfo) {
						if (errorsInfo.hasOwnProperty(key)) {
							console.error(`${key} 错误: ${errorsInfo[key]}`);
						}
					}
				} else {
					that.$set(that, `errors`, {})
					let data = {
						match_id: that.info.id,
						info: that.investigate
					}
					if (that.user.id) {
						data.user_id = that.user.id
						const res = await that.$api(`/matchReg`, 'POST', data)
						if (res.errcode == '0') {
							uni.showModal({
								content: "调查问卷填写成功！",
								showCancel: false
							});
							uni.navigateBack({
								delta: 1
							})
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							});
						}
					} else {
						that.$refs.baseForm.validate().then(async ass => {
							if (ass.password == ass.ispassword) {
								ass.openid = that.openid
								data.user = {
									nick_name: ass.account,
									...that.form,
									...ass
								}
								const res = await that.$api(`/matchReg`, 'POST', data)
								if (res.errcode == '0') {
									uni.showModal({
										content: "调查问卷填写成功！",
										showCancel: false
									});
									uni.navigateBack({
										delta: 1
									})
								} else {
									uni.showToast({
										title: res.errmsg,
										icon: 'none'
									});
								}
							} else {
								uni.showToast({
									title: `密码不一致`,
									icon: 'error'
								});
								return;
							}
						}).catch(err => {
							console.log('err', err);
							return;
						})
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		.one {
			padding: 2vw;

			.list {
				.problem {
					display: flex;
					align-items: center;

					.t-icon {
						width: 30px !important;
						height: 30px !important;
					}
				}

				.type {
					padding: 2vw 0 2vw 2vw;

					.list {
						display: flex;
						align-items: center;
						justify-content: center;
						margin: 2vw 0;

						.name {
							width: 50%;
							text-align: center;
						}

						.input {
							margin: 0 1vw 0 0;

							.name {
								width: 50%;
								text-align: center;
								margin: 0 0 2vw 0;
							}
						}

						.icon {
							display: none;
							margin: 1vw 0 0 0;
						}
					}

					.list:hover {
						.icon {
							display: block;
						}
					}

					.add {
						border: 1px solid #e5e5e5;
						border-radius: 5px;
						text-align: center;
						padding: 2vw;
					}

					.image {
						width: 96%;
					}

					.error-message {
						text-align: left;
						margin: 5px 0 0 8px;
						color: var(--fF0Color);
						font-size: var(--font12Size);
					}

					.remark {
						margin: 2vw;
						font-size: 12px;
						color: red;
					}
				}
			}

			.button {
				margin: 2vw 0 0 0;
				padding: 2vw;
				text-align: center;

				button {
					background-color: var(--f3CColor);
					font-size: var(--font14Size);
					border-radius: 2vw;
				}
			}
		}
	}
</style>