<template>
	<view class="">
		<view style="padding: 0 20rpx 20rpx;" v-if="appletStatus==1">
			<view class="auth">
				<view class="flex justify-between padding-bottom-30" >
					<view class="flex">
						<image style="width: 35rpx;height: 35rpx;display: block;padding-top: 6rpx;padding-right: 10rpx;" src="../../static/icon/tag1.png" mode=""></image>
						<text class="text-lg text-bold">访客开门申请</text>
					</view>
					<navigator url="records/records" style="font-size: 22rpx;font-weight: 800;"  class="cu-btn base-line sm round">
						<text class="cuIcon-footprint padding-right-sm"></text>
						<text>申请记录</text>
					</navigator>
				</view>
				<view class="card">
					<u-form :model="model"  ref="uForm" >
						<u-form-item :required="true"  :label-width="labelWidth"   label="访问园区" >
							<u-input  type="select" :select-open="agencyShow" v-model="model.agencyName"  placeholder="请选择要访问的园区" @click="agencyShow=true"></u-input>
						</u-form-item>
						<u-form-item  :label-width="labelWidth"   label="访问企业" >
							<u-input  type="select" :select-open="enterpriseShow" v-model="model.enterpriseName" placeholder="请选择要访问的企业" @click="enterpriseShow=true"></u-input>
						</u-form-item>
						<u-form-item :required="true"  :label-width="labelWidth"   label="访问时间" >
							<u-input  type="select" :select-open="interviewTimeShow" v-model="model.interviewTime" placeholder="请选择访问时间" @click="interviewTimeShow=true"></u-input>
						</u-form-item>
						<u-form :model="model"  ref="uForm" >
							<u-form-item :required="true" label-position="top" :border-bottom="false" :label-width="labelWidth"   label="访问缘由" >
								<u-input height="200" v-model="model.guestReason" placeholder="填写访问缘由" type="textarea" :border="border" />
							</u-form-item>
							<!-- <textarea value="" v-model="model.remarks" placeholder="填写备注信息" /> -->
						</u-form>
					</u-form>
				</view>
			</view>
			
			<view class="auth">
				<view class="flex">
					<image style="width: 35rpx;height: 35rpx;display: block;padding-top: 6rpx;padding-right: 10rpx;" src="../../static/icon/tag1.png" mode=""></image>
					<text class="text-lg text-bold">基本信息</text>
				</view>
				<view class="card">
					<u-form :model="model"  ref="uForm" >
						<u-form-item :required="true"  :label-width="labelWidth"  label="姓名" >
							<u-input  placeholder="请输入姓名" v-model="model.guestName" type="text"></u-input>
						</u-form-item>
						<u-form-item  :label-width="labelWidth"   label="性别" >
							<u-input  type="select" :select-open="sexSelectShow" v-model="sexSelectList[sexSelectIndex].text" placeholder="请选择性别" @click="sexSelectShow = true"></u-input>
						</u-form-item>
						<u-form-item  :required="true" label="手机号码"  :label-width="labelWidth">
							<u-input maxlength="11"  placeholder="请输入手机号" v-model="model.guestTel" type="number"></u-input>
						</u-form-item>
						<u-form-item   label="身份证号"  :label-width="labelWidth">
							<u-input maxlength="18"  placeholder="请输入身份证号" v-model="model.guestIdcard" ></u-input>
						</u-form-item>
					</u-form>
				</view>
			</view>
			
			<view class="auth">
				<view class="flex">
					<image style="width: 35rpx;height: 35rpx;display: block;padding-top: 6rpx;padding-right: 10rpx;" src="../../static/icon/tag1.png" mode=""></image>
					<text class="text-lg text-bold">人脸信息采集（可选）</text>
				</view>
				<view  style="font-size: 28rpx;padding: 20rpx 0 10rpx 30rpx;">
					<text class="text-red text-bold">*</text>
					<text style="color: #797979;">人脸照片用于人脸识别开门</text>
				</view>
				<view class="card">
					<view @click="faceSelectShow=true" class="flex justify-center padding-bottom-50">
						<view  :class="$isNotEmpty(model.imageUri)?'padding-top-30':''">
							<upload-img
							   :width="$isEmpty(model.imageUri)?350:560"
							   :height="$isEmpty(model.imageUri)?350:420"
							  :currentImage="model.imageUri"
							  bgsrc="https://vote-obs.guosen-fumao.cn/c683bfabcdfe4306adb96bb1605394b6-face1%5B0%5D.png"
							  >
							</upload-img>
							<view class="text-center  padding-top-20 base-color" >
							 <text class="cuIcon-camera padding-right-sm" style="font-size: 30rpx;"></text>
							 <text v-if="$isEmpty(model.imageUri)">点击上传人脸</text>
							 <text style="margin-top: 40rpx;display: inline-block;" v-else>点击重新上传</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		
			<button @click="submit" :style="{marginBottom:safeAreaBottom}"   class="cu-btn base-bg-color round flex" style="padding: 40rpx 0;margin-top: 40rpx;">
				<text >提交申请</text>
			</button>
			<!-- 性别 -->
			<u-picker v-model="sexSelectShow" @confirm="sexSelectCallback" :range="sexSelectList" range-key="text" mode="selector"></u-picker>
			
			<!-- 园区 -->
			<u-popup  border-radius="8" height="60%"  mode="bottom" v-model="agencyShow">
				<view class="fixed cu-bar search bg-white">
					<view class="search-form round">
						<text class="cuIcon-search"></text>
						<u-input style="width: 90%;" v-model="agencyKeyWord" type="text" :adjust-position="false" placeholder="请输入关键字搜索" confirm-type="search"/>
					</view>
				</view>
				<scroll-view v-if="!$isEmpty(agencyList)"  style="padding-top: 110rpx;height: 100%;" :scroll-y="true" >
					<view @click="selectAgency(item)" hover-class="hoverClass" class="text-center padding-30 solid-bottom"  v-for="(item,index) in agencyList" :key="index">
						<text>{{item.agencyName}}</text>
					</view>
					<u-divider v-if="agencyList.length>=20" height="80">只显示20条数据</u-divider>
				</scroll-view>
				<u-empty v-else name="search"></u-empty>
			</u-popup>
			
			<!-- 企业列表 -->
			<u-popup  border-radius="8" height="60%"  mode="bottom" v-model="enterpriseShow">
				<view class="fixed cu-bar search bg-white">
					<view class="search-form round">
						<text class="cuIcon-search"></text>
						<u-input style="width: 90%;" v-model="enterpriseKeyword" type="text" :adjust-position="false" placeholder="请输入关键字搜索" confirm-type="search"/>
					</view>
				</view>
				<scroll-view v-if="!$isEmpty(enterpriseList)" style="padding-top: 110rpx;height: 100%;" :scroll-y="true" >
					<view @click="selectEnterprise(item)" hover-class="hoverClass" class="text-center padding-30 solid-bottom"  v-for="(item,index) in enterpriseList" :key="index">
						<text>{{item.enterpriseName}}</text>
					</view>
					<u-divider v-if="enterpriseList.length>=20" height="80">只显示20条数据</u-divider>
				</scroll-view>
				<u-empty v-else name="search"></u-empty>
			</u-popup>
			
			<!-- 访问时间 -->
			<u-picker @confirm="interviewTimeConfirm" :params="params" v-model="interviewTimeShow" mode="time"></u-picker>
			<u-action-sheet @click="faceSelectCallback"  z-index="999999" :list="faceSelectList" v-model="faceSelectShow"></u-action-sheet>
		</view>
		<view v-else>
			
		</view>
	</view>
