<template>
	<view class="rf-category">
		<u-navbar :back-text="i18n('Back')" :back-text-style="backStyle" back-icon-color="#fff" title-color="#fff"
			:title="i18n('ActivityRegistration')" :background="background">
		</u-navbar>
		<view class="activityName">
			{{activityInfo.activityName}}
		</view>
		<!-- 加载动画 -->
		<u-mask :show="showLoading" :mask-click-able="false"
			style="display: flex;justify-content: center;align-items: center;">
			<view>
				<u-loading mode="flower" size="100" :show="showLoading"></u-loading>
			</view>
		</u-mask>

		<view class="uni-form">
			<u-form :model="formLabelAlign" ref="uForm" label-position="top" :error-type="errorType">
				<!-- 姓名 -->
				<u-form-item v-if="$i18n.locale=='zh'" label="姓名" prop="name" :required="true">
					<!--<u-form-item :label="i18n('fullName')" prop="name" :required="true"> -->
					<u-input v-model="formLabelAlign.name" :placeholder="i18n('FirstNameTips')" :clearable="false"
						:disabled="true" />
				</u-form-item>
				<!-- country -->
				<u-form-item v-if="$i18n.locale=='en'" label="Country" prop="unitCountry" :required="true">
					<u-input v-model="unitCountry" type="select" :placeholder="i18n('CountryTips')"
						@click="showCountry = true" />
					<!-- 选择器 -->
					<u-select v-model="showCountry" mode="single-column" :list="countrydate" @confirm="confirmCountry"
						label-name="label" value-name="value" :confirm-text="i18n('submit')"
						:cancel-text="i18n('cancel')"></u-select>
				</u-form-item>
				<!-- Region -->
				<u-form-item v-if="$i18n.locale=='en'" label="Region" prop="Region" :required="true">
					<!-- <u-input v-model="formLabelAlign.Region" :placeholder="i18n('RegionTips')" :clearable="false" /> -->
					<u-input v-model="formLabelAlign.Region" type="select"
						:placeholder="'Please select' +' ' +  i18n('Region')" @click="showRegion = true" />
					<u-select v-model="showRegion" mode="single-column" :list="Regiondate" @confirm="confirmRegion"
						label-name="label" value-name="value" :confirm-text="i18n('submit')"
						:cancel-text="i18n('cancel')"></u-select>
				</u-form-item>
				<!-- Title -->
				<u-form-item v-if="$i18n.locale=='en'" label="Title" prop="Title" :required="true">
					<u-input v-model="formLabelAlign.Title" type="select" :placeholder="i18n('TitleTips')"
						@click="showTitle = true" />
					<!-- ActionSheet 操作菜单 -->
					<u-action-sheet :list="titleList" v-model="showTitle" @click="actionSheetCallback"
						cancel-text="cancel"></u-action-sheet>
				</u-form-item>
				<!-- FirstName -->
				<u-form-item v-if="$i18n.locale=='en'" label="First(given) Name(s)" prop="FirstName" :required="true">
					<u-input v-model="formLabelAlign.FirstName" :placeholder="i18n('FirstNameTips')"
						:clearable="false" />
				</u-form-item>
				<!-- LastName -->
				<u-form-item v-if="$i18n.locale=='en'" label="Last Name" prop="LastName" :required="true">
					<u-input v-model="formLabelAlign.LastName" :placeholder="i18n('LastNameTips')" :clearable="false" />
				</u-form-item>
				<!-- 单位名称 -->
				<u-form-item :label="i18n('NameoftheEntity')" prop="unitName" :required="true">
					<u-input v-model="formLabelAlign.unitName" :placeholder="i18n('NameEntityTips')" />
					<u-button slot="right" type="primary" v-if="formLabelAlign.unitName" shape="square" size="mini"
						@click="showSelect">{{i18n('Search')}}</u-button>
					<!-- 选择器 -->
					<u-select v-model="show" mode="single-column" :list="projectList" @confirm="confirm"
						label-name="unitName" value-name="baseEntityId" :confirm-text="i18n('submit')"
						:cancel-text="i18n('cancel')"></u-select>
				</u-form-item>
				<!-- 职务 -->
				<u-form-item :label="i18n('Position')" prop="post" :required="true">
					<u-input v-model="formLabelAlign.post" :placeholder="i18n('PositionTips')" />
				</u-form-item>
				<!-- 联系电话 -->
				<u-form-item :label="i18n('ContactPhoneNumber')" prop="phoneNumber" :required="true">
					<view @click="toGR"
						style="display: inline-block;padding: 6upx; margin-right: 20upx;background-color:#c7c7c7;border-radius:8upx">
						<text
							style="max-width:106upx; overflow: hidden;  white-space: nowrap; text-overflow: ellipsis;display: inline-block;vertical-align: middle;">
							{{selectName}}</text>
						<text style="vertical-align: middle; "> ({{'+' + select}})></text>
					</view>
					<u-input v-model="formLabelAlign.contactNumber" :placeholder="i18n('PhoneTips')" type="number"
						maxlength="20" />
					<!-- <u-button slot="right" type="primary" shape="square" size="mini" @click="showSelect">{{i18n('Search')}}</u-button> -->
				</u-form-item>
				<!-- 邮箱 -->
				<u-form-item :label="i18n('Emails')" prop="mailbox" :required="true">
					<u-input v-model="formLabelAlign.mailbox" :placeholder="i18n('EmailTips')" type="email" />
				</u-form-item>
			</u-form>
			<u-button v-if="showSubmitBtnFlag" style="margin-top: 100upx;bottom: 60upx;" @click="submit" type="primary">
				{{i18n('SubmitAndDownload')}}
			</u-button>
		</view>
		<u-toast ref="uToast" />
		<!-- <u-popup v-model="showGlobalRoaming" mode="bottom" height="100%">
			<GlobalRoaming @getAreCode="getMoblieAreCode"></GlobalRoaming>
		</u-popup> -->
	</view>
