<template>
  <view class="container">
    <view class="title-content">
      <image src="../../static/emblem-icon.png" mode=""></image>
      <view class="text-layer">
        <!-- <text class="title">哈密市项目</text> -->
        <text class="sub-title">哈密市项目管理智慧平台</text>
      </view>

    </view>

    <view class="login-form-content">

      <view class="input-box">
        <view class="input-item flex align-center">
          <input v-model="loginForm.userName" style="font-size: 14px;" class="input" type="text" placeholder="请输入您现有的账号" maxlength="30" />
        </view>

        <view class="input-item flex align-center">
          <input v-model="loginForm.password" @keyup.enter="handleLogin" :type="passType" class="input"
            placeholder="请输入您的密码" maxlength="20" />
          <view class="pass-item-icon" :class="passType === 'text' ? 'pass-item-hide' :''">
            <image :src="passIcon" @click="changeInputType()"></image>
          </view>
        </view>
      </view>

      <view class="forget-pass-item">
        <text class="forget-pass" @click="goToForgetPass()">忘记密码</text>
      </view>

      <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round"
        :class="{ 'color-bg': colorCheck }">登录</button>

      <view class="change-ip">
        <text class="forget-pass" @click="goToChangeIP()">更换服务地址</text>
      </view>
    </view>

    <u-overlay :show="isDownload">
      <view class="download-box">
        <view class="loading-box">
          <view class="loading-icon">
            <u-loading-icon v-if="downloadPrecent !== '100'" size="40"></u-loading-icon>
            <u-icon v-else name="checkmark" size="40"></u-icon>
          </view>

          <view class="loading-text">{{downloadText}}</view>

          <view class="loading-progress">
            <u-line-progress :percentage="downloadPrecent" activeColor="#1869F6"></u-line-progress>
          </view>
        </view>
      </view>
    </u-overlay>
  </view>
</template>

