<template>
	<view class="login"
		style="background-image: url(https://static.hshuishang.com/loginMainImg.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="profile-fill">
					<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="avatar-img" :src="avatarUrl || defaultAvatar" mode="aspectFill"></image>
						<text class="avatar-tip">点击选择头像</text>
					</button>
					<input type="nickname" class="nickname-input" :value="nickName" placeholder="点击填写昵称"
						@blur="onNickInput" @input="onNickInput" />
				</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';
import { uploadOSS } from '@/utils/uploadOSS';
export default {
	data() {
		return {
			isLogin: false,
			loginChannel: '', // 登录渠道
			userId: '',
			passWord: '',
			nickName: '', // 微信昵称(头像昵称填写能力)
			avatarUrl: '', // 头像预览地址(临时或OSS)
			avatarTemp: '', // 微信头像临时路径，登录后再传OSS
			defaultAvatar: 'https://static.hshuishang.com/loginMainImg.png',
		}
	},
	methods: {

		// 选择头像回调：此时尚未登录(无 token)，仅暂存临时路径，
		// 待 get-phone 成功拿到 token 后再上传 OSS
		onChooseAvatar(e) {
			this.avatarTemp = e.detail.avatarUrl || '';
			this.avatarUrl = this.avatarTemp; // 仅用于界面预览
		},

		// 昵称输入回调
		onNickInput(e) {
			this.nickName = e.detail.value || '';
		},

		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_merchant', loginRes.is_merchant);
						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);
							uni.setStorageSync('headPhoto', res2.img);

							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,
					user_id: uni.getStorageSync('userId'),
					nick_name: this.nickName || ''
				}, { silent: false }).then(async (res) => {
					console.log(res);
					if (isLogin) {
						uni.setStorageSync('phone', res.phone);
						if (this.nickName) uni.setStorageSync('nickName', this.nickName);
						// 此时已登录(有 token)，把头像临时路径上传到 OSS 并落库
						if (this.avatarTemp) {
							try {
								const { objectKey } = await uploadOSS({ filePath: this.avatarTemp, scene: 'avatar', showLoading: false });
								// 数据库统一存相对 object key(带前导/)，显示时再拼 CDN 域名
								const avatarPath = '/' + objectKey;
								await request(apiArr2.userInfoUpdate, 'POST', {
									user_id: uni.getStorageSync('userId'),
									avatar: avatarPath
								}, { silent: true });
								uni.setStorageSync('headPhoto', avatarPath);
							} catch (err) {
								console.error('头像上传/保存失败:', err);
							}
						}
						uni.hideLoading();
						uni.showToast({
							title: '登录成功',
							icon: 'success',
							mask: true,
							duration: 2000,
							success: () => {
								setTimeout(() => {
									this.tohome();
								}, 2000)
							}
						});
					} else {
						uni.hideLoading();
						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_merchant');
				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 && res3.rows) || [];
				if (rows.length > 0) {
					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_merchant', loginRes.is_merchant);
				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");

.profile-fill {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-top: 30rpx;
}

.avatar-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	background: transparent;
	border: none;
	padding: 0;
	line-height: normal;
}

.avatar-btn::after {
	border: none;
}

.avatar-img {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	background-color: #f2f2f2;
}

.avatar-tip {
	font-size: 24rpx;
	color: #999999;
	margin-top: 10rpx;
}

.nickname-input {
	width: 420rpx;
	height: 80rpx;
	margin-top: 24rpx;
	padding: 0 24rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 12rpx;
	font-size: 28rpx;
	text-align: center;
}
</style>