<template>
  <view id="login" class="section">
    <!-- <u-loading-page :loading="true" loading-text="loading..."  loading-mode="spinner"></u-loading-page> -->

    <view class="bg">
      <image class="bgImage" :src="bg" v-if="bg" />
      <!-- <image class="bgImage" src="@/static/images/wt/bg.png" v-else /> -->
    </view>

    <view class="middle">
      <view class="top">
        <image class="logo" mode="heightFix" :src="logo" v-if="logo" />
        <image class="logo" mode="heightFix" src="@/static/logo200.png" v-else />
        <text class="title" v-if="title">{{ title }}</text>
        <text class="title" v-else>移动端登录</text>
      </view>

      <view class="content">
        <text class="title">请登录</text>

        <!-- #ifdef APP-PLUS -->
        <view id="okay" v-if="!linkUrl">首次账号登录请先配置服务器</view>
        <!-- <u-icon class="icons" name="scan" color="gray" size="22"></u-icon> -->
        <view class="setting" @tap="goSeverConfig"> 配置服务器 </view>
        <!--#endif-->
      </view>

      <view id="login-input" v-if="switchText == '账号密码登录'">
        <u-input v-model="phone" prefixIcon="phone" placeholder="请输入手机号码" />
      </view>

      <view id="login-input" v-if="switchText == '账号密码登录'">
        <u-input v-model="verify" prefixIcon="email" placeholder="请输入验证码" :maxlength="6">
          <template #suffix>
            <u-button @click="getVerifyCode">{{ !codeTime ? "获取验证码" : codeTime + "s" }}</u-button>
          </template>
        </u-input>
      </view>

      <view id="login-input" v-if="switchText == '验证码登录'">
        <u-input type="text" v-model="username" prefixIcon="account" placeholder="请输入账号" />

        <u-input v-model="password" prefixIcon="lock" placeholder="请输入密码" :password="inputIconBool">
          <template #suffix>
            <text :class="!inputIconBool ? 'iconfont ucicon-eye' : 'iconfont ucicon-eye-close'" @click="inputIconBool = !inputIconBool"></text>
          </template>
        </u-input>
      </view>

      <!--  -->
      <button class="submit" @click="submitRes">登 录</button>

      <view class="switchText" @click="switchMode">
        <text>{{ switchText }}</text>
      </view>

      <!-- #ifdef APP-PLUS -->
      <view class="xieyi text-center">
        <u-checkbox-group>
          <u-checkbox v-model="userChecked" shape="circle" inactiveColor="#0081ff" size="13"></u-checkbox>
        </u-checkbox-group>
        <text>我已阅读并同意</text>
        <text @click="handleUserAgrement" class="text-blue">用户协议</text>
        <text>和</text>
        <text @click="handlePrivacy" class="text-blue">隐私协议</text>
      </view>
      <!--#endif-->
    </view>
    <view class="bottom">
      <div class="title">{{ bottomTitle }}</div>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onShow, onHide, onLaunch, onReady } from "@dcloudio/uni-app";
import { reactive, getCurrentInstance, toRefs, inject, watchEffect } from "vue";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getCodeImg, getMobileTenantConfig } from "@/api/login";

import publicStore from "@/store/modules/public.js";

import useStores from "@/store/modules/user.js";
const useStore = useStores();
const newPublicStore = publicStore();

const { proxy } = getCurrentInstance();

const data = reactive({
  /** saas数据 */
  bg: "",
  logo: "",
  title: "",
  bottomTitle: "",
  /** login数据 */
  phone: undefined,
  verify: undefined,
  codeTime: 0,
  switchText: "验证码登录",
  tenantId: undefined,
  username: undefined,
  password: undefined,
  inputIconBool: true,
  /** 服务器配置数据 */
  linkUrl: uni.getStorageSync("serveUrl"),
  /** 用户隐私协议数据 */
  userChecked: false,

  // VerificationCodeOne
});

const { title, bg, bottomTitle, logo, phone, verify, codeTime, switchText, username, password, tenantId, inputIconBool, linkUrl, userChecked } = toRefs(data);

function goSeverConfig() {
  proxy.$tab.navigateTo("/pages/serveConfig");
}

/**登录方式切换 */
function switchMode() {
  if (switchText.value == "验证码登录") {
    switchText.value = "账号密码登录";
  } else {
    switchText.value = "验证码登录";
  }
}

