<template>
	<view class="login"
		style="background-image: url(https://wechat-img-file.oss-cn-beijing.aliyuncs.com/login/Group_491.png);">
		<view class="login-title">
			<view class="login-tip" style="font-size: 40rpx; color: #000000;">欢迎来到【榴园社区】</view>

			<view v-if="loginChannel === 'android' || loginChannel === 'ios'" class="app_login">
				<input class="input" type="number" maxlength="11" data-name="userId" @input='headerInputClick'
					:value="userId" placeholder="请输入手机号" />
				<input class="input" password data-name="passWord" @input='headerInputClick' :value="passWord"
					placeholder="请输入密码" />
				<view class="tips">未注册用户填写手机号后点击登录即可，无需输入密码</view>
				<button class="app_login_btn" @click="headerLoginClick">登录</button>
			</view>

			<view v-if="loginChannel === 'mp-weixin'" class="">
				<view class="login-tip" style="font-size: 28rpx; color: #555555; margin-top: 30rpx;">为了更好的体验，申请获取您的公开信息
				</view>
				<view class="login-tip" style="font-size: 28rpx; color: #555555; margin-top: 14rpx;">（头像、昵称等）</view>
				<view class="login-button">
					<button class="login-btn" open-type="getPhoneNumber" @click="headerLoginClick"
						@getphonenumber="getPhoneNumber">
						授权登录
					</button>
				</view>
			</view>
			<view class="login-to-home">
				<text class="login-to-home-text" @click='tohome'>
					返回首页>>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
