<template>
	<view class="auth-Container">
		<uni-forms ref="baseForm" :modelValue="baseFormData" labelWidth="75px" :rules="rules" validateTrigger="bind">
			<uni-forms-item label="真实姓名" name="name" required>
				<uni-easyinput v-model="baseFormData.name" placeholder="请输入姓名" maxlength="6" trim="both" />
			</uni-forms-item>
			<uni-forms-item label="手机号" name="phone" required>
				<uni-row>
					<uni-col :span="14">
						<uni-easyinput v-model="baseFormData.phone" placeholder="请输入手机号" :disabled="disabledPhone" trim="both" />
					</uni-col>
					<uni-col :span="8" :offset="2">
						<view class="phoneClass">
							<button class="getPhone" open-type="getPhoneNumber" 
								@getphonenumber="getPhoneNumber">自动获取</button>
						</view>
					</uni-col>
				</uni-row>
			</uni-forms-item>
			<uni-forms-item label="微信号" name="weixinId" required>
				<uni-easyinput v-model="baseFormData.weixinId" placeholder="微信号(不便接听电话时微信沟通)" maxlength="25"
					trim="both" />
			</uni-forms-item>
			<uni-forms-item label="英文名" name="englishName">
				<uni-easyinput v-model="baseFormData.englishName" placeholder="请输入你的英文名" maxlength="25" trim="both" />
			</uni-forms-item>
			<uni-forms-item label="身份证号" name="idCard" required>
				<uni-easyinput v-model="baseFormData.idCard" type="idcard" placeholder="请输入你的身份证号" />
			</uni-forms-item>
			<uni-forms-item label="性别" name="sex" required>
				<uni-data-checkbox v-model="baseFormData.sex" :localdata="sexs" />
			</uni-forms-item>
			<uni-forms-item label="身份" name="identify" required>
				<uni-data-checkbox v-model="baseFormData.identify" :localdata="identifies"/>
			</uni-forms-item>
			<uni-forms-item label="身份证照片" required>
				<text style="color: blue;">(说明：需要能看清楚证件号码、日期及头像)</text>
				<uni-file-picker fileMediatype="image"  :sizeType="sizeType" :imageStyles="listStyle" v-model="idCardFrontByte" :fileExtname="fileExtname" limit="1" title="身份证正面" @select="selectPhoto('idCardFront', $event)" @delete="deletePhoto('idCardFront', $event)" />
				<uni-file-picker fileMediatype="image"  :sizeType="sizeType" :imageStyles="listStyle" v-model="idCardBackByte" :fileExtname="fileExtname"  limit="1" title="身份证背面" @select="selectPhoto('idCardBack', $event)" @delete="deletePhoto('idCardBack', $event)" />
			</uni-forms-item>
			<uni-forms-item label="学生/毕业证" required>
				<text style="color: blue;">(已毕业的需要上传毕业证)</text>
				<uni-file-picker fileMediatype="image"  :sizeType="sizeType" :imageStyles="listStyle" v-model="diplomaPhotoByte" :fileExtname="fileExtname" limit="1" @select="selectPhoto('diplomaPhoto', $event)" @delete="deletePhoto('diplomaPhoto', $event)" />
			</uni-forms-item>
			<uni-forms-item label="头像" required>
				<text style="color: blue;">(说明：只能上传证件照，上传其他照片审核不予通过)</text>
				<uni-file-picker fileMediatype="image"  :sizeType="sizeType" :imageStyles="listStyle" v-model="teacherPhotoByte" :fileExtname="fileExtname" limit="1" @select="selectPhoto('teacherPhoto', $event)" @delete="deletePhoto('teacherPhoto', $event)" />
			</uni-forms-item>
			<uni-forms-item label="毕业/就读学校" name="school" required>
				<uni-easyinput v-model="baseFormData.school" placeholder="请输入学校全称" maxlength="30" trim="both" />
			</uni-forms-item>
			<uni-forms-item label="所学专业" name="major" required>
				<uni-easyinput v-model="baseFormData.major" placeholder="请输入专业名称" maxlength="20" trim="both" />
			</uni-forms-item>
			<uni-forms-item label="学历" name="education" required>
				<uni-data-select v-model="baseFormData.education" :localdata="educations" />
			</uni-forms-item>
			<uni-forms-item label="毕业年月" name="graduateMonth" required>
				<picker mode="date" fields="month" :value="baseFormData.graduateMonth" @change="bindDateChange">
						<uni-easyinput v-model="baseFormData.graduateMonth" placeholder="请选择全日制学历毕业年月" />
				</picker>
			</uni-forms-item>

			<uni-forms-item label="籍贯" name="nativePlace" required>
				<uni-easyinput v-model="baseFormData.nativePlace" placeholder="xx省xx市xx区" maxlength="30" trim="both" />
			</uni-forms-item>
		</uni-forms>
		
		<!-- <canvas canvas-id="idCardFront" class="idCardFrontClass" :style="{width:idCardFrontWidth, height:idCardFrontHeight}"></canvas>
		<canvas canvas-id="idCardBack" class="idCardBackClass" :style="{width:idCardBackWidth, height:idCardBackHeight}"></canvas>
		<canvas canvas-id="diplomaPhoto" class="diplomaPhotoClass" :style="{width:diplomaPhotoWidth, height:diplomaPhotoHeight}"></canvas>
		<canvas canvas-id="teacherPhoto" class="profilePhotoClass" :style="{width:profilePhotoWidth, height:profilePhotoHeight}"></canvas> -->
		<view class="submitBtnWrapper">
			<button class="submitBtn" type="primary" @click="submit">{{buttonMessage}}</button>
		</view>
		
		<!-- 裁剪图片的插件 -->
		<ksp-cropper mode="free" :width="1024" :height="1024" :maxWidth="1024" :maxHeight="1024" :url="idCardFrontUrl" @cancel="urloncancel('idCardFront')" @ok="urlonok('idCardFront', $event)"></ksp-cropper>
		<ksp-cropper mode="free" :width="1024" :height="1024" :maxWidth="1024" :maxHeight="1024" :url="idCardBackUrl" @cancel="urloncancel('idCardBack')" @ok="urlonok('idCardBack', $event)"></ksp-cropper>
		<ksp-cropper mode="free" :width="1024" :height="1024" :maxWidth="1600" :maxHeight="1600" :url="diplomaPhotoUrl" @cancel="urloncancel('diplomaPhoto')" @ok="urlonok('diplomaPhoto', $event)"></ksp-cropper>
		<ksp-cropper mode="fixed" :width="160" :height="160" :maxWidth="1024" :maxHeight="1024" :url="teacherPhotoUrl" @cancel="urloncancel('teacherPhoto')" @ok="urlonok('teacherPhoto', $event)"></ksp-cropper>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex'
	export default {
		computed: {
			...mapState('m_user', ['authentication']),
		},
		data() {
			return {
				disabledPhone: true,
				listStyle: {
					"height": 100,	// 边框高度
					"width": 100,	// 边框宽度
					"border":{ // 如果为 Boolean 值，可以控制边框显示与否
						"color":"#ccc",		// 边框颜色
						"width":"1px",		// 边框宽度
						"style":"solid", 	// 边框样式
					}
				},
				idCardFrontUrl: '',
				idCardBackUrl: '',
				diplomaPhotoUrl: '',
				teacherPhotoUrl: '',
				// idCardFrontWidth: 0,
				// idCardFrontHeight: 0,
				// idCardBackWidth: 0,
				// idCardBackHeight: 0,
				// diplomaPhotoWidth: 0,
				// diplomaPhotoHeight: 0,
				// profilePhotoWidth: 0,
				// profilePhotoHeight: 0,
				fileExtname: 'png,jpg',
				sizeType: ['compressed'],
				idCardFrontByte: [{
					url: '',
					extname: '',
					name: ''
				}],
				idCardBackByte: [{
					url: '',
					extname: '',
					name: ''
				}],
				teacherPhotoByte: [{
					url: '',
					extname: '',
					name: ''
				}],
				diplomaPhotoByte: [{
					url: '',
					extname: '',
					name: ''
				}],
				buttonMessage: '申请认证',
				isLoading: false, // 节流阀
				baseFormData: {
					name: '',
					weixinId: '',
					phone: '',
					idCard: '',
					sex: '男',
					identify: '专职老师',
					school: '',
					major: '',
					education: '',
					nativePlace: '',
					education: '本科在读',
					idCardFront: '',
					idCardBack: '',
					diplomaPhoto: '',
					teacherPhoto: '',
					graduateMonth: '',
					teacherPhotoTemp: ''
				},
				sexs: [{
					text: '男',
					value: '男'
				}, {
					text: '女',
					value: '女'
				}],
				// 单选老师身份
				identifies: [{
					text: '专职老师',
					value: '专职老师'
				}, {
					text: '在校大学生',
					value: '在校大学生'
				}],
				educations:[ {
					value: '专科毕业',
					text: '专科毕业'
				}, {
					value: '本科毕业',
					text: '本科毕业'
				}, {
					value: '硕士毕业',
					text: '硕士毕业'
				}, {
					value: '博士毕业',
					text: '博士毕业'
				}, {
					value: '专科在读',
					text: '专科在读'
				},  {
					value: '本科在读',
					text: '本科在读'
				}, {
					value: '硕士在读',
					text: '硕士在读'
				},  {
					value: '博士在读',
					text: '博士在读'
				}],
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					weixinId: {
						rules: [{
							required: true,
							errorMessage: '请输入微信号',
						}, {
							errorMessage: '请输入正确的微信号',
							pattern: '^[a-zA-Z][a-zA-Z\\d_-]{5,19}$',
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号',
						}, {
							errorMessage: '请输入正确的手机号',
							pattern: '^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$',
						}]
					},
					idCard: {
						rules: [{
							required: true,
							errorMessage: '请输入身份证号',
						}, {
							errorMessage: '请输入正确的身份证号',
							pattern: '^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$',
						}]
					},
					school: {
						rules: [{
							required: true,
							errorMessage: '请输入学校全称',
						}]
					},
					major: {
						rules: [{
							required: true,
							errorMessage: '请输入专业名称',
						}]
					},
					graduateMonth: {
						rules: [{
							required: true,
							errorMessage: '请选择全日制学历毕业年月',
						}]
					},
					nativePlace: {
						rules: [{
								required: true,
								errorMessage: '请输入籍贯',
							},
							{
								pattern: '[\\u4e00-\\u9fa5]+[\\u7701]{1}[\\u4e00-\\u9fa5]+[\\u5E02]{1}[\\u4e00-\\u9fa5]+[\\u53BF|\\u533A]{1}',
								errorMessage: '请输入正确的格式：xx省xx市xx区/县',
							}
						]
					}
				}
			};
		},
		onLoad(option) {
			if (option.item) {
				this.baseFormData = JSON.parse(decodeURIComponent(option.item))
				this.buttonMessage = '修改认证'
				this.getPhotoes()
			} else {
				this.idCardFrontByte = [],
				this.idCardBackByte = [],
				this.teacherPhotoByte = [],
				this.diplomaPhotoByte = [],
				this.buttonMessage = '申请认证'
			}
		},
		methods: {
			...mapMutations('m_user', ['updateAuthentication']),
			
				        bindDateChange: function(e) {
				            this.baseFormData.graduateMonth = e.target.value
						
				        },
						getCurrentMonth () {
							const date = new Date()
				            let year = date.getFullYear()
				            let month = date.getMonth() + 1
							month = month > 9 ? month : '0' + month
							console.log(`${year}-${month}`)
							return `${year}-${month}`
						},

			// 获取图片
			async getPhotoes() {
				this.diplomaPhotoByte[0].url = this.baseFormData.diplomaPhoto
				this.diplomaPhotoByte[0].name = 'diplomaPhoto'
				this.idCardBackByte[0].url = this.baseFormData.idCardBack
				this.idCardBackByte[0].name = 'idCardBack'
				if(this.baseFormData.verifyStatus == "审核中"){
					this.teacherPhotoByte[0].url = this.baseFormData.teacherPhotoTemp
				}else{
					this.teacherPhotoByte[0].url = this.baseFormData.teacherPhoto
				}
				this.teacherPhotoByte[0].name = 'teacherPhoto'
				this.idCardFrontByte[0].url = this.baseFormData.idCardFront
				this.idCardFrontByte[0].name = 'idCardFront'
			},
			// 手机号
			async getPhoneNumber(e) {
				if (e.detail.code === undefined) return uni.$showMsg('获取手机号失败！')
				const query = {
					code: e.detail.code
				}
				const {
					data: result
				} = await uni.$http.get('/ucenter/mini-program-openid-uid/wxGetPhone', query)
				if (result.data.phone === '' || result.data.phone === null) {
					this.disabledPhone = false
					return uni.$showMsg('手机号获取失败,请手动输入')
				} else {
					this.baseFormData.phone = result.data.phone
					return uni.$showMsg('获取手机成功！')
				}
			},
			deletePhoto(item,e) {
				// console.log("删除",item)
				this.baseFormData[item] = ''
			},
			// 上传身份证正面
			selectPhoto(item,e) {
				// console.log('上传',item)
				switch(item) {
					case 'idCardFront':
						this.idCardFrontByte = []
						this.idCardFrontUrl = e.tempFilePaths[0]
						break
					case 'idCardBack':
						this.idCardBackByte = []
						this.idCardBackUrl = e.tempFilePaths[0]
						break
					case 'diplomaPhoto':
						this.diplomaPhotoByte = []
						this.diplomaPhotoUrl = e.tempFilePaths[0]
						break
					case 'teacherPhoto':
						this.teacherPhotoByte = []
						this.teacherPhotoUrl = e.tempFilePaths[0]
						break
				}
			},
			urlonok(item,ev) {
				// console.log('裁剪',item)
				const evPath = ev.path
				switch(item) {
					case 'idCardFront':
						this.idCardFrontByte = {
							url: evPath
						}
						this.idCardFrontUrl = ''
						this.upload(evPath, 'idCardFront')
						break
					case 'idCardBack':
						this.idCardBackByte = {
							url: evPath
						}
						this.idCardBackUrl = ''
						this.upload(evPath, 'idCardBack')
						break
					case 'diplomaPhoto':
						this.diplomaPhotoByte = {
							url: evPath
						}
						this.diplomaPhotoUrl = ''
						this.upload(evPath, 'diplomaPhoto')
						break
					case 'teacherPhoto':
						this.teacherPhotoByte = {
							url: evPath
						}
						this.teacherPhotoUrl = ''
						this.upload(evPath, 'teacherPhoto')
						break
				}
			},
			urloncancel(item) {
				// console.log('取消',item)
				switch(item) {
					case 'idCardFront':
						this.idCardFrontByte = null
						// url设置为空，隐藏控件
						this.idCardFrontUrl = "";
						break
					case 'idCardBack':
						this.idCardBackByte = null
						this.idCardBackUrl = "";
						break
					case 'diplomaPhoto':
						this.diplomaPhotoByte = null
						this.diplomaPhotoUrl = "";
						break
					case 'teacherPhoto':
						this.teacherPhotoByte = null
						this.teacherPhotoUrl = "";
						break
				}
			},
			upload(path, item) {
				wx.uploadFile({
					url: uni.$http.baseUrl + '/file/uploading',
					filePath: path,
					name: 'file',
					header: {
						token: uni.getStorageSync('token'),
						picName: item
					},
					success: res => {
						const result = JSON.parse(res.data)
						this.baseFormData[item] = result.data.url
					},
					fail: res => {
						if (res.errno === 1001) {
							uni.$showMsg('只能选择.jpg或者.png的图片')
						}
					}
				})
			},
			submit() {
				if (this.isLoading) {
					return uni.$showMsg('操作过快,请耐心等待…')
				}
				this.isLoading = true
				this.$refs.baseForm.validate().then(res => {
					if (this.baseFormData.phone === undefined || this.baseFormData.phone === '') return uni.$showMsg('手机号未获取！')
					if (this.baseFormData.idCardFront === undefined || this.baseFormData.idCardFront === '') return uni.$showMsg('身份证正面未上传！')
					if (this.baseFormData.idCardBack === undefined || this.baseFormData.idCardBack === '') return uni.$showMsg('身份证背面未上传！')
					if (this.baseFormData.diplomaPhoto === undefined || this.baseFormData.diplomaPhoto === '') return uni.$showMsg('学生/毕业证未上传！')
					if (this.baseFormData.teacherPhoto === undefined || this.baseFormData.teacherPhoto === '') return uni.$showMsg('头像未上传！')
					if (this.baseFormData.education === undefined || this.baseFormData.education === '') return uni.$showMsg('请选择学历')
					if (this.buttonMessage === '修改认证') {
						const certificationUrl = '/education/teacher-certifications/updateCertificationInfo'
						this.sendRequest(certificationUrl, 2)
						
					} else {
						const certificationUrl = '/education/teacher-certifications/saveCertificationInfo'
						this.sendRequest(certificationUrl, 1)
					}
				}).catch(err => {

					this.isLoading = false
				})
				this.isLoading = false
			},
			sendRequest(certificationUrl, count) {
				uni.request({
					url: uni.$http.baseUrl + certificationUrl,
					data: this.baseFormData,
					header: {
						token: uni.getStorageSync('token')
					},
					method: 'POST',
					success: res => {
						this.isLoading = false
						uni.$showMsg(res.data.message)
						this.updateAuthentication('审核中')
						setTimeout(() => {
							// uni.navigateBack({
							// 	delta: count
							// })
							uni.navigateTo({
								url: '/subpkg/teacher/authentication/teacher_authentication'
							})
						}, 1000)
					}
				})
			}
		}
	}
