<template>
	<view class="page-container ">
		<u-nav-bar title="特别申请" bg="#007aff" ref="uNavBar" />
		<view class="u-bg" />
		<view class="u-disabled-mask" v-if="false" />
		<view class="main-content">
			<u-panel v-if="form.notice">
				<u-des-row label="注意事项" />
				<view class="notice-tip" v-html="form.notice" />
			</u-panel>
			<u-panel>
				<u-des-row label="姓名" :value="userInfo.studentName" border />
				<u-des-row label="性别" :value="userInfo.genderName" border />
				<u-des-row label="班级" :value="userInfo.gradeName" border />
				<u-des-row label="学号" :value="userInfo.studentNO" border />
				<u-des-row label="联系电话" eye>
					<view slot="value" slot-scope="{isOpen}">
						{{isOpen ? userInfo.mobileNo : hideCode(userInfo.mobileNo, 3,4) }}
					</view>
				</u-des-row>
			</u-panel>
			<u-panel>
				<u-des-row label="绩点" :value="form.avgScore.toFixed(2)" border />
				<u-des-row label="专业群排名" :value="form.avgScoreRank" border />
				<u-picker v-model="form.majorId" label-key="majorName" value-key="majorId" :options="majorOptions">
					<u-des-row slot-scope="{data}" label="申请专业" :value="data.majorName || '请选择'"
						:style="{opacity: data.majorName?1:0.5}" border />
				</u-picker>
				<u-des-row label="申请原因" />
				<uni-easyinput type="textarea" autoHeight  :maxlength="300" v-model="form.applyReason" placeholder="请输入详细的申请原因哦(最多300字)~">
				</uni-easyinput>
			</u-panel>
			<u-panel style="padding-top:24rpx;">
				<!-- <u-des-row label="附件" :value="form.attachmentList.length + '/9'" /> -->
				<uni-file-picker v-model="form.attachmentList" @select="imgSelect" fileMediatype="image"
					file-extname="png,jpg" :auto-upload="false" mode="grid" :limit="9" title="附件">
					<view class="choose-image u-flex-center">
						<image src="/static/upload_icon.png" style="width: 70rpx;height: 60rpx;" mode=""></image>
						<view class="choose-image-tip">上传图片</view>
					</view>
				</uni-file-picker>
			</u-panel>
			<u-panel>
				<u-des-row label="学生签名" @click="toSign(1)">
					<image slot="value" style="width: 34rpx;height: 30rpx;" src="/static/sign_icon.png"
						mode="widthFix" />
				</u-des-row>
				<view v-if="form.studentSign" class="u-sign-preview">
					<image :src="form.studentSign" style="width: 100%;height: 100%;" mode="widthFix"></image>
					<view class="icon-clear u-flex-center" @click="form.studentSign=''">
						<uni-icons type="closeempty" size="15" color="white" />
					</view>
				</view>
				<view v-else class="sign-tip">填写完信息请点击签字笔完成签名哦~</view>
			</u-panel>
			<view class="u-flex" style="margin: 96rpx 0 32rpx;">
				<view class="u-button save-button" :class="{'disabled':disabledSave}" @click="!disabledSave && onSumbit(1)">
					暂存
				</view>
				<view style="width:20rpx">
				</view>
				<button class="u-button sumbit-button" :class="{'disabled':disabledSumbit}" @click="!disabledSumbit && onSumbit(2)">
					{{form.applyStatus >= 1 ? '已提交' : '提交'}}
				</button>
			</view>
		</view>
		<u-drawer :visible.sync="visible" title="手写签名" @sumbit="signSumbit" @cancel="visible=false">
			<view v-if="false" class="drawer-tip">
				<text class="empty-2"></text>
				<text>本人已仔细阅读专业分流并理解了有关要求和规定，在此我郑重承诺：“本人自愿按以上顺序选择专业，服从调剂，且专业分流后不再变更。
					对违反以上承诺所造成的后果，本人自愿承担相应责任。”</text>
			</view>
			<u-sign ref="uSign" v-if="visible" />
		</u-drawer>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		hideCode
	} from '@/common'
	import formChecker from '@/common/formChecker.js'
	export default {
		data() {
			return {
				majorOptions: [], // majorId majorName
				form: {
					notice: '',
					majorId: '',
					majorName: '',
					applyReason: '',
					attachmentList: [],
					studentSign: '',
					specialApplyId: '',
					applyStatus: '', //0未提交 1已提交 2通过 3驳回
				},
				signType: '',
				visible: false // 签名 抽屉
			}
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
			}),
			disabledSave() {
				return this.form.applyStatus >= 1 // 已提交
			},
			disabledSumbit() {
				return this.form.applyStatus >= 1 || !this.form.specialApplyId // 已提交 或 未缓存
			}
		},
		mounted() {
			this.$ajax.get('/shunt/major-info').then(res => {
				this.majorOptions = res.data || []
			})
			this.init()
		},
		methods: {
			hideCode,
			async init() {
				// 特别申请浏览
				this.$ajax.post('/shunt/special-apply-view').then(res => {
					let attachmentList = res.data.attachmentList || []
					attachmentList = attachmentList.map(item => {
						return {
							path: item,
							url: item,
						}
					})
					Object.assign(this.form, res.data, {
						attachmentList
					})
					console.log(111, this.form)
				})
			},
			imgSelect(res) {
				let error2M = 0
				const newImgs = res.tempFiles.filter(file => {
					const isLt2M = file.size / 1024 / 1024 < 2 
					if(!isLt2M) {
						error2M++
					}
					return isLt2M
				})
				if (error2M) {
					uni.showToast({
						title: `当前选择了${res.tempFiles.length}个文件，${error2M}个文件大于2M`,
						icon: "none"
					});
				}
				console.log(111, newImgs)
				this.form.attachmentList = this.form.attachmentList.concat(newImgs)
			},
			toSign(type) { // 1学生 2家长
				this.signType = type
				this.visible = true
			},
			signSumbit() {
				this.$refs.uSign.getBase64(res => {
					if (this.signType === 1) {
						this.form.studentSign = res?.tempFilePath || ''
					} else {
						this.form.test7 = res?.tempFilePath || ''
					}
					this.visible = false
				})
			},
			// api 
			async onSumbit(type) { // 1:暂存 2:提交
				//定义表单规则
				var rule = [
					// 	{
					// 	name: "avgScore",
					// 	checkType: "notnull",
					// 	errorMsg: "请输入绩点"
					// }, {
					// 	name: "avgScoreRank",
					// 	checkType: "notnull",
					// 	errorMsg: "请输入专业群排名"
					// }, 
					// 
					{
						name: "majorId",
						checkType: "notnull",
						errorMsg: "请输入申请专业"
					}, {
						name: "applyReason",
						checkType: "notnull",
						errorMsg: "请输入申请原因"
					}, {
						name: "attachmentList",
						checkType: "notnull",
						errorMsg: "请添加附件"
					}, {
						name: "studentSign",
						checkType: "notnull",
						errorMsg: "请填写学生签名"
					}
				];

				//进行表单检查
				var checkRes = formChecker.check(this.form, rule);
				if (!checkRes) {
					uni.showToast({
						title: formChecker.error,
						icon: "none"
					});
					return
				}
				await this.uploadFiles()
				const that = this
				uni.showLoading()
				const params = {
					...that.form
				}
				params.attachmentList = params.attachmentList.map(item => item.path)
				that.$ajax.post('/shunt/special-apply', params).then(res => {
					if (type === 1) {
						uni.showToast({
							title: '暂存成功',
							icon: "success"
						});
						that.init()
					}
					uni.hideLoading()
				}).catch(error => {
					uni.hideLoading()
					uni.showModal({
						title: '错误',
						content: error.msg || error,
						showCancel: false
					})
				})
				if (type === 2) {
					uni.showLoading()
					that.$ajax.post('/shunt/special-apply-submit').then(res => {
						uni.showToast({
							title: '提交成功',
							icon: "success"
						});
						that.init()
						uni.hideLoading()
					}).catch(error => {
						uni.hideLoading()
						uni.showModal({
							title: '错误',
								content: error.msg || error,
							showCancel: false
						})
					})
				}

			},
			async uploadFiles(success) {
				uni.showLoading({
					title: '上传文件中...'
				});
				const promiseList = []
				const indexList = []
				const that = this
				that.form.attachmentList.forEach((element, index) => {
					if (element.status) {
						indexList.push(index)
						promiseList.push(uni.uploadFile({
							url: `/shunt/upload`,
							filePath: element.url,
							// fileType: 'image',
							name: 'file',
							header: {
								token: uni.getStorageSync('TOKEN')
							},
							formData: {
								// file: res.tempFiles[0],
								fileType: 'APPLY',
							},
							// success(uploadFileRes) {
							// 	const data = JSON.parse(uploadFileRes.data)
							// 	const filePath = data.data.filePath
							// 	console.log(1111, filePath)
							// 	that.form.attachmentList[index] = filePath
							// }
						}))
					}
				})
				await Promise.all(promiseList).then(resList => {
					resList.forEach((element, index) => {
						let uploadFileRes = element[1]
						const data = JSON.parse(uploadFileRes.data)
						const filePath = data.data.filePath
						const formIndex = indexList[index]
						that.form.attachmentList[formIndex].path = filePath
					})
				})
				uni.hideLoading()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		.u-bg {
			height: 317rpx;
			background: $uni-color-primary;
		}

		.main-content {
			padding: 60rpx 32rpx 32rpx 32rpx;
		}

		.notice-tip {
			font-size: 24rpx;
			font-weight: 400;
			color: #999999;
			line-height: 1.5;
			padding-bottom: 32rpx;
		}

		.sign-tip {
			height: 144rpx;
			font-size: 20rpx;
			font-weight: 400;
			color: #A3ABBF;
		}

		.drawer-tip {
			font-size: 24rpx;
			font-weight: 400;
			line-height: 1.5;
			color: #999999;
			margin-bottom: 36rpx;
		}

		.save-button,
		.sumbit-button {
			flex: 1;
			height: 88rpx;
			background: linear-gradient(90deg, #FFCF18 0%, #FFB300 100%);
			border-radius: 8rpx;

			&.disabled {
				cursor: not-allowed;
				opacity: 0.3;
			}
		}

		.sumbit-button {
			background: linear-gradient(90deg, #36ACFC 0%, #078EF7 100%);
		}

		.choose-image {
			width: 100%;
			height: 100%;
			background: #FFFFFF;
			cursor: pointer;
			text-align: center;
			border: 1rpx dashed #A3ABBF;
			flex-direction: column;

			.choose-image-tip {
				font-size: 24rpx;
				font-weight: 400;
				color: #078EF7;
				margin-top: 24rpx;
			}

		}

	}
</style>
