<template>
	<view class="container">
		<view class="top">
			<text class="iconfont icon-youjiantou zuojiantou" @click="goBack()"></text>
			<text>申请加盟</text>
		</view>
		<view class="page">
			<text class="num actived">1</text>
			<text class="line"></text>
			<text class="num">2</text>
			<text class="line"></text>
			<text class="num">3</text>
			<text class="line"></text>
			<text class="num">4</text>
			<text class="line"></text>
			<text class="num">5</text>
			<text class="line"></text>
			<text class="num">6</text>
	 		<text class="line"></text>
			<text class="num">7</text>
	<!--		<text class="line"></text>
			<text class="num">8</text> -->
		</view>
		<view class="wrapper">
			<view class="title">
				<view>
					<text class="line"></text>
					基本资料
				</view>
				<text class="page_mark">1/7</text>
			</view>
			<view class="content">
				<view class="contentDetail employ">
					<!-- <view class="contentItem" v-if="Invitationcodetype == true">
						<text>邀请码</text>
						<input type="text" class="form-control" placeholder="非必填"
							v-model="applyParam.inviterInvitationCode" :disabled="this.display" />
					</view> -->
					<!-- <view class="contentItem">
						<text>申请身份</text>
						<picker @change="changeIdentity" :value="identityIdx" :range="identityArr" range-key="name"
							:disabled="this.display">
							<view class="uni-input">{{identityArr[identityIdx]['name']}}
								<text class="iconfont icon-youjiantou"></text>
							</view>
						</picker>
					</view>
					<view class="contentItem" v-if="applyParam.partnerLevel == 'B1'">
						<text>工作室名称</text>
						<input type="text" class="form-control"
							:disabled="this.applyParam.approvalStatus!= 0 && this.applyParam.approvalStatus != 2"
							v-model="applyParam.b1Name" placeholder="请输入工作室名称" />
					</view>
					<view class="contentItem" >
						<text>所属组织</text>
						<input type="text" v-if="applyParam.applyType == 1" class="form-control"
							v-model="applyParam.areaName" placeholder="请输入工作室名称" :disabled="this.display" />
						<picker v-else @change="changeArea" :value="areaIdIdx" :range="cffpAreaQuerys"
							range-key="areaName" :disabled="this.display">
							<view class="uni-input">{{cffpAreaQuerys[areaIdIdx]['areaName']}}
								<text class="iconfont icon-youjiantou"></text>
							</view>
						</picker>
					</view> -->
					<view class="contentItem">
						<text>  <text class="requireCode">*</text>姓名</text>
						<!-- @blur="checkInput(1,applyParam.name)" -->
						<input 
							type="text" 
							class="form-control" 
							v-model="applyParam.name" 
							placeholder="请输入姓名"
							auto-blur=true  
							:disabled="this.display"
							maxlength="10"
						/>
					</view>
					<view class="contentItem">
						<text><text class="requireCode">*</text>手机号</text>
						<input type="text" class="form-control" v-model="applyParam.mobileNumber" placeholder="请输入手机号"
							maxlength="11" auto-blur=true @blur="checkInput(2,applyParam.mobileNumber)"
							:disabled="this.display" />
					</view>
					<view class="contentItem" @click="openSelsect('1')">
						<text><text class="requireCode">*</text>证件类型</text>
						<commonSelect 
							:dataList="idTypesList"
							:visible="showIdType"
							:showValue="idTypeIdx"
							@confirm="changeIdTypeSelect"
							@close="showIdType=false"
						/>
					</view>
					<view class="contentItem">
						<text><text class="requireCode">*</text>证件号码</text>
						<view>
							<input 
								type="text" 
								class="form-control" 
								v-model="applyParam.idNo" 
								placeholder="请输入证件号码"
								auto-blur=true 
								@blur="checkInput(3,applyParam.idNo)"
								maxlength="20"
								:disabled="this.applyParam.approvalStatus!= 0 && this.applyParam.approvalStatus != 2" />
						</view>
					</view>
					<view class="contentItem"  @click="openBirthday">
						<text><text class="requireCode">*</text>出生日期</text>
						<commonTimePicker
							:timeData="birthObj"
							:visible="showBirthday" 
							:birthDay="true"
							:showDay="true"
							:yearStart="1900"
							:yearEnd="yearend"
							startTxt="请选择"
							iconDirection="right"
							@confirmDate="changeBirthDay" 
							@closeTime="showBirthday=false"
						/>
					</view>
					<view class="contentItem">
						<text>居住地址</text>
						<view>
							<input 
								maxlength="50"
								type="text" 
								class="form-control" 
								placeholder="xx省xx市xx区xx路xx号" 
								v-model="applyParam.liveAddress"
								:disabled="this.applyParam.approvalStatus!= 0 && this.applyParam.approvalStatus != 2" 
							/>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="fixed" @click="saveInfo()">
			{{(this.applyParam.approvalStatus== 0 || this.applyParam.approvalStatus == 2)?'保存并下一步':'下一步'}}
		</view>
	</view>
