<template>
  <gui-page :is-loading="isLoading">
    <template #gBody>
      <view style="padding:50rpx;">
        <view class="server-config" @click="handleSetServerIP">
          <text class="font-icons">&#xe6bc;</text>
        </view>
        <view style="height:150rpx;" />
        <view class="gui-flex gui-row gui-justify-content-center login-title">
          <image src="../../static/logo.png" style="width: 90rpx;height: 90rpx;" mode="aspectFit" />
          <text class="login-title-text">东智-MOMPlus</text>
        </view>
        <view style="margin-top:80rpx;">
          <form @submit="submit">
            <view>
              <text class="gui-text-small gui-color-gray">账户</text>
            </view>
            <view class="gui-border-b">
              <input
                v-model="loginForm.username"
                type="text"
                class="gui-form-input"
                name="username"
                placeholder="登录账户"
              >
            </view>
            <view class="gui-margin-top">
              <text class="gui-text-small gui-color-gray">密码</text>
            </view>
            <view class="gui-border-b">
              <input
                v-model="loginForm.password"
                type="password"
                class="gui-form-input"
                name="password"
                placeholder="密码"
              >
            </view>
            <view class="gui-margin-top gui-flex gui-rows gui-space-between" hover-class="gui-tap">
              <text class="gui-text gui-color-gray gui-block" @tap="forgetPwd">忘记密码</text>
              <text class="gui-text gui-color-gray gui-block gui-text-right" @tap="loginbymsg">短信登录</text>
            </view>
            <view style="margin-top:68rpx;">
              <button
                type="default"
                class="gui-button gui-bg-primary gui-noborder"
                formType="submit"
                style="border-radius:50rpx;"
              >
                <text class="gui-color-white gui-button-text">登 录</text>
              </button>
            </view>
          </form>
        </view>
      </view>
    </template>
  </gui-page>
</template>

<script>
import graceChecker from '@/Grace6/js/checker.js'
import { getFileStorage } from '@/unit/fileStorage.js'

export default {
  data() {
    return {
      isLoading: false,
      loginForm: {
        username: '',
        password: '',
        validCode: 'akiooa'
      }
    }
  },
  beforeCreate() {
    // #ifdef APP-PLUS
    // 3秒超时保护，防止文件读取卡死
    const timeout = setTimeout(() => {
      console.warn('读取服务配置超时，使用默认配置')
      uni.$baseUrl = ''
    }, 3000)

    getFileStorage('serverConfig.txt')
      .then(data => {
        clearTimeout(timeout)
        if (data === null) {
          uni.$baseUrl = ''
        } else {
          try {
            const ipconfig = JSON.parse(data)
            uni.$baseUrl = ipconfig.deal + '://' + ipconfig.ip + ':' + ipconfig.port
          } catch (e) {
            console.error('解析服务配置失败:', e)
            uni.$baseUrl = ''
          }
        }
      })
      .catch((e) => {
        clearTimeout(timeout)
        uni.$baseUrl = ''
        console.error('获取服务配置失败:', e)
        uni.showToast({
          title: '获取服务配置失败, 请检查本地文件',
          duration: 2000,
          icon: 'none'
        })
      })
    // #endif
  },
  methods: {
    forgetPwd: function() {},
    loginbymsg: function() {},
    handleSetServerIP: function() {
      uni.navigateTo({
        url: '/pages/personCenter/accountConfig'
      })
    },
    
    submit: async function(e) {
	  // 校验服务器地址是否配置
	  // if (!uni.$baseUrl) {
	  //     uni.showToast({
	  //         title: '服务器地址未配置，请点击右上角设置',
	  //         icon: 'none',
	  //         duration: 2000
	  //     });
	  //     return;
	  // }
      // 表单数据
      var formData = e.detail.value
      
      // 定义表单规则
      var rule = [
        {
          name: 'username',
          checkType: 'string',
          checkRule: '4,50',
          errorMsg: '登录账户输入有误, 至少4个字符'
        },
        {
          name: 'password',
          checkType: 'string',
          checkRule: '4,16',
          errorMsg: '登录密码至少4个字符'
        }
      ]
      
      var checkRes = graceChecker.check(formData, rule)
      if (!checkRes) {
        uni.showToast({
          title: graceChecker.error,
          icon: 'none'
        })
        return
      }

      // 使用原生 Loading，更可靠
      uni.showLoading({
        title: '登录中...',
        mask: true  // 防止触摸穿透
      })

      try {
        // 1. 调用登录接口
        const loginRes = await uni.$reqPost('login', {
          ...formData,
          tenantName: '瑞泰克',
          tenantId: 1,
          rememberMe: true
        })

        if (loginRes.code !== 0) {
          uni.showToast({
            title: loginRes.msg || '登录失败',
            duration: 2000,
            icon: 'none'
          })
          return
        }

        // 保存 token
        uni.setStorageSync('token', loginRes.data?.accessToken)

        // 2. 获取用户信息（await 等待完成）
        const infoRes = await uni.$reqGet('loginInfo')
        
        if (infoRes.data) {
          uni.setStorageSync('permissions', JSON.stringify(infoRes.data.permissions || []))
          uni.setStorageSync('user', JSON.stringify(infoRes.data.user || {}))
        }

        // 3. 登录成功，跳转首页
        uni.$emit('loginSuccess', true)
        uni.switchTab({
          url: '/pages/tabbar/tabbarPanel'
        })

      } catch (err) {
        console.error('登录异常:', err)
        uni.showToast({
          title: err?.message || '网络异常，请检查网络连接',
          duration: 3000,
          icon: 'none'
        })
      } finally {
        // 确保 Loading 一定关闭，避免卡住
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .login-logo {
    width: 180rpx;
    height: 180rpx;
    font-size: 80rpx;
    text-align: center;
    line-height: 120rpx;
    padding: 30rpx;
    border-radius: 18rpx;
  }

  .login-title {
    height: 140rpx;
    display: flex;
    align-items: center;

    .login-title-text {
      font-size: 54rpx;
      font-weight: bold;
      color: rgba(0, 160, 233, 1);
    }
  }

  .other-login-icons {
    width: 88rpx;
    height: 88rpx;
    text-align: center;
    font-size: 70rpx;
    margin: 20rpx;
  }

  .server-config {
    position: fixed;
    top: 20px;
    right: 20px;

    text {
      font-size: 32px;
      color: #808080;
    }
  }
</style>
