<template>
  <view class="background">
	<!-- 欢迎 -->
	<image class="welcome" src="../../../static/login/account_login/welcome.png"></image>
	<!-- 登录部分 -->
	<view class="login_part">
		<!-- 导航栏 -->
		<view class="login_ways">

			<view class="account_words" @click="toPassageEvent" 
				:style="{borderBottom:passageWordsBottomBorder}">
				密码登录
			</view>


			<view class="captcha_words" @click="toCaptchaEvent" 
				:style="{borderBottom:captchaWordsBottomBorder}">
				验证码登录
			</view>
		</view>


		<!-- 表单部分 -->
		<form class="login_form">
			<view class="form_input">
				<!-- 账号输入框 -->
				<view class="account_box login_form_item">
					<view class="form_input_box">
						<input class="account" v-model="phone_number" type="text" placeholder="请输入你的电话号码"/>
					</view>
					<view class="error_tip" v-if="isPhoneError">*该手机号未注册</view>
				</view>
				<!-- 密码输入框 -->
				<view class="passage_box login_form_item" v-if="isPassagePage">
					<view class="form_input_box passage_input_box">
						<input class="passage" v-model="password" :password="isOpened" type="text" placeholder="请输入你的密码"/>
						<image @click="openEyesEvent" class="eyes" :src="eyesStateIcon"></image>
					</view>
					<view class="error_tip" v-if="isPassageError">*密码错误</view>
				</view>




				<!-- 验证码输入框 -->
				<view class="captcha_box login_form_item" v-else>
					<view class="form_input_box captcha_input_box">
						<input class="captcha"  v-model="code" name="captcha" type="text" placeholder="请输入你的验证码"/>
						<button class="captcha_button" @click="sendCaptchaEvent" 
							:style="{color:captchaButtonColor, backgroundColor:captchaButtonBackgroundColor}">
							{{captchaButtonText}}
						</button>
					</view>
					<view class="error_tip" v-if="isCaptchaError">*验证码错误</view>
				</view>
				<view class="forget_passage" @click="forgetPassageClick">忘记密码？</view>
				<view class="button_box login_form_item">
					<button name="submit_button" class="login_button" @click="login">登录</button>
				</view>
			</view>
		</form>




	</view>
	<!-- 前往注册 -->
	<navigator url="/pages/login/register/register">
		<image class="goto_register" src="../../../static/login/account_login/register.png"></image>
	</navigator>
	<!-- 其他登录部分 -->
<!--	<view class="otherways_part">
		<image class="otherways_tips" src="../../../static/login/account_login/other_ways.png"></image>
		<view class="two_ways">
			<image class="qq_icon" src="../../../static/login/account_login/qq_icon.png"></image>
			<image class="weixin_icon" src="../../../static/login/account_login/weixin_icon.png"></image>
		</view>
	</view>-->
  </view>
</template>

<script setup>

import { ref, computed , onMounted } from 'vue';
import app from "@/App.vue";

const isSendCaptcha = ref(false);	//是否发送了验证码的标志
var codeTime = ref(0);	//验证码的倒计时
const captchaButtonBackgroundColor = computed(() => isSendCaptcha.value ? "#ABCBFF" : "#ffffff"); //验证码按钮的背景颜色
const captchaButtonColor = computed(() => isSendCaptcha.value ? "#ffffff" : "#000364");//验证码按钮的字体颜色
const captchaButtonText = computed(() => isSendCaptcha.value ? (codeTime.value+"s后重新发送"):"发送验证码")



const phone_number=ref("");//用户输入的手机号
const password=ref("");//用户输入的密码
const code=ref("");//发送的验证码
const which_way_to_login = ref("0");	//登录方式 使用0为密码登录 使用1为验证码登录
const access_token = ref("0");	//登录成功后返回的token






const isPassagePage = ref(true);	//是否是密码登录页的标志；
const passageWordsBottomBorder = computed(() => isPassagePage.value? "0.1rem solid #094ABC":"none");	//密码登录导航的下边框
const captchaWordsBottomBorder = computed(() => isPassagePage.value? "none":"0.1rem solid #094ABC");	//验证码登录导航的下边框

const isOpened = ref(true);	//密码是否明文显示的标志
const eyesStateIcon = ref("../../../static/login/account_login/login_part/closedeyes.png");

