<template>
  <view class="content">
    <view class="self-inf">
    
	  <view class="antu-box" v-if="isAuth">
		<view class="img-name-box">
		  <image :src="userHeadImg" class="heade-img" mode="aspectFill"></image>
		  <p class="nickname">{{ userNickName }}</p>
		  <p class="nickname">{{userPhone}}</p>
		</view>
		<view class="org-info-box" v-for="(item,index) in userPosList" :key="index">
		  <view class="org-info">{{item.name || '-'}}</view>
		  <!-- <view class="org-line"></view> -->
		  <view class="org-info">{{item.position}}</view>
		</view>	  
	  </view>
	  
	  <view class="img-name-box" v-if="!isAuth" style="height: 180rpx;">
		<image src="/static/auth-icon.png" class="heade-img" mode="aspectFill" style="margin-left: 80rpx;"></image>
        <button @click="goAuthPage()" class="auth-btn">授权登录</button>
      </view>
      <!-- <image class="bg-img" :src="swiperBackground" mode="aspectFill"></image> -->
    </view>
    <view class="options" :style="{paddingTop:(posLength > 1 ? '160rpx':'80rpx')} ">
	 <!-- <view class="options" :class="{ paddingTop80: userPosList.length > 1 }"> -->
      <view  v-for="(item, idx) in list" :key="idx" class="options-item" @click="goDetailFn(idx, item.url)"  v-if="item.isShow">
        <view class="img-box">
          <img :src="item.icon" alt="" class="options-item-img" />
        </view>
        <view class="options-item-name">
          {{ item.name }}
        </view>
      </view>
    </view>
	
	<uni-popup ref="popup" type="center" :is-mask-click="false">
			<view class="auth-pop">
				<image src="/static/logo.png" mode="aspectFill"></image>
				<text class="margin-top-3 auth-title">欢迎使用农工笔记小程序</text>
				<text class="margin-top-3 auth-content">此页面是微信授权页面,授权之后你可以获取更优质的服务,您的隐私将会受到保护</text>
				<view class="margin-top-3">
					<!-- <button type='default' class="refuse" @click="goAuthPage">去授权</button>-->
					<button type='primary' class="allow" @click="getUserInfo()" v-if="!isAuth">登录授权</button>
					<button type="primary" class="allow"  open-type="getPhoneNumber"  style="font-size: 12px;"
					@getphonenumber="getPhoneNumber" v-if="isAuth && !isNeedPhone">手机号码授权</button> 
				</view>
			</view>
		</uni-popup>

     <!-- <button class="submit-btn" @click="goUpload()">上传</button> -->
  </view>
</template>