</template>

<script>
	import uploadImg from '@/components/uploadimg/uploadImg.vue'
	let that;
	export default {
		components:{
		   uploadImg
		},
		data() {
			return {
				//0 体验版 1正式版
				appletStatus:0,
			
				labelWidth:'200',
				model: {
					openId:'',
					agencyId:'',
					enterpriseId:'',
					guestName:'',
					guestTel:'',
					guestSex:'1',//1 男 2 女
					guestIdcard:'',//身份证号
					guestReason:'',//访问缘由
					interviewTime:'',//访问时间
					imageUri:''
				},
				//访问时间
				interviewTimeShow:false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				//性别
				sexSelectList: [{text: '男',value:1},{text: '女',value:2}],
				sexSelectShow: false,
				sexSelectIndex:0,
				
				//园区下拉框
				agencyList:[],
				agencyKeyWord:'',
				agencyShow:false,
				
				//企业下拉框
				enterpriseShow:false,
				enterpriseList:[],
				enterpriseKeyword:'',
				
				//上传人脸的方式
				faceSelectList: [{
					text: '相册上传',
				}, {
					text: '拍照上传'
				}],
				faceSelectShow:false,
			}
		},
		watch:{
			agencyKeyWord(){
				let that=this
				//节流函数
				if (this.timer){
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					that.agencyList=[]
					that.getAgencyList()
				}, 500)
			},
			enterpriseKeyword(){
				let that=this
				//节流函数
				if (this.timer){
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					that.enterpriseList=[]
					that.getEnterpriseList()
				}, 500)
			},
		},
		computed: {
		  //ios底部安全区域
		  safeAreaBottom() {
		    let info = uni.getSystemInfoSync()
		    let safe = 20
		    if (
		      info &&
		      ['devtools', 'ios'].includes(info.platform) &&
		      info.statusBarHeight > safe
		    ) {
		      return info.statusBarHeight - safe+'px'
		    }
		    return 0
		  }
		},
		onShow() {
			this.handelAppletAudit()
			
			let currPage=this.getPageCtx()
			if (!this.$isEmpty(currPage.data.image)) {
				this.uploadFile(currPage.data.image)
			}
		},
		
		onLoad(options) {
			that=this
			//拉取园区列表
			this.getAgencyList()
			this.getEnterpriseList()
			
			if (!this.$isEmpty(options.agencyId)&&!this.$isEmpty(options.agencyName)) {
				this.model.agencyId=options.agencyId
				this.model.agencyName=options.agencyName
			}
			if (!this.$isEmpty(options.enterpriseId)&&!this.$isEmpty(options.enterpriseName)) {
				this.model.enterpriseId=options.enterpriseId
				this.model.enterpriseName=options.enterpriseName
			}
			
			if (!this.$isEmpty(options.interviewTime)&&!this.$isEmpty(options.interviewTime)) {
				this.model.interviewTime=options.interviewTime
			}
			if (!this.$isEmpty(options.openId)) {
				this.model.openId=options.openId
			}else{
				//获取openid
				this.getOpenid()
			}
		},
		methods: {
			handelAppletAudit(){
				this.appletStatus=uni.getStorageSync("appletStatus")
				if (this.appletStatus==1) {
					uni.setNavigationBarTitle({
						title:'申请开门'
					})
				}else{
					uni.setNavigationBarTitle({
						title:'待开发'
					})
				}
			},
			/**
			 * 获取openid
			 */
			getOpenid(){
				uni.login({
					success: (res) => {
						let data={
							appId:this.$api.wxData.appId,
							jsCode:res.code,
							secret:this.$api.wxData.secret
						}
						this.$api.wxApi.getOpenId(data).then(res=>{
							let resData= JSON.parse(res.data)
							this.model.openId=resData.openid
							if (this.$isEmpty(this.model.openId)) {
								uni.showModal({
									content:"系统错误，获取openid失败",
									showCancel:false,
									success() {
										uni.reLaunch({
											url:"/pages/login/login"
										})
									}
								})
							}
						})
					}
				})
			},
			//获取园区列表
			getAgencyList(){
				let params={
					size:20,
					agencyName:this.agencyKeyWord
				}
				this.$api.agency.getAgencyTenantList(params).then(res=>{
					this.agencyList = res.data
				})
			},
			//选择园区
			selectAgency(item){
				let params={
					tenant_id:item.tenantId,
					username:item.account,
					password:item.password,
					grant_type: "password"
				}
				this.model.agencyId=item.id
				this.model.agencyName=item.agencyName
				this.agencyShow=false
				this.$cache.put('tokenObj',params)
				//获取token
				this.$api.getToken(this.$u.queryParams(params)).then(res=>{
					let token=res.token_type+" "+res.access_token
					uni.setStorageSync('token', token)
					//获取企业列表
					this.getEnterpriseList()
				})
				
			},
			//获取企业列表
			getEnterpriseList(){
				let params={
					size:20,
					enterpriseName:this.enterpriseKeyword
				}
				this.$api.enterprise.page(params).then(res=>{
					this.enterpriseList =res.data.records
				})
			},
			//选择企业
			selectEnterprise(item){
				this.enterpriseShow=false
				this.model.enterpriseName=item.enterpriseName
				this.model.enterpriseId=item.id
			},
			
			/**
			 * 获取页面对象
			 */
			getPageCtx(idx = 0){
			  let pages = getCurrentPages()
			  if (pages.length > 0) {
			    return pages[pages.length - 1 - idx] || {}
			  }
			  return {}
			},
			//性别
			sexSelectCallback(e) {
				uni.hideKeyboard();
				this.sexSelectIndex=e[0]
				this.model.guestSex=this.sexSelectList[this.sexSelectIndex].value
			},
			//访问时间
			interviewTimeConfirm(e){
				this.model.interviewTime=e.year+'-'+e.month+'-'+e.day
			},
			//人脸上传
			faceSelectCallback(index){
				if (index==0) {
					//图片上传
					this.chooseImage()
				} else if(index==1){
					//拍照上传
					uni.navigateTo({
						url:'/pages/my-camera/my-camera'
					})
				}
			},
			//点击上传图片事件
			chooseImage: function () {
			  uni.chooseImage({
			    count: 1,
			    //最多可以选择的图片张数，默认9
			    sourceType: ['album'],
			    sizeType: ['compressed'],
			    //可选择原图或压缩后的图片
			    success: res => {
			      that.uploadFile(res.tempFilePaths[0])
			    }
			  });
			},
			//处理照片，拍照上传和相册上传的共同处理方法
			uploadFile(imgUrl){
				this.$api.uploadFile.submit(imgUrl).then(res=>{
					that.model.imageUri=res.data.link
				})
			},
			async send(openId){
				let tokenData={
					grantType:this.$api.wxData.subscribe_grant_type,
					appId:this.$api.wxData.appId,
					secret:this.$api.wxData.secret
				}
				let res=await this.$api.wxApi.getAccessToken(tokenData)
				let token=JSON.parse(res.data).access_token
				let subscribeData={
					accessToken:token,
					touser:openId,
					lang:"zh_CN",
					page:'/pages/guest/records/records',
					miniprogramState:this.$miniprogramState,
				    templateId: this.$adminTmplIds[1],
					  "data": {
						  "thing1": {
							  "value": this.model.guestName
						  },
						  "phone_number2":{
							  "value": this.model.guestTel
						  },
						  "thing4": {
							  "value": this.model.agencyName
						  },
						  "thing3": {
							  "value": this.model.guestReason
						  },
					}
				}
				let resp=await this.$api.wxApi.subscribe(subscribeData)
				console.log(resp);
			},
			async getOpenListAndSendMsg(){
				let agencyRes=await this.$api.getManagerOpenList({agencyId:this.model.agencyId})
				let enterpriseRes=await this.$api.getManagerOpenList({enterpriseId:this.model.enterpriseId})
				let openIds=[...agencyRes.data,...enterpriseRes.data]
				openIds.forEach(item=>{
					this.send(item)
				})
			},
			async submit(){
				await this.$mpi.subscribe(that.$staffTmplIds)
				if (this.$isEmpty(this.model.agencyId)) {
					this.$u.toast('请选择要访问的园区')
					return
				}
				if (this.$isEmpty(this.model.interviewTime)) {
					this.$u.toast('请选择访问时间')
					return
				}
				if (this.$isEmpty(this.model.guestReason)) {
					this.$u.toast('请填写访问缘由')
					return
				}
				if (this.$isEmpty(this.model.guestName)) {
					this.$u.toast('请填写姓名')
					return
				}
				if (this.$isEmpty(this.model.guestTel)) {
					this.$u.toast('请填写手机号')
					return
				}
				if (!this.$verify.isMobile(this.model.guestTel)) {
					this.$u.toast('请填写正确的手机号')
					return
				}
				if (!this.$isEmpty(this.model.guestIdcard)) {
					if (!this.$u.test.idCard(this.model.guestIdcard)) {
						this.$u.toast('请输入正确的身份证号')
						return
					}
				}
				this.$api.guest.submit(this.model).then(res=>{
					if (res.success) {
						uni.showModal({
							content:'操作成功，请耐心等待管理员审核',
							showCancel:false,
							success() {
								that.getOpenListAndSendMsg()
								that.model={
									openId:'',
									agencyId:'',
									agencyName:'',
									enterpriseId:'',
									enterpriseName:'',
									guestName:'', 
									guestSex:'',//1 男 2 女
									guestIdcard:'',//身份证号
									guestReason:'',//访问缘由
									interviewTime:'',//访问时间
									imageUri:''
								}
							}
						})
					}
				})
			},
		},
		
		/**打开设置页
		 * 方法可以不实现，但是不可以不写
		 */
		opensetting(){
			
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #FFFFFF;
	}
	.auth{
		padding: 40rpx 10rpx;
		.card{
			margin-top: 20rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			border-radius: 12rpx;
			box-shadow: 0 -10rpx rgba(248, 248, 248,.9) ,0 10rpx rgba(248, 248, 248,.9) , -10rpx 0rpx rgba(248, 248, 248,.9) ,10rpx 0rpx rgba(248, 248, 248,.9);
			.item{
				padding:30rpx 0;
				display: flex;
				justify-content: space-between;
			}
		}
	}
</style>