const isPhoneError = ref(false);
const isPassageError = ref(false);
const isCaptchaError = ref(false);
onMounted(() => {//页面加载时 登录方式为密码登录
  which_way_to_login.value= 0;
  console.log(which_way_to_login.value);
});
//进入验证码登录页面
function toCaptchaEvent(){
	isPassagePage.value = false;
  which_way_to_login.value=1;//切换到验证码登录界面
}
function sendCaptchaEvent(){
  // 校验手机号是否是中国手机号
  const isChinaPhone = /^1[3-9]\d{9}$/.test(phone_number.value);
  if (!isChinaPhone) {
    uni.showToast({
      title: '请输入有效的中国大陆手机号',
      icon: "none"
    });
    return; // 如果手机号无效，停止执行
  }
  if (codeTime.value>0){	//说明在倒计时
		uni.showToast({	//弹出提示框
			title: '不能重复获取',
			icon:"none"
		});
	} else{	//说明没有发送，也没倒计时
		codeTime.value = 60;
		isSendCaptcha.value = true;
		var timer = setInterval(()=>{
			codeTime.value--;
			if(codeTime.value<1){
				clearInterval(timer);
				isSendCaptcha.value = false;
				codeTime.value = 0;
			}
		},1000)
	}
  //这里向后端执行请求
  const app = getApp();
  // 向后端发送请求
  uni.request({
    url: app.globalData.fit_journey_login_address + '/phone_code_register/getPhoneCode',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: {
      phone:String(phone_number.value)
    },
    success: (res) => {
      uni.showToast({
        title: '发送验证码成功，请注意查收~',
        icon: "none"
      });

    },
    error: (res) => {
      console.log("请求失败！请求数据是", res);
    }
  });
}
function login() {
  //向后端发送请求
  uni.request({
    url:app.globalData.fit_journey_login_address+'/common/isPhoneRegistered',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method:'GET',
    data:{
      phone:phone_number.value,
    },
    success:(res)=>{
      console.log(res);
      if(res.data.code===200){
        uni.showToast({
          title: '手机号未注册或输入错误~',
          icon: "none"
        });
        return 0;
      }
    },
  })
  console.log(which_way_to_login.value);
  if (which_way_to_login.value === 0) {	//密码登录
    console.log("这里开始运行了");
    // 获取后端服务器地址
    const serverAddress = app.globalData.fit_journey_login_address + '/AccountLogin/PhonePasswordLogin';
    console.log("后端服务器的地址是" + serverAddress);
    console.log("发送的账号是" + String(phone_number.value));
    console.log("发送的密码是" + String(password.value));
    if(phone_number.value==null||code.value==null){
      uni.showToast({
        title: '手机号和密码不能为空',
        icon: "none"
      });
    }
    // 向后端发送请求
    uni.request({
      url: serverAddress,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
         phone: String(phone_number.value),
        password: String(password.value)
      },
      success: (res) => {
        if (res.statusCode === 500) {
          uni.showToast({
            title: '账号或密码错误',
            icon: "none"
          });
        } else {
          uni.showToast({
            title: '登录成功',
            icon: "none"
          });
          access_token.value = res.data.data.token;
          console.log("登录成功!从后端收集的token是：", access_token.value);
          // 存储 token 到本地
          uni.setStorage({
            key: 'access_token', // 本地存储的键名
            data: access_token.value, // 存储的值
            success: () => {
              console.log("Token 已存储到本地！");
            },
            fail: () => {
              console.error("Token 存储失败！");
            }
          });
          console.log(access_token.value);
          console.log("登录成功!从后端收集的token是：", uni.getStorageSync('access_token'));
          uni.navigateTo({
            url: '/pages/information/sex/sex'//登录成功后跳转的页面
          })
        }
      },
      error: (res) => {
        console.log("请求失败！请求数据是", res);
        uni.showToast({
          title: '登录失败，服务器错误',
          icon: "none"
        });
      }
    });
  } else {	//验证码登录
    console.log("验证码登录部分开始运行了");
    // 获取后端服务器地址
    const serverAddress = app.globalData.fit_journey_login_address + '/PhoneLogin/phoneLogin';
    console.log("后端服务器的地址是" + serverAddress);
    console.log("发送的账号是" + String(phone_number.value));
    console.log("发送的code是" + String(code.value));
    if(phone_number.value==null||code.value==null){
      uni.showToast({
        title: '手机号和验证码不能为空',
        icon: "none"
      });
    }
    // 向后端发送请求
    uni.request({
      url: serverAddress,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        phone: String(phone_number.value),
        code: String(code.value)
      },
      success: (res) => {
        console.log(res);
        if (res.statusCode === 500) {
          uni.showToast({
            title: '账号或密码错误,或账号没有进行注册',
            icon: "none"
          });
        } else {
          uni.showToast({
            title: '登录成功',
            icon: "none"
          });
          access_token.value = res.data.data.token;
          console.log("登录成功!从后端收集的token是：", access_token.value);
          // 存储 token 到本地
          uni.setStorage({
            key: 'access_token', // 本地存储的键名
            data: access_token.value, // 存储的值
            success: () => {
              console.log("Token 已存储到本地！");
            },
            fail: () => {
              console.error("Token 存储失败！");
            }
          });
          console.log(access_token.value);
          console.log("登录成功!从后端收集的token是：", uni.getStorageSync('access_token'));

          //登录成功进行界面的跳转操作
          uni.navigateTo({
            url: '/pages/information/sex/sex'//登录成功后跳转的页面
          })
        }
      },
      error: (res) => {
        console.log("请求失败！请求数据是", res);
        uni.showToast({
          title: '登录失败，服务器错误',
          icon: "none"
        })
      }
    })
  }
}
//进入密码登录页面
function toPassageEvent(){
	isPassagePage.value = true;
  which_way_to_login.value=0;
}
// 判断密码是否要明文显示
function openEyesEvent()
{
	if (isOpened.value)
	 {
		 isOpened.value = false;
		 eyesStateIcon.value = "../../../static/login/account_login/login_part/openedeyes.png"
	 }
	else
	 {
		 isOpened.value =true;
		 eyesStateIcon.value = "../../../static/login/account_login/login_part/closedeyes.png";
	 }
}

function forgetPassageClick(){
	//TODO:进入到忘记密码界面
	uni.navigateTo({
		url:'/pages/login/forget_password/forget_password',
		animationType: 'pop-in',
		animationDuration: 200
	})
}
</script>
<style lang="scss">
@import "@/static/login/account_login/css/acccount_login.scss";
</style>