</script>

<!-- 设置页面背景 -->
<style lang="scss">
	page{
		height: 100%;
		//background-color: #FFF2CC;
	}
</style>

<style lang="scss" scoped>
	.idCardFrontClass {
		position: absolute;
		left:-8000px;
		top:-8000px;
	}
	
	.idCardBackClass {
		position: absolute;
		left:-9000px;
		top:-9000px;
	}
	
	.diplomaPhotoClass {
		position: absolute;
		left:-7000px;
		top:-7000px;
	}
	
	.profilePhotoClass {
		position: absolute;
		left:-6000px;
		top:-6000px;
	}
	
.auth-Container{
	width: 96%;
	height: 100%;
	padding-left: 20rpx;
	font-size: 30rpx;
}

.warning {
	color: red
}


	// 提交按钮样式
	.submitBtnWrapper{
		height: 140rpx;
		align-items: center;
	}
	.submitBtn{
		width: 300rpx;
		border-radius: 50rpx;
		// margin-bottom: 40rpx;
		background-color: #35b882;
		font-size: 30rpx;
	}

	
	// 获取手机号按钮背景颜色
	.getPhone{
			    font-size: 30rpx;
				border-radius: 40rpx;
				background-color: #35b882;
				//font-weight: bold;
				color: #FFF;
				//padding: 10rpx;
	}
		.phoneClass {
		margin-top: 6rpx;
	}
	.uni-input{
		//border: 1rpx solid;
		background-color: #FFF;
		height: 80rpx;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
	}
</style>