<script setup>
  import {
    ref,
    computed,
    onMounted,
    watch
  } from "vue";

  import {
    onLoad,
    onShow
  } from "@dcloudio/uni-app"

  import {
    getNewestVersion
  } from '@/api/login.js'

  import {
    validateVersion
  } from "@/utils/validateVersion.js"

  import user from '@/store/modules/user'
  import config from '@/config.js'
  import store from '@/store'
  import passSee from "@/static/pass-see.svg"
  import passHide from "@/static/pass-hide.svg"

  // 登录信息
  const loginForm = ref({
    userName: "",
    password: ""
  });

  let passType = ref("password")
  let passIcon = ref(passHide)

  function changeInputType() {
    passType.value = passType.value === "password" ? "text" : "password"
    passIcon.value = passType.value === "password" ? passHide : passSee
  }



  // 登录
  async function handleLogin() {
    if (functionBan) {
      return uni.showToast({
        title: '请更新至最新版本后操作。',
        icon: 'none',
        mask: false,
        duration: 1000
      });
    }

    if (loginForm.value.userName === "") {
      uni.showToast({
        title: '请输入您的账号',
        icon: 'error',
        mask: false,
        duration: 1000
      });
    } else if (loginForm.value.password === "") {
      uni.showToast({
        title: '请输入您的密码',
        icon: 'error',
        mask: false,
        duration: 1000
      });
    } else {
      uni.getNetworkType({
        success: function(res) {
          if (res.networkType === "none") {
            // console.log('injudge');
            // uni.showToast({
            // 	title: '请输入您的账号',
            // 	icon: 'error',
            // 	mask: false,
            // 	duration: 1000
            // });
            // console.log('beforeJudge');
            // return
            const serverAddress = uni.getStorageSync('serverAddress')
            const baseUrlIp = serverAddress ? serverAddress : config.baseUrl
            let titleText = `服务器ip：${baseUrlIp} 连接不上，请检查网络`
            uni.showModal({
              // title: '网络不通，请检查网络情况',
              title: '提示',
              content: titleText,
              icon: 'none',
              mask: false,
              duration: 3000,
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          } else {
            uni.showToast({
              title: '登录中，请耐心等待...',
              icon: 'loading',
              mask: false,
              duration: 1000
            });
            store.dispatch('Login', loginForm.value).then(() => {
              loginSuccess()
            }).catch(err => {
              console.log(err);
            })
          }
        },
        fail: function(err) {
          return uni.showToast({
            title: '获取手机网络状态失败。',
            icon: 'error',
            mask: false,
            duration: 1000
          });
        }
      })
    }
  };

  // 设置用户信息
  function loginSuccess(result) {
    store.dispatch('GetInfo').then(res => {
      uni.switchTab({
        url: '/pages/home/headHome'
      });
    })
  }

  // 忘记密码
  function goToForgetPass() {
    if (functionBan) {
      return uni.showToast({
        title: '请更新至最新版本后操作。',
        icon: 'none',
        mask: false,
        duration: 1000
      });
    }
    uni.navigateTo({
      url: '/pages/login/forgetPass/index'
    })
  }

  // 更换服务地址
  function goToChangeIP() {
    if (functionBan) {
      return uni.showToast({
        title: '请更新至最新版本后操作。',
        icon: 'none',
        mask: false,
        duration: 1000
      });
    }
    uni.navigateTo({
      url: '/pages/login/changeIP/index'
    })
  }

  // 禁止功能使用
  let functionBan = false

  // 是否正在下载新版本
  let isDownload = ref(false)

  // 下载进度
  let downloadPrecent = ref(0)

  // 下载文件
  let downloadFilePath = null;

  // 下载提示文字
  let downloadText = ref("下载中，请勿关闭软件。")

  // 判断是否最新版本
  function judgeIsNewest() {
    //#ifdef APP-PLUS
    // 获取系统信息
    uni.getSystemInfo({
      // 成功则进行对比
      success: async (res) => {
        // 获取最新版本
        const newsetVersionRes = await getNewestVersion().catch(() => {
          uni.showModal({
            title: '错误',
            content: '获取最新系统版本失败。'
          });
        });
        let newsetVersion = newsetVersionRes.data.version;
        let higherThanNewest = validateVersion(res.appWgtVersion, newsetVersion)
        // 如果版本低于服务上的最新版
        if (!higherThanNewest) {
          // 禁用功能
          functionBan = true;
          // 最新版本下载链接
          const serverAddress = uni.getStorageSync('serverAddress');
          const baseUrlIp = serverAddress ? serverAddress : config.baseUrl;
          const downloadUrl = baseUrlIp + '/projects/outApi/version/download';
          // 展示下载提示
          uni.showModal({
            title: '新版本提醒',
            content: `检测到新版本“${newsetVersion}”，请下载更新。`,
            confirmText: '去下载',
            cancelText: '退出软件',
            cancelColor: '#808080',
            success: async (modelRes) => {
              // 确认选择
              if (modelRes.confirm) {
                if (plus.os.name == "Android") {
                  isDownload.value = true

                  let downloadTask = uni.downloadFile({
                    url: downloadUrl,
                    success: (successRes => {
                      downloadFilePath = successRes
                        .tempFilePath;
                      uni.hideLoading();
                      plus.runtime.install(successRes
                        .tempFilePath);
                      isDownload.value = false;
                      downloadPrecent.value = 0;
                    }),

                    fail: (failRes) => {
                      uni.hideLoading();
                      uni.showModal({
                        title: '错误',
                        content: '下载最新版本失败。'
                      });
                      isDownload.value = false;
                      downloadPrecent.value = 0;
                    }
                  })

                  downloadTask.onProgressUpdate(res => {
                    downloadPrecent.value = res.progress
                    if (res.progress == 100) {
                      downloadText = "下载完成，即将安装最新版本"
                    }
                  })
                };
              } else {
                // 退出软件
                plus.runtime.quit();
              }
            },
          })
        }
      },
      // 失败禁用功能并弹窗
      fail: () => {
        functionBan = true;
        uni.showModal({
          title: '错误',
          content: '获取当前系统版本失败。'
        })
      }
    })
    //#endif
  }

  // 判断是否已经下载了最新版
  const judgeIsDownloadNewest = () => {
    if (downloadFilePath) {
      uni.showModal({
        title: '新版本已下载',
        content: '最新版本已下载完毕，请点击安装。',
        confirmText: '去安装',
        showCancel: false,
        success: async (modelRes) => {
          if (modelRes.confirm) {
            if (plus.os.name == "Android") {
              plus.runtime.install(downloadFilePath);
            }
          }
        }
      })
    }
  }

  let colorCheck = ref(false)
  watch(() => {
    if (loginForm.value.userName !== '' && loginForm.value.password !== '') {
      colorCheck.value = true
    } else {
      colorCheck.value = false
    }
  })

  onLoad(() => {
    judgeIsNewest()
  })

  onShow(() => {
    judgeIsDownloadNewest()
  })
</script>

<style lang="scss">
  page {
    height: 100%;
    background-color: #fff !important;
  }

  .color-bg {
    background: #002F69 !important;
  }

  .container {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #002F69;
    overflow: hidden;

    .title-content {
      position: absolute;
      top: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 20rpx;
      width: 100%;
      height: calc(310rpx + var(--status-bar-height));
      z-index: 1;
      background-size: 100% 100%;
      background-color: #002F69;

      image {
        width: 144rpx;
        height: 144rpx;
      }

      .text-layer {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;

        .title {
          font-size: 40rpx;
          font-weight: 700;
          color: #FFFFFF;
          line-height: 60rpx;
        }

        .sub-title {
          font-size: 46rpx;
          font-weight: 700;
          color: #FFFFFF;
          line-height: 60rpx;
        }
      }
    }

    .login-form-content {
      position: absolute;
      top: calc(310rpx + var(--status-bar-height));
      left: 0;
      z-index: 100;
      width: 100%;
      height: 2000rpx;
      background-color: #fff;
      border-radius: 60rpx 60rpx 0rpx 0rpx;

      .welcome-text {
        margin: 0 0 60rpx;
        font-size: 44rpx;
        font-weight: 700;
        color: #C6C6CD;
      }

      .item-text {
        font-size: 36rpx;
        font-weight: 400;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
        color: #343437;
      }

      .input-box {
        margin: auto;
        width: 556rpx;
        margin-top: 132rpx;
        display: flex;
        flex-direction: column;
        border: 2rpx solid #DDDDDD;
        border-radius: 16rpx;

        .input-item {
          margin: auto;
          height: 90rpx;
          width: 558rpx;
          font-size: 28rpx;
          // background-color: #f5f6f7;
          border-radius: 16rpx;

          .input {
            width: 100%;
            font-size: 14px;
            line-height: 20px;
            text-align: left;
            padding-left: 15px;
          }
        }

      }


      .pass-item-icon {
        flex: 1;
        height: 100%;
        line-height: 80rpx;
        text-align: right;
        padding-right: 15px;

        image {
          width: 36rpx;
          height: 18rpx;
        }
      }

      .pass-item-hide {
        image {
          width: 36rpx;
          height: 28rpx;
        }
      }

      .forget-pass-item {
        margin: auto;
        width: 556rpx;
        margin-top: 30rpx;
        text-align: right;
      }

      .forget-pass {
        color: #002F69;
      }

      .login-btn {
        margin: auto;
        width: 556rpx;
        margin-top: 40rpx;
        height: 45px;
        background: #DDDDDD;
        border-radius: 48rpx;
      }
    }

    .change-ip {
      margin-top: 200rpx;
      text-align: center;

      .forget-pass {
        color: #002F69;
        border-bottom: 2rpx solid #002F69;
      }
    }

    .download-box {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .loading-box {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 360rpx;
        height: 360rpx;
        padding: 20rpx;
        background-color: #fff;
        border-radius: 40rpx;
      }

      .loading-icon {
        flex: 4;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      .loading-text {
        flex: 1;
        display: flex;
        align-items: flex-end;
        text-align: center;
      }

      .loading-progress {
        flex: 1;
        display: flex;
        align-items: flex-end;
      }
    }
  }
</style>