<script>
import md5 from "@/common/md5.js";
export default {
	components: {
	},
  data() {
    return {
      isAuth: true,
      userHeadImg: "",
      userNickName: "",
	  userPhone:'',
	  userBranch:'',
	  userPosList:[],
	  posLength:0,
	  userPos:'',
	  userscanCode:"",
	  iv:'',
	  encryptedData:'',
	  isNeedPhone:getApp().globalData.user_phone,
      list: [
   //      { 
		 // icon: "/static/upload.png",
		 // name: "内容上传" ,
		 // url: "/pages/index/upload/upload",
		 // isShow:false,
		 // },
   //      { 
		 //  icon: "/static/sign.png", 
		 //  name: "发布记录" ,
		 //  url: "/pages/index/record/record",
		 //  isShow:false,
		 // },
		 {
		   icon: "/static/scan.png", 
		   name: "扫码" ,
		   // url: "/pages/index/scanCode/index",
		   isShow:true,
		  },
		{
		  icon: "/static/self-icon.png", 
		  name: "个人信息" ,
		  url: "/pages/index/self_info",
		  isShow:true,
		 },
		 {
		   icon: "/static/org-icon.png", 
		   name: "组织成员" ,
		   url: "/pages/index/org_member",
		   isShow:true,
		  },
		 {
		  icon: "/static/explain-icon.png", 
		  name: "后台登录" ,
		  url: "/pages/index/back_login",
		  isShow:true,
		 },
		 {
		   icon: "/static/back.png",
		   name: "退出登录" ,
		   // url: "/pages/index/scanCode/index",
		   isShow:true,
		  },
      ],
    };
  },
  async onLoad() {
	  // setTimeout(()=>{
	  // 		this.getUserInfo()
	  // },1000)
	  await this.$getOpenId
	  this.getUserInfoData()
  },
  onShow() {
  },
  methods: {
	goAuthPage() {
		uni.navigateTo({
		  url: "./auth/index",
		});
	},
    open(){
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        uni.hideTabBar()
		this.$refs.popup.open('center')
      },
	getUserInfo() {
		uni.getUserProfile({
			desc:'登录',
			success:(res)=> {
				getApp().globalData.user_headUrl = res.userInfo.avatarUrl;
				getApp().globalData.user_name = res.userInfo.nickName;
				this.userHeadImg = res.userInfo.avatarUrl;
				this.userNickName = res.userInfo.nickName;
				this.iv = res.iv;
				this.encryptedData = res.encryptedData;
				this.isAuth = true;
				getApp().globalData.isAuth = true; 
				getApp().globalData.globalAuth = true; 
				this.loginUserInfo()
			},
			fail:(err)=> {
				getApp().globalData.isAuth = false;
				getApp().globalData.globalAuth = false; 
				this.isAuth = false;
			}
		})
	},
	getPhoneNumber(e){
		let that = this;
		 if (e.detail.errMsg == 'getPhoneNumber:ok') { //允许授权执行跳转
		  that.phoneRequest(e.detail.iv, e.detail.encryptedData, getApp().globalData.session_key)
		} else { //
		      that.isNeedPhone = false;
		}
	},
	phoneRequest(myIv,myEncryptedData,sKey){
		let that = this;
		let md5Sign = md5("method="+'user'+"&timestamp="+getApp().globalData.globalTimestamp+"&secret="+getApp().globalData.secret)
		let url = getApp().globalData.shareUrl+'api/api.php'+'?method=user&source=user&action=phone&timestamp='+getApp().globalData.globalTimestamp +'&sign='+md5Sign
		uni.request({
			url:url,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				iv:myIv,
				sessionKey:sKey,
				encryptedData:myEncryptedData,
				openid:getApp().globalData.open_id
			},
			success: (res) => {
				console.log(res)
				if(res.data.code === 200){
					getApp().globalData.user_phone = res.data.data;
					this.userPhone = res.data.data.substr(0, 3) + '****' + res.data.data.substr(7) ;
					this.$refs.popup.close()
					uni.showTabBar({})
				}else {
					uni.showToast({
					  title: res.data.msg,
					  duration: 2500,
					  icon: "none",
					});
				} 
			},
			fail: () => {
				console.log("连接失败");
			}
		});
	},
	loginUserInfo(){
		let md5Sign = md5(
		  "method=" +
			"user" +
			"&timestamp=" +
			getApp().globalData.globalTimestamp +
			"&secret=" +
			getApp().globalData.secret
		);
		let url =
		  getApp().globalData.shareUrl +
		  "api/api.php" +
		  "?method=user&action=update&timestamp=" +
		  getApp().globalData.globalTimestamp +
		  "&sign=" +
		  md5Sign;
		uni.request({ 
		  url: url,
		  method: "POST",
		  header: {
			"content-type": "application/x-www-form-urlencoded",
		  },
		  data: {
			nickname:getApp().globalData.user_name,
			headimg:getApp().globalData.user_headUrl,
			openid:getApp().globalData.open_id
		  },
		  success: (res) => {
			if (res.data.code === 200) {
			}
		  },
		  fail: () => {
			console.log("连接失败");
		  },
		});
	},	  
	goUpload(){
		let that = this;
		if(!that.isAuth){
			  uni.showToast({
				title: "您还没有授权",
				duration: 2500,
				icon: "none",
			  });
			  return;
		}else {
			uni.navigateTo({
				url: "/pages/index/upload/upload",
			})
		}
	},
	getUserInfoData() {
	    let md5Sign = md5(
	      "method=" +
	        "user" +
	        "&timestamp=" +
	        getApp().globalData.globalTimestamp +
	        "&secret=" +
	        getApp().globalData.secret
	    );
	    let url =
	      getApp().globalData.shareUrl +
	      "api/api.php" +
	      "?method=user&action=info_by_openid&timestamp=" +
	      getApp().globalData.globalTimestamp +
	      "&sign=" +
	      md5Sign;
	    uni.request({
	      url: url,
	      method: "POST",
	      header: {
	        "content-type": "application/x-www-form-urlencoded",
	      },
	      data: {
	        openid:getApp().globalData.open_id,
	      },
	      success: (res) => {
	        if (res.data.code === 200) {
				if (res.data.data.nickname) {
				  this.isAuth = true;
				  this.userHeadImg = res.data.data.headimg;
				  this.userNickName = res.data.data.nickname;
				  if(res.data.data.phone){
					  this.userPhone = res.data.data.phone.substr(0, 3) + '****' + res.data.data.phone.substr(7)
					  this.getUserInfoBranch();
				  }else {
					  this.open()
				  }
				  getApp().globalData.globalAuth  = true;
				  getApp().globalData.user_name  = res.data.data.nickname;
				  getApp().globalData.user_headUrl  = res.data.data.headimg;
				  getApp().globalData.user_department = res.data.data.department;
				  getApp().globalData.user_real_name = res.data.data.real_name;
				  getApp().globalData.user_phone = res.data.data.phone;
				  getApp().globalData.isAuth = true;
				  this.isAuth = true;
				  this.isNeedPhone = false;
				}else {
				  this.open();	
				  this.isAuth = false;
				  getApp().globalData.globalAuth  = false;
				  getApp().globalData.user_name = '';
				  getApp().globalData.isAuth = false;
				  this.isAuth = false;
				}
	        }
	      },
	      fail: () => {
	        console.log("连接失败");
	      },
	    });
	  },
	  getUserInfoBranch() {
	      let md5Sign = md5(
	        "method=" +
	          "member" +
	          "&timestamp=" +
	          getApp().globalData.globalTimestamp +
	          "&secret=" +
	          getApp().globalData.secret
	      );
	      let url =
	        getApp().globalData.shareUrl +
	        "api/api.php" +
	        "?method=member&action=my_branch&timestamp=" +
	        getApp().globalData.globalTimestamp +
	        "&sign=" +
	        md5Sign;
	      uni.request({
	        url: url,
	        method: "POST",
	        header: {
	          "content-type": "application/x-www-form-urlencoded",
	        },
	        data: {
	          openid:getApp().globalData.open_id,
	        },
	        success: (res) => {
	          if (res.data.code === 200) {
				  this.userPosList = res.data.data;
				  this.posLength = res.data.data.length;
	          }
	        },
	        fail: () => {
	          console.log("连接失败");
	        },
	      });
	    },
    codeReg(strs){
			let reg = /\[(.*?)\]/gi;
			let str = strs;
			let tmp = str.match(reg) , result = '';
			if (tmp) {
				for (let i = 0; i < tmp.length; i++) {
					 result = tmp[i].replace(reg, "$1")
				}
			} else {
				console.log("no match.");
			}
			 console.log(result)
			this.getScanCode(result)
    },
	getScanCode(codeRes) {
	    let md5Sign = md5(
	      "method=" +
	        "user" +
	        "&timestamp=" +
	        getApp().globalData.globalTimestamp +
	        "&secret=" +
	        getApp().globalData.secret
	    );
	    let url =
	      getApp().globalData.shareUrl +
	      "api/api.php" +
	      "?method=user&action=qrcode_login&timestamp=" +
	      getApp().globalData.globalTimestamp +
	      "&sign=" +
	      md5Sign;
	    uni.request({
	      url: url,
	      method: "POST",
	      header: {
	        "content-type": "application/x-www-form-urlencoded",
	      },
	      data: {
	        openid:getApp().globalData.open_id,
			qrcode:codeRes
	      },
	      success: (res) => {
	        if (res.data.code === 200) {
				uni.showToast({
					title:res.data.msg,
					icon:'none'
				})
	        } else {
				uni.showToast({
					title:res.data.msg,
					icon:'none'
				})
			}
	      },
	      fail: () => {
	        console.log("连接失败");
	      },
	    });
	  },		
    goDetailFn(index, url) {
      let that = this;
	  if(!that.isAuth){
		  uni.showToast({
		    title: "您还没有授权",
		    duration: 2500,
		    icon: "none",
		  });
		  return;
	  }
      switch (index) {
        case 0: //扫码
		    uni.scanCode({
		        success: function (res) {
		            console.log('条码类型：' + res.scanType);
		            console.log('条码内容：' + res.result);
					that.codeReg(res.result)
		        }
		    });
          break;
        case 1: //个人信息
			uni.navigateTo({
			  url,
			}); 
          break;
		case 2: //组织成员
		  uni.navigateTo({
		    url,
		  });
		  break;  
		case 3: //后台登录
			uni.navigateTo({
			  url,
			});
		  break;  
		case 4: //退出登录
			uni.showModal({
			  title: "确定退出登录吗?",
			  success(res) {
				if (res.confirm) {
				  that.loginOut();
				} else if (res.cancel) {
				  console.log("用户点击取消");
				}
			  },
			});
		  break;  
        default:
			uni.navigateTo({
			  url,
			});
      }
    },
    loginOut() {
    let md5Sign = md5(
      "method=" +
        "user" +
        "&timestamp=" +
        getApp().globalData.globalTimestamp +
        "&secret=" +
        getApp().globalData.secret
    );
    let url = getApp().globalData.shareUrl +
      "api/api.php" +
      "?method=user&action=logout&timestamp=" +
      getApp().globalData.globalTimestamp +
      "&sign=" +
      md5Sign;
    uni.request({
      url: url,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      data: {
        openid: getApp().globalData.open_id,
      },
      success: (res) => {
        if (res.data.code === 200) {
		  let that = this;	
          that.isAuth = false;
          getApp().globalData.isAuth = false;
          getApp().globalData.user_headUrl = "";
          getApp().globalData.user_name = "";
          getApp().globalData.user_phone = "";
		  this.userPhone = '';
		  //this.list[3].isShow = false;
  		//this.$forceUpdate();
          uni.showToast({
            title: "退出登录成功",
            duration: 2500,
            icon: "none",
			success() {
				that.open()
			}
          });
        }
      },
      fail: () => {
        console.log("连接失败");
      },
    });
  },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  .self-inf {
    position: relative;
    height: 240rpx;
    width: 100%;
    // display: flex;
    // margin-bottom: 80rpx;
	background-color: #c2e3e6;
    // border-radius: 0rpx 0rpx 100% 100%;
    .img-name-box {
		height: 150rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		width: 85%;
      .auth-btn {
		margin-left: 30rpx;
		margin-top: 20rpx;
        font-size: 28rpx;
        background-color: #02a7f0;
        color: #fff;
      }
      .heade-img {
        z-index: 1;
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        // margin-left: 80rpx;
      }
    }
    .bg-img {
      z-index: -1;
      position: absolute;
      width: 100%;
      height: 100%;
      // border-radius: 0rpx 0rpx 70rpx 70rpx;
    }
    .nickname {
      font-weight: 600;
      font-size: 28rpx;
      margin-left: 30rpx;
      margin-top: 20rpx;
      color: #555;
      letter-spacing: 1rpx;
    }
  }
  .options {
    padding: 80rpx 70rpx 20rpx 70rpx;
    z-index: 99;
    position: relative;
    .options-item {
      background-color: #fff;
      display: flex;
      box-shadow: 0px 4rpx 32rpx rgba(0, 0, 0, 0.1);
      border-radius: 32rpx;
      margin-top: 30rpx;
      height: 75px;
      align-items: center;
      .img-box {
        margin-left: 40rpx;
        .options-item-img {
          width: 56rpx;
          height: 56rpx;
        }
      }
      .options-item-name {
        margin-left: 40rpx;
        font-weight: 600;
        font-size: 30rpx;
        margin-bottom: 10rpx;
      }
    }
  }
}
.auth-box {
    display: flex;
    background-color: #fff;
    height: 500rpx;
    width: 600rpx;
    border-radius: 10rpx;
		button {
		   height:100rpx;
		   font-size: 26rpx;
		};
}
.fontGrey {
  color: $uni-text-color-grey;
}
.antu-box {
	display: flex;
	flex-direction: column;
	align-items: center;
	background: #fff;
	border-radius: 10rpx;
	position: relative;
	z-index: 99;
	top: 25px;
	width: 80%;
	left: 10%;
	color: #555;
	box-shadow: 0px 2px 16px rgba(0, 0, 0, 0.2);
}
.submit-btn {
    color: white;
    font-weight: normal;
    width: 70%;
    border-radius: 20rpx;
    background-color: #02a7f0;
    margin: 50rpx auto;
  }