import { apiArr } from '../../api/login';
import { apiArr as apiArr2 } from '../../api/v2User';
import { request } from '../../utils';
export default {
	data() {
		return {
			isLogin: false,
			loginChannel: '', // 登录渠道
			userId: '',
			passWord: '',
		}
	},
	methods: {

		headerInputClick(e) {
			const { name } = e.currentTarget.dataset;
			const { value } = e.detail;
			this[name] = value
		},

		headerLoginClick() {
			let that = this
			uni.showLoading({
				title: '登录中...',
				mask: true
			});
			if (this.loginChannel === 'android' || this.loginChannel === 'ios') {
				this.appLogin();
				return;
			}

			uni.login({
				onlyAuthorize: true,
				success: (res) => {
					request(apiArr.login, 'POST', {
						code: res.code,
						phone: '',
						password: '',
					}, { silent: false }).then((loginRes) => {
						// 存储用户信息
						uni.setStorageSync('ctoken', loginRes.token);
						uni.setStorageSync('is_deal', loginRes.is_deal);
						uni.setStorageSync('is_dev', loginRes.is_dev);
						uni.setStorageSync('is_shop', loginRes.is_shop);
						uni.setStorageSync('is_worker', loginRes.is_worker);


						// 获取用户信息
						request(apiArr.loginInfo, 'POST', {
							token: loginRes.token
						}, { silent: false }).then((res2) => {
							if (res2.error) return;
							// 保存userId 后续接口使用
							uni.setStorageSync('userId', res2.user_id);
							uni.setStorageSync('openId', res2.open_id);
							uni.setStorageSync('shopId', res2.wshop_id);

							this.isLogin = true;
							that.getUserInfo();
							that.getCommunityList();
						})
					}, (err) => {
						uni.hideLoading();
						console.log('登录接口错误', err);
					})
				}
			})
		},

		// 小程序登录获取手机号接口
		getPhoneNumber(event) {
			console.log('小程序登录获取手机号', event);
			const { isLogin } = this;
			// uni.setStorageSync('phone', '18332119617');
			// this.tohome();
			//  return
			if (event.detail.errMsg === "getPhoneNumber:ok") {
				request(apiArr.loginGetUserPhone, 'POST', {
					code: event.detail.code
				}, { silent: false }).then((res) => {
					console.log(res);
					uni.hideLoading();
					if (isLogin) {
						uni.setStorageSync('phone', res.phone);
						uni.showToast({
							title: '登录成功',
							icon: 'success',
							mask: true,
							duration: 2000,
							success: () => {
								setTimeout(() => {
									this.tohome();
								}, 2000)
							}
						});
					} else {
						uni.showToast({
							title: '登录失败',
							icon: 'error',
							mask: true,
							duration: 2000,
						})
					}
				})
			} else {
				uni.hideLoading();
				uni.removeStorageSync('ctoken');
				uni.removeStorageSync('userId');
				uni.removeStorageSync('openId');
				uni.removeStorageSync('phone');
				uni.removeStorageSync('is_deal');
				uni.removeStorageSync('is_dev');
				uni.removeStorageSync('is_shop');
				uni.removeStorageSync('is_worker');
				uni.removeStorageSync('shopId');
				uni.removeStorageSync('order_dispatch_permission');
				uni.removeStorageSync('work_order_permission');

				uni.removeStorageSync('nickName');
				uni.removeStorageSync('changeCommData');
				console.error('用户拒绝授权:', event.detail.errMsg);
			}
		},

		getUserInfo() {
			request(apiArr2.getUserInfo, "POST", {
				user_id: uni.getStorageSync('userId')
			}, { silent: false }).then(res => {
				const { community_worker } = res;
				uni.setStorageSync('order_dispatch_permission', community_worker && community_worker[0].order_dispatch_permission == 1 || false);
				uni.setStorageSync('work_order_permission', community_worker && community_worker[0].work_order_permission == 1 || false);
				uni.setStorageSync('nickName', res.nick_name);
				console.log(res)
			})
		},

		// 获取已入住房源信息
		getCommunityList() {
			request(apiArr.getCommunityList, 'POST', {
				latitude: uni.getStorageSync('location').lat,
				longitude: uni.getStorageSync('location').lng,
				page_num: 1,
				page_size: 10,
			}, { silent: false }).then((res3) => {
				const { rows: [{}] } = res3;
				uni.setStorageSync("changeCommData",{ name: rows[0].name, id: rows[0].community_id })
			})
		},
		

		// app端登录
		async appLogin() {
			try {
				const loginRes = await request(apiArr.login, 'POST', {
					code: '',
					phone: this.userId,
					password: this.passWord
				}, { silent: false });
				uni.setStorageSync('ctoken', loginRes.token);
				uni.setStorageSync('is_deal', loginRes.is_deal);
				uni.setStorageSync('is_dev', loginRes.is_dev);
				uni.setStorageSync('is_shop', loginRes.is_shop);
				uni.setStorageSync('is_worker', loginRes.is_worker);

				// 获取用户信息
				const loginInfoRes = await request(apiArr.loginInfo, 'POST', {
					token: loginRes.token
				}, { slient: false });
				uni.setStorageSync('userId', loginInfoRes.user_id);
				uni.setStorageSync('openId', loginInfoRes.open_id);
				uni.setStorageSync('shopId', loginInfoRes.wshop_id);
				uni.setStorageSync('phone', this.userId); // app端无获取手机号功能，登录成功则存储用户填写手机号
				this.isLogin = true;
				uni.hideLoading();

				if (loginRes.msg) {
					uni.showModal({
						title: '提示',
						content: loginRes.msg,
						showCancel: false,
						complete: (res) => {
							if (res.confirm) {
								this.tohome();
							}
						}
					})
				} else {
					this.tohome();
				}
			} catch (error) {
				uni.hideLoading();
				//TODO handle the exception
				console.log('app登录异常', error);
			}

		},


		// 返回主页
		tohome: function () {
			// console.log(123);
			uni.redirectTo({
				url: '/pages/index/index'
			});
		}
	},
	onLoad() {
		const systemInfo = uni.getSystemInfoSync();
		console.log('platformplatform', systemInfo)
		// this.loginChannel = systemInfo.osName;
		// return;
		if (systemInfo.uniPlatform === 'mp-weixin') {
			this.loginChannel = systemInfo.uniPlatform;
		} else {
			this.loginChannel = systemInfo.osName;
		}
	}
}
</script>

<style>
@import url("./login.css");
</style>