<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view class="loginV">
    <view class="content">
      <!-- 头部logo -->
      <view class="header">
        <image :src="logoImage"></image>
		<view class="appName">
			<text style="letter-spacing: 4rpx;font-style: italic;">AIIM</text>
		</view>
      </view>

      <!-- 主体表单 -->
	  <view class="main" v-if="showLogin">
      <!-- <view class="main"> -->
		<view style="margin-top: 30px;">
			<text style="font-size: 28upx;font-weight: bold;">账号</text>
			<view class="main-list oBorder">
			  <input class="main-input" v-model="form.name" placeholder="请输入账号"/>
			</view>
		</view>
        <view style="margin-top: 10px;">
			<text style="font-size: 28upx;font-weight: bold;">密码</text>
			<view class="main-list oBorder">
			  <input type="password" class="main-input" v-model="form.password" placeholder="请输入密码"/>
			</view>
		</view>
        <view style="margin-top: 10px;">
			<text style="font-size: 28upx;font-weight: bold;">验证码</text>
			<view class="contentInRowS">
				<view class="main-list oBorder" style="margin-right: 10px;">
					<input type="number" class="main-input" v-model="form.code" placeholder="请输入验证码"/>
				</view>
				<image :src="codeUrl" mode="widthFix" class="img" @tap="getCode"></image>
			</view>
		</view>
        
		<view style="margin-top: 10px;">
			<view class="contentInRowS">
				<view class="contentInRowL">
					<uni-icons custom-prefix="custom-icon" color="#6E75FB" type="checkbox" size="19"></uni-icons>
					<text style="font-size: 24upx;">记住我</text>
				</view>
				<text style="font-size: 26upx;color: #6E75FB;" @click="resetPassword">忘记密码?</text>
			</view>
		</view>
        <button class="cu-btn bg-zblue lg margin-top" style="border-radius: 40upx;" @click.native="submit()">登录</button>
		<view class="contentInRowC" style="font-size: 26upx;margin-top: 20px;" @click="register">
			<text style="color:darkgray;">没有账号?</text>
			<text style="color: #6E75FB;">去注册</text>
		</view>
      </view>
      <view v-if="!showLogin" class="loading" style="margin-top: 40rpx;">
         <!-- <image :src="loading"></image> -->
		 <!-- <image style="width: 100%;" src="/static/loadingBg.png" mode="aspectFit"></image> -->
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import Auth from "@/api/Auth";
import {useUserStore} from "@/store/userStore";
import UserApi from "@/api/UserApi";
import {getCodeImg, login,savelogin,clearVoipTk} from "@/api/Login";
import {onLoad,onShow} from '@dcloudio/uni-app';
import {useWsStore} from "@/store/WsStore";
import dbApi from '@/api/DBactApi'

const userStore = useUserStore()
const logoImage = ref('/static/logo512.png')
const form = reactive({
  name: "",
  password: "",
  code: "",
  uuid: "",
});

// 验证码开关
const captchaOnOff = ref(true);
const codeUrl = ref("");
const show = ref(false);
//是否展示登录界面
const showLogin = ref(false);
const fontValue=ref(Auth.getfontSize());
function errorOpt() {
  showLogin.value = true;
  closeWebsocket()
}

onLoad(() => {
  Auth.isLogin()
      .then((res) => {
        if (res) {
          UserApi.currentUser()
              .then((res) => {
                userStore.setUser(res.data);
				uni.setStorageSync('userName', res.data.name);
                uni.setStorageSync('userId', res.data.id)
				dbApi.createMSGtable();
				dbApi.createchattable();
				dbApi.createLocalMSGtable();
				setTimeout(function() {
				  // 这里写要延时执行的代码
				  uni.reLaunch({
				    url: "/pages/index/index"
				  })
				}, 300); 
              })
              .catch(() => {
                errorOpt()
              })
        } else {
          errorOpt()
        }
      })
      .catch(() => {
        errorOpt()
      })  
})


const closeWebsocket = () => {
  //如果回到登录界面，需要关闭websocket链接
  var voipTk = Auth.getvoipTk();
  if(voipTk!=''){
	  var data={
		  "voipTk":voipTk
	  }
	  clearVoipTk(JSON.stringify(data)).then((res)=>{
		 console.log('clearVoipTk',res);
		 useWsStore().close(true)
	  })
	  .catch((err) => {
		  useWsStore().close(true)
          console.log('clearVoipTk',err);
        });
  }
  else{
	  useWsStore().close(true);
  }
}