.org-info-box {
    display: flex;
    justify-content: space-evenly;
    height: 80rpx;
    align-items: center;
    width: 100%;
    border-top: 1px solid #d4d4d4;
    color: #555;
    font-size: 28rpx;
    background: #fff;
} 
.org-info {
	width: 50%;
	padding-left: 10%;
}
.org-line {
	width: 1px;
	height: 82rpx;
	background: #d4d4d4;
} 
   .auth-pop{
		background-color: #fff;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 75%;
		margin: 0 auto;
		border-radius: 10rpx;
		padding: 20rpx;
   }
   .auth-pop image{
	   width: 200upx;
	   height: 200upx;
	   margin-top: 10%;
   }
   .auth-pop view {
	   // display: flex;
	   // width: 490upx;
	   // justify-content: space-between;
   }
   .auth-title {
	   font-size: 32upx;
   }
   .auth-content {
   	   font-size: 26upx;
	   color: #a7aaa9;
   }
   .allow {
	   background-color: #27BCEF;
	   margin: 20rpx 0 75rpx;
	   text-align: center;
	   vertical-align: middle;
	   touch-action: manipulation;
	   cursor: pointer;
	   background-image: none;
	   white-space: nowrap;
	   user-select: none;
	   font-size: 14px;
	   border: 0 !important;
	   position: relative;
	   text-decoration: none;
	   height: 44px;
	   width: 250rpx;
	   line-height: 44px;
	   box-shadow: inset 0 0 0 1px #27BCEF;
	   background: #fff !important;
	   color: #27BCEF !important;
	   display: inline-block;
	   border-radius: 10rpx;

   }
   .refuse {
	   background-color: #19be6b;
	   margin: 20rpx 20rpx 200rpx 20rpx;
	   text-align: center;
	   vertical-align: middle;
	   touch-action: manipulation;
	   cursor: pointer;
	   background-image: none;
	   white-space: nowrap;
	   user-select: none;
	   font-size: 14px;
	   border: 0 !important;
	   position: relative;
	   text-decoration: none;
	   height: 44px;
	   width: 250rpx;
	   line-height: 44px;
	   box-shadow: inset 0 0 0 1px #8a8a8a;
	   background: #fff !important;
	   color: #8a8a8a !important;
	   display: inline-block;
	   border-radius: 10rpx;

   }
   .margin-top-3{
	   margin-top: 10%;
   }
   .paddingTop80 {
	   padding-top:160rpx;
   }
</style>