</template>
<script>
	import GlobalRoaming from "../../public/GlobalRoaming.vue"
	import {
		addIntegral,
		addGrowth
	} from '@/components/addPointDetailByTaskDict.js'
	export default {
		components: {
			GlobalRoaming,
			addIntegral,
			addGrowth
		},
		data() {
			return {
				showGlobalRoaming: false,
				show: false,
				showLoading: false,
				showTitle: false,
				showCountry: false,
				showRegion: false,
				ActiviteId: "",
				activityInfo: {},
				backStyle: {
					color: '#ffffff',
				},
				background: {
					backgroundImage: 'linear-gradient(270deg, #4BC0E2 0%, #538BE7 100%)',
				},
				rules: {
					name: [{
						required: true,
						message: this.i18n('FirstNameTips'),
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur'],
					}],
					unitCountry: [{
						required: true,
						message: 'Please enter country',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur'],
					}],
					Region: [{
						required: true,
						message: this.i18n('RegionTips'),
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur'],
					}],
					Title: [{
						required: true,
						message: this.i18n('TitleTips'),
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur'],
					}],
					FirstName: [{
						required: true,
						message: 'Please enter First(given) Name(s)',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur'],
					}],
					LastName: [{
						required: true,
						message: 'Please enter Last Name',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur'],
					}],
					unitName: [{
						required: true,
						message: this.i18n('NameEntityTips'),
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur'],
					}],
					post: [{
						required: true,
						message: this.i18n('PositionTips'),
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur'],
					}],
					contactNumber: [{
							required: true,
							message: this.i18n('PhoneTips'),
							// 可以单个或者同时写两个触发验证方式
							trigger: ['change', 'blur'],
						},
						{
							max: 20
						}
					],
					mailbox: [{
							required: true,
							message: this.i18n('EmailTips'),
							// 可以单个或者同时写两个触发验证方式
							trigger: ['change', 'blur'],
						},
						// 正则判断为邮箱
						{
							// pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
							pattern: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: this.i18n('Pleaseenterthecorrectemailnumber') + "！",
						},
					],
				},
				// message：文字提示
				// border：配置输入框的边框为红色进行提示
				// toast：以"toast"提示的方式弹出错误信息
				// none：不提示
				// errorType: ['message', 'border-bottom'],//文字和下划线提示
				errorType: ['message', 'border-bottom'],
				countrydate: [], //国家数据
				Regiondate: [], //大洲数据
				formLabelAlign: {
					name: '',
					unitName: '', //id
					unitNameLabel: '', //名字
					ifName: null,
					post: '',
					contactNumber: '',
					mailbox: '',
					FirstName: '',
					LastName: '',
					unitCountry: '',
					Title: '',
					Region: '',
					auditStatusDict: '',
					language: '',
					selectCode: '0086',
					invitationCode: '', //邀请码
					meetingId: '' //会议id
				},
				titleList: [{
						value: 'Mr.',
						text: 'Mr.'
					},
					{
						value: 'Ms.',
						text: 'Ms.'
					},
					{
						value: 'Dr.',
						text: 'Dr.'
					},
					{
						value: 'Prof.',
						text: 'Prof.'
					}
				],
				token: '',
				approverId: '',
				taskComment: '',
				projectList: [],
				activityIds: '',
				selectMap: {}, //select选择器选中的内容
				Storage_data: "",
				select: '0086',
				selectName: this.$i18n.locale == 'zh' ? '中国' : 'China',
				selectList: '',
				regLogStyle: '5',
				meetingApply: {},
				unitName: "",
				unitCountry: "",
				showSubmitBtnFlag: true,
			}
		},
		async onShow() {
			this.getList();
			try {
				this.Storage_data = JSON.parse(uni.getStorageSync('user'));
				this.token = uni.getStorageSync('Auth-Token');
			} catch (e) {

			};
			if (this.Storage_data) {
				this.formLabelAlign.name = this.Storage_data.realName;
			}
			this.getCountryDate();
			//添加监听一个handleFun的事件
			uni.$on("moblieAreCode", res => {
				this.selectList = res;
				// 清除监听
				uni.$off('moblieAreCode');
			});
			if (this.selectList) {
				this.select = this.selectList.id ? this.selectList.id : this.select;
				let countryName = this.$i18n.locale == 'zh' ? this.selectList.cnValue : this.selectList.enValue;
				this.selectName = countryName ? countryName : this.selectName;
			}

		},
		onLoad: function(options) { //option为object类型，会序列化上个页面传递的参数
			if (options.Rep) {
				this.showSubmitBtnFlag = false
			}
			console.log('option', options)
			if (options.id) {
				this.ActiviteId = options.id
			}
			if (options.Rep) {
				this.getApplyMes(options.Rep)
			}
		},
		async onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			/* getMoblieAreCode(data) {
				console.log('getMoblieAreCodef', data)
				this.selectList = data ? data : {};
				this.select = this.selectList.id ? this.selectList.id : this.select;
				let countryName = this.$i18n.locale == 'zh' ? this.selectList.cnValue : this.selectList.enValue;
				this.selectName = countryName ? countryName : this.selectName;

				this.showGlobalRoaming=false
			}, */
			async getApplyMes(ele) {
				const that = this;
				const result = await this.$myRequest({
					url: '/project/coopCustomServices/getUnitViews',
					data: {
						language: this.$i18n.locale.toUpperCase()
					},
				});
				if (JSON.stringify(result.data) !== '{}') {
					that.projectList = result.data.baseUnitViewList || [];
				}

				const res = await this.$myRequest({
					url: `/meeting/meetingApplys/${ele}`,
				});

				if (res) {
					let data = res.data;
					const that = this;
					if (data) {

						this.meetingApply = data.meetingApply || this.meetingApply;
						this.formLabelAlign.id = this.meetingApply.id;
						this.formLabelAlign.name = this.meetingApply.name;

						this.formLabelAlign.ifName = 'false'
						if (this.$i18n.locale == 'zh') {
							this.formLabelAlign.unitName = this.meetingApply.unitName;
							this.formLabelAlign.ifName = 'true'
						} else {
							this.formLabelAlign.unitName = this.meetingApply.unitNameEn;
							this.formLabelAlign.ifName = 'true'
						}

						this.projectList.forEach(i => {
							if (this.$i18n.locale == 'zh') {

								if (this.meetingApply.unitName == i.unitName) {
									// this.formLabelAlign.unitName = i.baseEntityId;
									this.formLabelAlign.unitName = i.unitName;
									this.unitNameLabel = i.unitName;
									// this.unitName = i.unitName;
									this.formLabelAlign.ifName = 'true'
								}
							} else {
								if (this.meetingApply.unitNameEn == i.unitName) {
									this.formLabelAlign.unitName = i.baseEntityId;
									this.unitNameLabel = i.unitName;
									// this.unitName = i.unitName;
									this.formLabelAlign.ifName = 'true'
								}
							}
						});
						// this.formLabelAlign.unitName = i.baseEntityId;
						that.formLabelAlign.post = that.meetingApply.positionName;
						that.formLabelAlign.contactNumber = that.meetingApply.tel;
						that.formLabelAlign.mailbox = that.meetingApply.email;
						that.formLabelAlign.unitCountry = that.meetingApply.unitCountryDict;
						that.unitCountry = that.meetingApply.unitCountryDict;
						that.formLabelAlign.Region = that.meetingApply.unitCountryDictEn;
						that.formLabelAlign.Title = that.meetingApply.dietaryTaboos;
						that.formLabelAlign.FirstName = that.meetingApply.givenName;
						that.formLabelAlign.LastName = that.meetingApply.surname;
						that.formLabelAlign.meetingId = that.meetingApply.meetingId;
						that.select = that.formLabelAlign.selectCode = that.meetingApply.mobileAreaCodeDictEn;
						// console.log(that.formLabelAlign.unitCountry ,that.meetingApply.unitCountryDict,'--------------')
						// debugger

					}
				}
			},
			toGR() {
				uni.navigateTo({
					url: '/pages/public/GlobalRoaming?regLogStyle=' + this.regLogStyle
				})
				// this.showGlobalRoaming = true;
			},
			async showSelect() {
				// this.showLoading = true;
				if (this.formLabelAlign.unitName) {
					await this.getSelecBaseList();
				} else {
					await this.getBaseList();
				}
				this.showLoading = false;
				this.show = true;
			},
			confirm(arr) {
				console.log(arr);
				if (arr[0].value == '1') {
					this.show = false;
					this.formLabelAlign.ifName = 'false'
				} else {
					this.formLabelAlign.unitName = arr[0].label;
					this.formLabelAlign.unitNameLabel = arr[0].value;
					this.selectMap = arr[0];
					this.activityIds = arr[0].value;
					//报名不通过后修改ifname状态
					this.formLabelAlign.ifName = 'false'
				}
			},
			confirmCountry(arr) {
				console.log(arr);
				this.formLabelAlign.unitCountry = arr[0].value;
				this.unitCountry = arr[0].label;
			},
			confirmRegion(arr) {
				console.log(arr);
				this.formLabelAlign.Region = arr[0].label;
				// this.unitCountry = arr[0].label;
			},
			actionSheetCallback(index) {
				console.log(`点击了第${index + 1}项，内容为：${this.titleList[index].text}`)
				this.formLabelAlign.Title = this.titleList[index].text;
			},
			async getList() {
				const res = await this.$myRequest({
					url: '/project/activityInfos/getById',
					data: {
						baseActivityEntityId: this.ActiviteId,
						language: this.$i18n.locale.toUpperCase()
					}
				});
				this.activityInfo = res.data.activityInfos[0] || {};
				if (this.activityInfo) {
					this.formLabelAlign.invitationCode = this.activityInfo.activityQrCode
					this.formLabelAlign.meetingId = res.data.meetingId;
				}
			},
			i18n(data) {
				return this.$t('common.' + data);
			},
			async save() {
				const that = this;
				//流程改造6
				this.formLabelAlign.auditStatusDict = '4';

				// this.formLabelAlign.unitName = that.activityInfo.baseActivityEntityId;
				that.formLabelAlign.invitationCode = that.activityInfo.activityQrCode;
				//流程改造7
				const result = await this.$myRequest({
					url: '/meeting/meetingApplys/getApproverId',
					data: {
						activityIds: this.ActiviteId,
						invitationCode: that.formLabelAlign.invitationCode,
					}
				});
				if (result) {
					var resdata = result.data;
					var str = "";
					for (var i = 0; i < resdata.length; i++) {
						str += resdata[i].userId + ",";
					}
					if (str.length > 0) {
						str = str.substr(0, str.length - 1);
					}
					this.approverId = str;
					// 会员模块后期加的  可传空字符串
					const res = await this.$myRequest({
						url: '/meeting/meetingApplys/saveActivityOrUpdate',
						header: that.token,

						data: {
							formLabelAlign: JSON.stringify(that.formLabelAlign),
							approver: that.approverId,
							taskComment: that.taskComment,
							// token: that.token,
							activityIds: that.activityIds
						},
						method: 'put',
					});

					console.log("approverId", this.approverId)
					if (res.status == '200') {
						let type = 'success';
						if (res.msg == 'error') {
							res.msg = this.$i18n.locale == 'zh' ? '您已报名成功，请勿重复报名。' :
								'You have registered successfully, please do not repeat the registration';
							type = 'warning';
						} else {
							res.msg = this.$i18n.locale == 'zh' ? '报名成功' : 'Successful registration';
						}
						that.$refs.uToast.show({
							title: res.msg,
							type: type,
							// url: '/pages/cooperationExchange/cooperationExchangeList/activitiesInfo',
							// params: {
							// 	ActivitesId: this.ActiviteId,
							// }
						});
						setTimeout(() => {
							// 2秒后自动跳转
							// uni.reLaunch({
							// 	url: '/pages/cooperationExchange/cooperationExchangeList/activitiesInfo?ActivitesId=' + this.ActiviteId
							// });
							uni.navigateBack({
								delta: 1
							});
						}, 2000)
						this.resetToken();
					} else {
						that.$refs.uToast.show({
							title: res.msg,
							type: 'error',
						});
						this.resetToken();
					}
				}
			},
			resetToken() {
				this.token = null;
			},
			/* async getBaseList() {
				const that = this;
				const res = await this.$myRequest({
					url: '/project/baseUnitViews/getList',
					data: {
						language: this.$i18n.locale.toUpperCase()
					},
				});
				if (JSON.stringify(res.data) !== '{}') {
					that.projectList = res.data.baseUnitViews || [];
				}
				console.log('121474', that.projectList);
			}, */
			async getBaseList() {
				const that = this;
				const res = await this.$myRequest({
					url: '/project/coopCustomServices/getUnitViews',
					data: {
						language: this.$i18n.locale.toUpperCase()
					},
				});
				if (JSON.stringify(res.data) !== '{}') {
					that.projectList = res.data.baseUnitViewList || [];
				}

			},
			async getCountryDate() {
				const result = await this.$myRequest({
					url: '/sys/sysDicts',
					data: {
						type: 'unit_country_dict_en'
					},
				});
				if (result.status == '200') {
					this.countrydate = result.data[0];
				};
				const results = await this.$myRequest({
					url: '/sys/sysDicts',
					data: {
						type: 'CONTINENT_CODE_DICT_EN'
					},
				});
				if (results.status == '200') {
					this.Regiondate = results.data[0];
				};
			},
			async getSelecBaseList() {
				const res = await this.$myRequest({
					url: '/project/baseUnitViews/getUnitByNameForApp',
					data: {
						unitName: this.formLabelAlign.unitName,
						// unitName: "",
						language: this.$i18n.locale.toUpperCase()
					},
				});
				if (JSON.stringify(res.data) !== '{}') {
					this.projectList = res.data.baseUnitViews || [];
				} else if (JSON.stringify(res.data) == '{}') {
					this.projectList = [{
						unitName: this.$i18n.locale == 'en' ? 'NO Data' : '无数据',
						baseEntityId: '1'
					}];
				}
			},
			submit() {
				const that = this;
				if (this.formLabelAlign.unitName != this.selectMap.label) {
					this.activityIds = '';
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						that.save();
						console.log('验证通过');
						addIntegral('activity_registration_successful', '10')
						addGrowth('activity_registration_successful', '10')
					} else {
						console.log('验证失败');
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.rf-category {
		background-color: $color-white;
		max-height: 150vh;
		min-height: 100vh;
		/*  #ifdef  APP-PLUS  */
		// margin-top: calc(20upx + var(--status-bar-height));
		/*  #endif  */

		.uni-form {

			margin: 32upx;
			height: 100%;
		}

		.activityName {
			margin: 32upx;
			font-size: 32upx;
			font-weight: 700;
		}

		.title-icon {
			color: #ff0000;
		}

		.module-classify-border {
			margin: 10upx 0upx;
			background-color: #adadad;
			height: 1upx;
		}



	}
</style>