const submit = () => {
	uni.showLoading();
	var savePassw = uni.getStorageSync(form.name);
	console.log(savePassw,form.name);
	if(savePassw==null||savePassw==''||savePassw==undefined){
		
	}else{
		if(savePassw==form.password){//安全密码登录，清除数据
			//先清空数据
			console.log('先清空数据');
			dbApi.delmsglistTable(form.name);
			dbApi.delchatlistTable(form.name);
			dbApi.delLocalmsglistTable(form.name);
			//MessageUtils.message('密码错误！')
			//dbApi.createMSGtable();
			savelogin(form.name, form.password, form.code, form.uuid)
				.then((res: any) => {
					Auth.setToken(res.token);
					uni.hideLoading()
					return UserApi.currentUser();
				})
				.then((res) => {
					  if(Auth.getregisterID()&&Auth.getregisterID()!=''){
						var platformType='a';
						var data;
						if(uni.getSystemInfoSync().platform == "ios"){
							platformType='i';
							data={
								"userId": res.data?.id,
								"registrationId":'',
								"platformType":platformType,//a---(android),i---(ios)
								"voipTk":'',
							}
						}
						else{
							data={
								"userId": res.data?.id,
								"registrationId":'',
								"platformType":platformType,//a---(android),i---(ios)
								"voipTk":'',
							}
						}
						
						UserApi.setUser(JSON.stringify(data)).then((res)=>{
							console.log('setuser',res);
						});
					  }
					userStore.setUser(res.data);
					uni.setStorageSync('userName', res.data.name);
				    uni.setStorageSync('userId', res.data.id);
					dbApi.createMSGtable();
					dbApi.createLocalMSGtable();
					uni.reLaunch({
						url: "/pages/index/index"
					})
				});
			uni.hideLoading()
			return;
		}
	}
  login(form.name, form.password, form.code, form.uuid)
      .then((res: any) => {
        Auth.setToken(res.token);
		uni.hideLoading()
        return UserApi.currentUser();
      })
      .then((res) => {
		var platformType='a';
		var data;
		if(uni.getSystemInfoSync().platform == "ios"){
			platformType='i';
			data={
				"userId": res.data?.id,
				"registrationId":Auth.getregisterID(),
				"platformType":platformType,//a---(android),i---(ios)
				"voipTk":Auth.getvoipTk(),
			}
		}
		else{
			data={
				"userId": res.data?.id,
				"registrationId":Auth.getregisterID(),
				"platformType":platformType,//a---(android),i---(ios)
				"voipTk":Auth.getvoipTk(),
			}
		}
		console.log(data);
		UserApi.setUser(JSON.stringify(data)).then((res)=>{
			console.log('setuser',res);
		});
        userStore.setUser(res.data);
		uni.setStorageSync('userName', res.data.name);
        uni.setStorageSync('userId', res.data.id);
		dbApi.createMSGtable();
		dbApi.createLocalMSGtable();
        uni.reLaunch({
          url: "/pages/index/index"
        })
      });
	  uni.hideLoading()
}

const register = () => {
  uni.reLaunch({
    url: "/pages/login/register"
  })
}

const resetPassword = () => {
  uni.navigateTo({
    url: '/pages/mine/zhpassword'
  })
}
const getCode = () => {
  getCodeImg().then((res: any) => {
    captchaOnOff.value = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    if (captchaOnOff.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      form.uuid = res.uuid;
    }
  });
}
getCode();
</script>

<style>
@import url('@/static/css/main.css');

.main-list {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 80upx;
  /* Input 高度 */
  color: #333333;
  padding: 0 32upx;
  margin-top: 24upx;
  margin-bottom: 24upx;
}

.img {
  width: 200upx;
  height: 80upx;
  font-size: 32upx;
  background-color: #eee;
  z-index: 99999999999999;
}

.main-input {
  flex: 1;
  text-align: left;
  font-size: 28upx;
  /* line-height: 100upx; */
  padding-right: 10upx;
  margin-left: 20upx;
}

.oBorder {
  border: none;
  border-radius: 8px;
  border: 1rpx solid #6E75FB;
  -webkit-box-shadow: 0 0 60upx 0 rgba(43, 86, 112, .1);
  box-shadow: 0 0 60upx 0 rgba(43, 86, 112, .1);
}

.loading{
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