/** 点击发送验证码 */
function getVerifyCode() {
  //#ifdef APP-PLUS
  if (!uni.getStorageSync("serveUrl")) {
    proxy.$modal.msg("首次登录请先进行服务器配置");
    return;
  }
  //#endif

  if (!phone.value) {
    proxy.$modal.msg("请输入手机号码");
    return;
  }
  if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(phone.value)) {
    proxy.$modal.msg("请输入正确的手机号码");
    return;
  }

  //#ifdef APP-PLUS
  if (userChecked.value) {
    proxy.$modal.msg("请在阅读并同意 用户协议和隐私协议后登录");
    return;
  }
  //#endif

  verify.value = undefined;
  getCodeImg({
    phone: phone.value,
  }).then((res) => {
    console.log(res);
  });
  if (codeTime.value > 0) {
    proxy.$modal.msg("不能重复获取");
    return;
  } else {
    codeTime.value = 60;
    let timer = setInterval(() => {
      codeTime.value--;
      if (codeTime.value < 1) {
        clearInterval(timer);
        codeTime.value = 0;
      }
    }, 1000);
  }
}

/**
 * 判断运行环境
 */
function env() {
  // const u = navigator.userAgent
  // //https://blog.csdn.net/weixin_42659644/article/details/126294231
  // if(u.indexOf('saas')>-1){ //指定app内 获取app识别号
  // }else{
  // }

  console.log(window.location.host);

  //#ifdef H5
  linkUrl.value = window.location.host;
  // linkUrl.value = window.location.host;
  // linkUrl.value='ces.cn';
  // linkUrl.value='172.16.120.165:13203'
  getMobileTenantConfigApi({ url: linkUrl.value });
  //#endif

  //  uni.showToast({
  //   title: '服务器链接地址为'+linkUrl,
  //   icon: "none",
  // })

  //  let port = uni.getSystemInfoSync().platform;
  // switch (port) {
  //   case "android":
  //     getMobileTenantConfigApi({ url: window.location.host });
  //     console.log("Android"); //android
  //     break;
  //   case "ios":
  //     console.log("iOS"); //ios
  //     getMobileTenantConfigApi({ url: window.location.host });
  //     break;
  //   case "windows":
  //     getMobileTenantConfigApi({ url: window.location.host });
  //     break;
  //   default: //devtools
  //     console.log("小程序");
  //     break;
  // }
}

/** 点击提交按钮 */
function submitRes() {
  //#ifdef APP-PLUS
  if (!uni.getStorageSync("serveUrl")) {
    proxy.$modal.msg("首次登录请先进行服务器配置");
    return;
  }
  //#endif

  //#ifdef APP-PLUS
  if (userChecked.value) {
    proxy.$modal.msg("请在阅读并同意 用户协议和隐私协议后登录");
    return;
  }
  //#endif

  if (switchText.value == "账号密码登录") {
    if (!phone.value) {
      proxy.$modal.msg("请输入手机号码");
      return;
    }
    if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(phone.value)) {
      proxy.$modal.msg("请输入正确的手机号码");
      return;
    }
    if (!verify.value) {
      proxy.$modal.msg("请输入验证码");
      return;
    }
    login({
      phone: phone.value,
      verify: verify.value,
      tenantId: tenantId.value,
    });
  } else {
    if (!username.value) {
      proxy.$modal.msg("请输入账户");
      return;
    }
    if (!password.value) {
      proxy.$modal.msg("请输入密码");
      return;
    }

    login({
      username: username.value,
      password: password.value,
      tenantId: tenantId.value,
    });
  }
}

/** 获取登录数据 */
function login(data) {
  proxy.$modal.loading("登录中，请耐心等待...");

  useStore.Login(data).then(() => {
    /** 获取用户信息 */
    proxy.$modal.closeLoading();
    useStore.GetInfo().then((res) => {
      proxy.$tab.reLaunch("/pages/index");
    });
  });
}

/** 获取登录页数据 */
function getMobileTenantConfigApi(params) {
  getMobileTenantConfig(params).then((res) => {
    if (res.data.length > 0) {
      let data = res.data[0];
      title.value = data.loginTitle;
      bottomTitle.value = data.loginFooter;
      tenantId.value = data.tenantId;
      bg.value = data.loginBackUrl;
      logo.value = data.loginLogo;
      uni.setStorageSync("homeTitle", data.loginTitle);
    }
  });
}

// 用户协议
function handleUserAgrement() {
  let site = getApp().globalData.config.appInfo.agreements[0];
  proxy.$tab.navigateTo(`/pages/common/textview/index1?title=${site.title}&content=${site.content}`);
}
// 隐私协议
function handlePrivacy() {
  let site = getApp().globalData.config.appInfo.agreements[1];
  proxy.$tab.navigateTo(`/pages/common/textview/index1?title=${site.title}&content=${site.content}`);
}