</template>

<script>
	import api from "@/api/api";
	import common from '@/common/common.ts';
	import validate from '@/util/validate.js';
	import util  from "@/util/dataHandling";
	import commonSelect from '@/components/commonSelect/commonSelect.vue';
	import commonTimePicker from '@/components/commonTimePicker/commonTimePicker.vue';
	export default {
		components: {
			commonSelect,
			commonTimePicker
		},
		data() {
			return {
				birthObj:{year:null,month:null,day:null},
				yearend:util.getDateParts().year-18,
				showBirthday:false,
				showIdType:false,
				showBank:false,
				identityIdx:0,
				identityArr: [{
					partnerLevel: 'A1',
					name: '事业伙伴'
				}, {
					partnerLevel: 'B1',
					name: '工作室'
				}],
				applyParam: {
					inviterInvitationCode: '',
					name: '',
					mobileNumber: '',
					partnerLevel: 'P1',
					idType: '',
					idNo: '',
					birthday: '',
					areaId: '',
					approvalStatus: 0,
					b1Name: '',
					liveAddress: ''
					// birthday:`${new Date().getFullYear()}-${new Date().getMonth() + 1} -${new Date().getDate()}`,
				},
				idTypesList: [{id:null,name:'请选择'}],
				idTypeIdx: 0,
				maxDate: `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()}`,
				cffpAreaQuerys: [{
					areaId: null,
					areaName: "请选择所属组织",
					levelOrder: null
				}],
				areaIdIdx: 0,
				areaName: null,
				partnerLevelName: null,
				name: null,
				mobile: null,
				userId: uni.getStorageSync('cffp_userId'),
				shareId: null,
				display: false,
				Invitationcodetype: false,
				cffp_userInfo: {
					name: '',
					mobile: ''
				}
			}
		},
		components: {},
		onLoad(options) {
			if (options.shareId) {
				this.shareId = options.shareId
				uni.setStorageSync('applyId', '')
				uni.removeStorageSync('workform')
				uni.removeStorageSync('cardForm')
				uni.removeStorageSync('educationForm')
				uni.removeStorageSync('backForm')
				uni.removeStorageSync('personalForm')
				uni.removeStorageSync('contractForm')
				uni.removeStorageSync('picList')
			} else {
				this.cffp_userInfo = uni.getStorageSync('cffp_userInfo');
				if (this.cffp_userInfo) {
					this.applyParam.name = JSON.parse(uni.getStorageSync('cffp_userInfo'))['name'];
					this.applyParam.mobileNumber = JSON.parse(uni.getStorageSync('cffp_userInfo'))['mobile'];
				}
			}
			// this.erpInitialize();
			// let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			// let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
			// console.log('当前路由地址',curRoute)
			// if(!uni.getStorageSync('applyId') && options.shareId){
			// 	this.queryById(options.id,null)
			// }

		},
		onShow() {
			if (this.shareId) {
				this.queryById(this.shareId, null)
			} else if (uni.getStorageSync('applyId')) {
				this.queryById(uni.getStorageSync('applyId'), null)
			} else {
				this.queryById(null, uni.getStorageSync('cffp_userId'))
			}
			console.log('year',util.getDateParts().year);
		},
		methods: {
			openBirthday(){
				if(this.applyParam.approvalStatus == 0 || this.applyParam.approvalStatus == 2){
					this.showBirthday = true
				}
				
			},
			changeBirthDay(obj){
				this.birthObj = obj
				this.showBirthday = false
				this.applyParam.birthday = `${obj.year}-${obj.month<10?`0${obj.month}`:obj.month}-${obj.day<10?`0${obj.day}`:obj.day}`;
				if(!util.isAdult(this.applyParam.birthday)){
					uni.showToast({
						title: '未满18岁不可申请',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				
			},
			changeIdTypeSelect(value){
				this.idTypeIdx = value;
				this.applyParam.idType = this.idTypesList[this.idTypeIdx]['name'];
				this.showIdType = false
			},
			openSelsect(type){
				if(this.applyParam.approvalStatus == 0 || this.applyParam.approvalStatus == 2){
					this.showIdType = true
				}
			},
			goBack() {
				uni.navigateBack({
					delta: 1  
				});
			},
			erpInitialize() {
				return new Promise((resolve, reject) => {
					api.erpInitialize({}).then((res) => {
						resolve(res['success']);
						if (res['success']) {
							this.idTypesList = this.idTypesList.concat(res['data']['idTypes']);
						}
					})
				})
			},
			queryOrgList() {
				const param = {
					userId: this.userId,
					partnerLevel: this.applyParam.partnerLevel
				}
				api.queryOrgList(param).then((res) => {
					if (res['success']) {
						this.cffpAreaQuerys = [{
							areaId: null,
							areaName: "请选择所属组织",
							levelOrder: null
						}]
						this.cffpAreaQuerys = this.cffpAreaQuerys.concat(res['data']['cffpAreaQuerys'])
						for (let j = 0; j < this.cffpAreaQuerys.length; j++) {
							if (this.applyParam.areaId == this.cffpAreaQuerys[j].areaId) {
								this.areaIdIdx = j;
							}
						}
					}
				})
			},
			changeIdentity: function(e) {
				this.identityIdx = e.detail.value;
				this.applyParam.partnerLevel = this.identityArr[this.identityIdx]['partnerLevel'];
				
				this.areaIdIdx = 0;
			},
			
			changeArea: function(e) {
				this.areaIdIdx = e.detail.value;
				this.applyParam.areaId = this.cffpAreaQuerys[this.areaIdIdx]['areaId'];
			},
			checkInput(type, code) {
				
				// if (type == 1) {
				// 	if (code && !common.nameValid(code)) {
				// 		uni.showToast({
				// 			title: '请输入真实的姓名!',
				// 			duration: 2000,
				// 			icon: 'none'
				// 		})
				// 		return;
				// 	}
				// }
				if (type == 2) {
					if (code && !common.mobileNoValid(code)) {
						uni.showToast({
							title: '请输入正确的手机号码!',
							duration: 2000,
							icon: 'none'
						})
						return;
					}
				}
				if (type == 3) {
					if (this.applyParam.idType === '身份证') {
						if (code && !common.IdCodeValid(code).pass) {
							uni.showToast({
								title: `${common.IdCodeValid(code).msg}`,
								duration: 2000,
								icon: 'none'
							})
							return;
						}
						
						this.applyParam.birthday = util.dateFormat2(common.IdCodeValid(code).birthDay, 'yyyy-MM-dd');
						let date = this.applyParam.birthday.split('-')
						this.birthObj.year = Number(date[0])
						this.birthObj.month = Number(date[1])
						this.birthObj.day = Number(date[2])
					} else {
						if (code && !common.checkTaxNo(code)) {
							uni.showToast({
								title: '证件号码只能是5-20位的数字字母组合',
								duration: 2000,
								icon: 'none'
							})
							return;
						}
					}

				}
			},
			async queryById(id, userId) {
				await this.erpInitialize();
				api.queryById({
					id: id,
					userId: userId
				}).then((res) => {
					if (res['success']) {
						this.applyParam = res['data']['data'];
						if(this.applyParam.birthday&&this.applyParam.birthday.length>0){
							let date = this.applyParam.birthday.split('-')
							this.birthObj.year = Number(date[0])
							this.birthObj.month = Number(date[1])
							this.birthObj.day = Number(date[2])
						}
						if (this.applyParam.inviterInvitationCode) {
							this.Invitationcodetype = true
						}
						for (let m = 0; m < this.identityArr.length; m++) {
							if (this.applyParam.partnerLevel == this.identityArr[m].partnerLevel) {
								this.identityIdx = m;
								break;
							}
						}
						for (let i = 0; i < this.idTypesList.length; i++) {
							if (this.idTypesList[i].name == this.applyParam.idType) {
								this.idTypeIdx = i;
								console.log('this.idTypeIdx',this.idTypeIdx);
								break;
							}
						}
						if (this.applyParam.approvalStatus != 0 && this.applyParam.approvalStatus != 2 || this
							.applyParam.applyType == '1') {
							this.display = true
						}
					}
				})
			},
			saveInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				if (this.applyParam.approvalStatus == 0 || this.applyParam.approvalStatus == 2) {
					// if (!this.applyParam.areaId) {
					// 	uni.showToast({
					// 		title: '请选择所属组织',
					// 		duration: 2000,
					// 		icon: 'none'
					// 	})
					// 	return;
					// }
					if (!this.applyParam.name) {
						uni.showToast({
							title: '请输入姓名',
							duration: 2000,
							icon: 'none'
						})
						return;
					}
					 if (!common.nameValid(this.applyParam.name)) {
						let that = this;
						uni.showToast({title: '请填写真实姓名',duration: 2000,icon: 'none'});
						this.applyParam.name = ''
						return
					}
					if (!this.applyParam.mobileNumber) {
						uni.showToast({
							title: '请输入手机号',
							duration: 2000,
							icon: 'none'
						})
						return;
					}
					if (!this.applyParam.partnerLevel) {
						uni.showToast({
							title: '请选择申请身份!',
							duration: 2000,
							icon: 'none'
						})
						return;
					} else {
						if (this.applyParam.partnerLevel == 'B1') {
							if (!this.applyParam.b1Name) {
								uni.showToast({
									title: '申请身份为工作室时,工作室名称必填!',
									duration: 2000,
									icon: 'none'
								})
								return;
							}
						}
					}
					if (!this.applyParam.idType || this.applyParam.idType == '请选择') {
						uni.showToast({
							title: '请选择证件类型',
							duration: 2000,
							icon: 'none'
						})
						return;
					}
					if (!this.applyParam.idNo) {
						uni.showToast({
							title: '请输入证件号',
							duration: 2000,
							icon: 'none'
						})
						return;
					}
					if (!this.applyParam.birthday) {
						uni.showToast({
							title: '请选择出生日期',
							duration: 2000,
							icon: 'none'
						})
						return;
					}else{
						if(!util.isAdult(this.applyParam.birthday)){
							uni.showToast({
								title: '未满18岁不可申请',
								duration: 2000,
								icon: 'none'
							})
							return
						}
						
						
					}
					if(this.applyParam.liveAddress&&!validate.validateDetailAddress(this.applyParam.liveAddress)){
						uni.showToast({title: '请输入真实地址',duration: 2000,icon: 'none'});
						this.applyParam.liveAddress = ''
						return
					}
					
					this.applyParam = {
						...this.applyParam,
						applyType: this.applyParam.inviterInvitationCode ? '1' : '2',
						operatStep: 1,
						userId: this.userId,
						hasCrossDistrict: this.applyParam.hasCrossDistrict ? this.applyParam.hasCrossDistrict : '0'
					}
					
					if((this.idTypeIdx == '1' || this.idTypeIdx == '5')&&this.applyParam.idNo.length<18 ){
						uni.showToast({title: '请输入18位身份证号',duration: 2000,icon: 'none'});
						return
					}
					// 暂时关闭
					if((this.idTypeIdx == '1' || this.idTypeIdx == '5')){
						let obj = common.IdCodeValid(this.applyParam.idNo)
						if(!obj.pass){
							uni.showToast({title: obj.msg,duration: 2000,icon: 'none'});
							return
						}
						
					}
					api.saveApplyInfo(this.applyParam).then((res) => {
						if (res['success']) {
							uni.navigateTo({
								url: `id-card`
							});
							uni.setStorageSync('applyId', String(res['data']['id']))
						} else {
							uni.showToast({
								title: res['message'],
								duration: 2000,
								icon: 'none'
							})
							return;
						}
						uni.hideLoading()
					})
				} else {
						uni.navigateTo({
							// url:`id-card?id=${res['data']['id']}`
							url: `id-card`
						});
				uni.hideLoading()
				}
			},
			validateDetailAddress(address) {
			      // 验证是否包含省市区信息
			      const provinceCityRegex = /(省|自治区|直辖市|市|区|县|自治州|盟|旗)/;
			      
			      // 验证详细地址格式（门牌号等）
			      const detailRegex = /^[\u4e00-\u9fa5a-zA-Z0-9\-\.\/号栋单元室房层]+$/;
			      
			      if (!provinceCityRegex.test(address)) {
					  uni.showToast({title: '地址中应包含省市区信息',duration: 2000,icon: 'none'});
			        return false
			      }
			      
			      if (!detailRegex.test(address)) {
					   uni.showToast({title: '详细地址格式不正确',duration: 2000,icon: 'none'});
			        return false
			      }
			      
			      return true
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'applyCommon.scss';
	.form-control{
		min-width: 400rpx;
	}
	.requireCode{
		color: red;
	}
</style>
