<template>
	<view class="">
		<view style="padding: 0 20rpx 20rpx;" v-if="appletStatus==1">
			<u-top-tips type="info" ref="uTips"></u-top-tips>
			<u-alert-tips :show="show" type="warning" title="审核意见" :close-able="true"  :description="opinion"></u-alert-tips>
			<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>
				</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.realName" type="text"></u-input>
						</u-form-item>
						<u-form-item :required="true" :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="18"  placeholder="请输入身份证号" v-model="model.idcard" ></u-input>
						</u-form-item>
						<u-form-item :required="true"  label="手机号码"  :label-width="labelWidth">
							<u-input maxlength="11" disabled  placeholder="请输入手机号" v-model="model.phone" type="number"></u-input>
						</u-form-item>
						<u-form-item :required="true" :border-bottom="false"  label="脸部信息采集"  :label-width="labelWidth"></u-form-item>
					</u-form>
					
					<view @click="faceSelectShow=true" class="flex justify-center padding-bottom-50">
						<view class=" ">
							<upload-img
							   :width="$isEmpty(model.face)?350:560"
							   :height="$isEmpty(model.face)?350:420"
							  :currentImage="model.face"
							  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.face)">点击上传人脸</text>
							 <text style="margin-top: 40rpx;display: inline-block;" v-else>点击重新上传</text>
							</view>
						</view>
					</view>
				</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>
				</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="ganderSelectShow" v-model="gander"  placeholder="请选择工作园区" @click="ganderShow"></u-input>
						</u-form-item>
						<u-form-item :required="true" :label-width="labelWidth"   label="园区区域" >
							<u-input  type="select" :select-open="residentialSelectShow" v-model="residential"  placeholder="请选择园区区域" @click="residentialShow"></u-input>
						</u-form-item>
						<u-form-item :required="true" :label-width="labelWidth"   label="所属企业" >
							<u-input  type="select" :select-open="companySelectShow" v-model="company" placeholder="请选择所属企业" @click="companyShow"></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>
				</view>
				<view class="card">
					<u-form :model="model"  ref="uForm" >
						<u-form-item label-position="top" :border-bottom="false" :label-width="labelWidth"   label="备注(可选)" >
							<u-input height="200" v-model="model.remarks" placeholder="填写备注信息" type="textarea" :border="border" />
						</u-form-item>
						<!-- <textarea value="" v-model="model.remarks" placeholder="填写备注信息" /> -->
					</u-form>
				</view>
			</view>
			
			<!-- <view class="auth flex justify-between">
				<view class="flex flex-direction">
					<view class="">
						<text style="font-size: 34rpx;" class="cuIcon-noticefill  base-color padding-right-10"></text>
						<text class="text-lg">消息通知提醒</text>
					</view>
					<view class="padding-top-10 text-sm text-gray">
						<text>开启订阅后，认证审核通知将推送到您的微信上</text>
					</view>
				</view>
				<button v-if="subscribeShow" @click="subscribe" class="cu-btn sm round base-bg-color">
					订阅
				</button>
				<button v-else @opensetting="opensetting" open-type="openSetting"class="cu-btn sm round base-bg-color">
					订阅
				</button>
			</view> -->
			<button @click="submit" v-if="canIUseGetUserProfile" :style="{marginBottom:safeAreaBottom}"   class="cu-btn base-bg-color round flex" style="padding: 40rpx 0;margin-top: 40rpx;">
				<text v-text="operationType==0?'提交':'重新审核'"></text>
			</button>
			
			<button v-else :style="{marginBottom:safeAreaBottom}" open-type="getUserInfo" @getuserinfo="submit"  class="cu-btn base-bg-color round flex" style="padding: 40rpx 0;margin-top: 40rpx;">
				<text v-text="operationType==0?'提交':'重新审核'"></text>
			</button>
			
			
			
			<!-- 性别 -->
			<u-picker v-model="sexSelectShow" @confirm="sexSelectCallback" :range="sexSelectList" range-key="text" mode="selector"></u-picker>
			<!-- 园区 -->
			<u-picker v-model="ganderSelectShow" @confirm="ganderSelectCallback" :range="ganderSelectList" range-key="name" mode="selector"></u-picker>
			<!-- 区域 -->
			<u-picker v-model="residentialSelectShow" @confirm="residentialSelectCallback" :range="residentialSelectList" range-key="name" mode="selector"></u-picker>
			<!-- 企业 -->
			<u-popup  border-radius="8" height="60%"  mode="bottom" v-model="companySelectShow">
				<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="keyword" type="text" :adjust-position="false" placeholder="请输入关键字搜索" confirm-type="search"/>
					</view>
					<!-- <view @click="fetchEnterpriseList" class="action">
						<button class="cu-btn bg-blue shadow-blur round">搜索</button>
					</view> -->
				</view>
				<scroll-view v-if="!$isEmpty(companySelectList)" @scrolltolower="scrolltolower" style="padding-top: 110rpx;height: 100%;" :scroll-y="true" >
					<view @click="companySelectCallback(item)" hover-class="hoverClass" class="text-center padding-30 solid-bottom"  v-for="(item,index) in companySelectList" :key="index">
						<text>{{item.enterpriseName}}</text>
					</view>
					<u-divider v-if="flag" height="80">没有更多了</u-divider>
				</scroll-view>
				<u-empty v-else name="search"></u-empty>
			</u-popup>
			<!-- <u-picker v-model="companySelectShow" @confirm="companySelectCallback" :range="companySelectList" range-key="enterpriseName" mode="selector"></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,
				
				open:false,
				
				// 0:用户认证 1:重新审核
				operationType:0,
				phone:'',//当operationType为1时需要传过来
				opinion:'',//审核不通过时的审核意见
				show:false,//当有审核意见时才显示
				
				labelWidth:'200',
				model: {
					avatar:'',
					name:'',//昵称
					openId:'',
					realName: '',
					enterpriseId:'',
					enterpriseName:'',
					face:'',
					sex: '',	//性别 1 男 2 女
					idcard:'',
					phone: '',
					remarks:''
				},
				//性别
				sexSelectList: [{text: '男',value:1},{text: '女',value:2}],
				sexSelectShow: false,
				sexSelectIndex:0,
				//园区
				gander:'',
				ganderSelectList: [],
				ganderSelectShow: false,
				ganderSelectIndex:0,
				//区域
				residential:'',
				residentialId:'',
				residentialSelectList: [],
				residentialSelectShow: false,
				residentialSelectIndex:0,
				//企业
				current:1,
				flag:false,
				keyword:'',
				
				company:'',
				companySelectList: [],
				companySelectShow: false,
				//上传人脸的方式
				faceSelectList: [{
					text: '相册上传',
				}, {
					text: '拍照上传'
				}],
				faceSelectShow:false,
				//验证码
				codeTips: '',
				subscribeShow:true,
				
				//获取头像信息,兼容低版本
				canIUseGetUserProfile: false,
			}
		},
		watch:{
			keyword(){
				let that=this
				//节流函数
				if (this.timer){
					clearTimeout(this.timer)//阻止setTimeout函数的执行
				}
				this.timer = setTimeout(() => {
					that.current=1
					that.companySelectList=[]
					that.fetchEnterpriseList(that.residentialId)
				}, 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
			
			//兼容低版本获取头像的方式
			if (uni.getUserProfile) {
				this.canIUseGetUserProfile=false
			}
			
			if (!this.$isEmpty(options.operationType)) {
				this.operationType=options.operationType
			}
			this.fetchAgencyList()
			if (this.operationType==0) {
				//用户认证
				this.getOpenid()
				if (!this.$isEmpty(options.phone)) {
					this.model.phone=options.phone
				}
			}else{
				//用户重新审核
				this.phone=options.phone
				this.fetchUserInfo()
			}
		},
		methods: {
			handelAppletAudit(){
				this.appletStatus=uni.getStorageSync("appletStatus")
				if (this.appletStatus==1) {
					uni.setNavigationBarTitle({
						title:'员工认证'
					})
				}else{
					uni.setNavigationBarTitle({
						title:'待开发'
					})
				}
			},
			/**
			 * 重新审核操作时，加载用户的认证信息
			 */
			async fetchUserInfo(){
				if (this.$isEmpty(getApp().globalData.userInfo)) {
					let res=await this.$api.enterprisestaff.page({phone:this.phone})
					this.model=res.data.records[0]
				}else{
					this.model=getApp().globalData.userInfo
				}
				if (this.model.sex==2) {
					this.sexSelectIndex=1
				}
				this.opinion=this.model.opinion
				if (!this.$isEmpty(this.opinion)) {
					this.show=true
				}
				this.fetchResidentialList(this.model.agencyId)
				this.fetchEnterpriseList(this.model.residentialId)
				this.gander=this.model.agencyName
				this.residential=this.model.residentialName
				this.company=this.model.enterpriseName
			},
			/**
			 * 获取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
							this.$cache.put('openid',resData.openid)
						})
					}
				})
			},
			/**
			 * 提交审核
			 */
			async submit(e){
				let userInfo={}
				try{
					if (this.canIUseGetUserProfile) {
						let res=await this.$mpi.getUserProfile()
						userInfo=res.userInfo
					}else{
						userInfo=e.detail.userInfo
					}
				}catch(e){
					this.$refs.uTips.show({
						title: '认证失败，获取头像昵称失败',
						type: 'error',
						duration: '3000'
					})
					return
				}
				if (this.$isEmpty(userInfo)) {
					this.$refs.uTips.show({
						title: '认证失败，获取头像昵称失败',
						type: 'error',
						duration: '3000'
					})
					return
				}
				this.model.avatar=userInfo.avatarUrl
				this.model.name=userInfo.nickName
				this.model.sex=this.sexSelectList[this.sexSelectIndex].value || 1
				if (this.$isEmpty(this.model.realName)) {
					this.$u.toast('请输入您的姓名')
					return
				}
				if (this.$isEmpty(this.model.idcard)) {
					this.$u.toast('请输入身份证号')
					return
				}
				if (!this.$u.test.idCard(this.model.idcard)) {
					this.$u.toast('请输入正确的身份证号')
					return
				}
				if (this.$isEmpty(this.model.phone)) {
					this.$u.toast('请输入手机号码')
					return
				}
				if (!this.$u.test.mobile(this.model.phone)) {
					this.$u.toast('请输入正确的手机号码')
					return
				}
				if (this.$isEmpty(this.model.face)) {
					this.$u.toast('请上传人脸信息')
					return
				}
				if (this.$isEmpty(this.model.enterpriseId)) {
					this.$u.toast('请选择所属企业')
					return
				}
				if (this.operationType==1) {
					//重新审核
					this.model.auditStatus=0
				}
				this.model.createType=1 //1小程序认证方式 0：后台数据导入
				let res=await this.$api.enterprisestaff.submit(this.model)
				if (res.code==200) {
					if (this.operationType==0) {
						that.$showModel('提交成功，请耐心等待企业管理者审核',false).then(res=>{
							uni.reLaunch({
								url:"/pages/login/login"
							})
						})
					}else{
						that.$showModel('操作成功',false).then(res=>{
							this.$navigateBack()
						})
					}
					await this.$mpi.subscribe(that.$staffTmplIds)
					this.getOpenListAndSendMsg()
				}else{
					this.$u.toast(res.msg)
				}
			},
			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/index/staffAudit/list',
					miniprogramState:this.$miniprogramState,
				    templateId: this.$adminTmplIds[2],
					  "data": {
						  "thing5": {
							  "value": this.model.realName
						  },
						  "phone_number6":{
							  "value": this.model.phone
						  },
						  "time3": {
							  "value": this.$dateTime.format(new Date())
						  }
						}
				}
				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)
				})
			},
		//园区 begin
			/**
			 * 显示园区
			 */
			ganderShow(){
				this.ganderSelectShow=true
			},
			/**
			 * 获取园区列表
			 */
			fetchAgencyList(){
				this.$api.agency.page().then(res=>{
					this.ganderSelectList=res.data.records
				})
			},
			/**
			 * 选择园区后的回调
			 * @param {Object} e
			 */
			ganderSelectCallback(e) {
				uni.hideKeyboard();
				//先重置区域和企业
				if (this.ganderSelectIndex!=e[0]) {
					this.resetResidential()
					this.resetEnterprise()
				}
				this.ganderSelectIndex=e[0]
				this.gander=this.ganderSelectList[this.ganderSelectIndex].name
				this.model.agencyName=this.ganderSelectList[this.ganderSelectIndex].name
				this.model.agencyId=this.ganderSelectList[this.ganderSelectIndex].id
				//加载区域
				this.fetchResidentialList(this.model.agencyId)
			},
		//园区 end
			
		//区域 begin
			/**
			 * 重置区域数据
			 * @param {Object} 
			 */
			resetResidential(){
				this.residentialSelectList=[]
				this.residential=''
				this.residentialSelectIndex=0
				this.model.residentialName=''
				this.model.residentialId=''
			},
			/**	
			 * 根据园区id获取区域列表
			 */
			fetchResidentialList(agencyId){
				this.$api.residential.page({agencyId:agencyId,size:300}).then(res=>{
					this.residentialSelectList=res.data.records
				})
			},
			//显示区域
			residentialShow(){
				if (this.$isEmpty(this.gander)) {
					//未选择园区提示先选择园区
					this.$u.toast("请先选择园区")
					return
				}
				this.residentialSelectShow=true
			},
			/**
			 * 选择区域的回调
			 */
			residentialSelectCallback(e){
				uni.hideKeyboard();
				//先重置数据
				if (this.residentialSelectIndex!=e[0]) {
					this.resetEnterprise()
				}
				this.residentialSelectIndex=e[0]
				this.residential=this.residentialSelectList[this.residentialSelectIndex].name
				this.residentialId=this.residentialSelectList[this.residentialSelectIndex].id
				this.model.residentialName=this.residentialSelectList[this.residentialSelectIndex].name
				this.model.residentialId=this.residentialSelectList[this.residentialSelectIndex].id
				//加载区域下的企业
				this.fetchEnterpriseList(this.residentialId)
			},
		//区域 end
			
		//企业 begin
			/**
			 * 重置企业数据
			 */
			resetEnterprise(){
				this.companySelectList=[]
				this.current=1
				this.company=''
				this.model.enterpriseName=''
				this.model.enterpriseId=''
			},
			/**
			 * 根据 区域id 获取 企业列表
			 */
			fetchEnterpriseList(residentialId){
				let params={
					residentialId:residentialId,
					current:this.current,
					enterpriseName:this.keyword
				}
				this.$api.enterprise.page(params).then(res=>{
					this.companySelectList = [...this.companySelectList,...res.data.records]
				})
			},
			/**
			 * @param {Object} 下拉加载更多企业
			 */
			scrolltolower(e){
				 if(this.companySelectList.length<this.current*10){
					 this.flag=true
				   return
				}else{
					this.current++
					this.fetchEnterpriseList(this.residentialId)
				}
				
			},
			/**
			 * 显示企业
			 */
			companyShow(){
				if (this.$isEmpty(this.residential)) {
					//未选择区域
					this.$u.toast("请选择区域")
					return
				}
				this.companySelectShow=true
			},
			//公司
			companySelectCallback(item) {
				this.model.enterpriseId=item.id
				this.model.enterpriseName=item.enterpriseName
				this.company=item.enterpriseName
				this.companySelectShow=false
			},
			
		//企业 end
			
			/**
			 * 获取页面对象
			 */
			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]
			},
			
			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])
			    }
			  });
			},
			//处理照片，拍照上传和相册上传的共同处理方法
			async uploadFile(imgUrl){
				uni.showLoading({
					title:"上传中",
				})
				let res=await this.$api.uploadFile.submit(imgUrl)
				that.model.face=res.data.link
				uni.hideLoading()
			},
		},
	}
</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>