watchEffect(() => {
  //#ifdef APP-PLUS
  if (uni.getStorageSync("serveUrl")) {
    linkUrl.value = uni.getStorageSync("serveUrl");
    getMobileTenantConfigApi({ url: linkUrl.value });
  }
  //#endif
});

/**
 * @onLoad
 */
onLoad(() => {
  env();

  const token = getToken();
  //需要登录
  if (token) {
    uni.switchTab({
      url: "/pages/index",
    });
  }
});

// onReady(() => {
//   //动态修改状态栏的颜色
//   uni.setNavigationBarColor({
//     frontColor: "#000000",
//     backgroundColor: "#ff0000",
//   });
// });
</script>

<style>
page {
  background-color: #ffffff;
}
</style>

<style lang="scss" scoped>
.section {
  display: flex;
  width: 100%;
  height: 100%;

  .bg {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 0;
    .bgImage {
      width: 100%;
      height: 100%;
    }
  }

  .middle {
    position: relative;
    z-index: 1;
    width: 100%;
    padding: 0 40px;
    margin: auto;
    margin-top: 30%;

    #login-input {
      .u-input {
        height: 45px;
        border-radius: 8px;
        padding: 5px 12px !important;
        border: 0 !important;
        // border-color: #000 !important;
        // border-color: gray !important;
        // background-color: rgba(255, 255, 255, 0.1) !important;
        background-color: #f5f6fa !important;
        margin-bottom: 20px;
      }

      :deep(.input-placeholder) {
        color: #96a6b5 !important;
      }

      :deep(.uni-input-wrapper) {
        font-size: 16px;
      }

      :deep(.u-icon__icon) {
        font-size: 24px !important;
        line-height: 24px !important;
        color: gray !important;
      }

      :deep(.iconfont) {
        color: gray !important;
      }

      :deep(:-webkit-autofill) {
        caret-color: #000; // 设置光标颜色
        // -webkit-text-fill-color: gray !important;
        -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
        background-color: transparent;
        background-image: none;
        transition: background-color 50000s ease-in-out 0s; //背景色透明  生效时长  过渡效果  启用时延迟的时间
      }

      :deep(.u-button) {
        color: #2a98ff;
        font-size: 16px !important;
        white-space: nowrap;
        border: 0;
        border-color: #2a98ff !important;
        background-color: rgba(255, 255, 255, 0) !important;

        &:before {
          opacity: 0;
        }
      }
    }

    .top {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 60px;

      :deep(uni-image) {
        height: 40px;
        // width:40px;
        width: auto;
      }
      .logo {
        margin-right: 10px;
      }
      .title {
        font-size: 20px;
        color: #000;
        max-width: 50%;
        white-space: nowrap;
      }
    }

    .content {
      display: flex;
      position: relative;
      margin: 30px 0 30px 0;
      .title {
        margin: auto auto auto 0;
        color: #000;
        font-size: 18px;
      }

      .icons {
        margin: auto 5px auto 0;
      }

      .setting {
        color: #2a98ff;
        margin: auto 0;
      }

      #okay {
        position: absolute;
        top: -35px;
        right: 0px;
        background-color: #2a98ff;
        text-align: center;
        line-height: 25px;
        display: inline-block;
        color: #fff;
        padding: 3px 5px;
        border-radius: 3px;
      }
      #okay::after {
        content: "";
        position: absolute;
        border: 5px solid transparent;
        transform: rotate(90deg);
        right: 5px;
        bottom: -9px;
        border-left-color: #2a98ff;
      }
    }

    .switchText {
      color: #96a6b5;
      width: 100%;
      display: block;
      margin-top: 20px;
    }

    .submit {
      height: 45px;
      line-height: 45px;
      border-radius: 24px;
      background: #2a98ff;
      color: #fff;
      border: 0px;
    }

    .xieyi {
      color: #96a6b5;
      margin-top: 30px;
      display: flex;
      justify-content: center;
      > uni-view {
        margin: auto 0;
      }
      > uni-text {
        margin: auto 0;
      }
      // animation: roundRule 0.5s linear infinite;
    }

    @keyframes roundRule {
      0% {
        transform: translateX(0);
      }
      50% {
        transform: translateX(-5px);
      }
      100% {
        transform: translateX(0);
      }
    }
  }

  .bottom {
    position: absolute;
    width: 100%;
    bottom: 10px;
    .title {
      text-align: center;
      color: #000;
      font-size: 14px;
    }
  }

  .iconfont {
    color: #999;
  }
}
</style>
