<template>
  <view class="normal-login-container">
    <view class="back-icon"  :style="`margin-top: ${globalData.statusBarHeight}px`">
      <up-icon name="arrow-left" size="24" @click="backClick"></up-icon>
    </view>
    <image src="/static/login13785@1x.png" mode="widthFix" class="wave-img"></image>

    <view class="logo-content" :style="`margin-top: ${globalData.navBarHeight}px`">
      <image :src="imagePath" mode="aspectFit" class="logo-image"></image>
      <text class="title">金邻助家</text>
    </view>

    <view class="slogan-content">
      <text class="slogan-text">着力打造全国居家服务行业标准</text>
      <text class="slogan-text">和建立综合信用评价体系</text>
    </view>

    <image src="/static/13779@1x.png" mode="widthFix" class="house-illustration"></image>

    <view class="actions-container">
      <up-button @click="onLogin" :customStyle="WeChat">微信授权登录</up-button>
      <view class="xieyi text-center">
        <up-checkbox-group v-model="checkboxValue">
          <up-checkbox label="我已认真阅读、理解并同意" name="agree" usedAlone @change="onCheckboxChange" class="text-grey1">
          </up-checkbox>
        </up-checkbox-group>

        <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router' // 根据实际情况选择路由库
import store from '@/store'
import { onShow, onLoad } from '@dcloudio/uni-app'
import {
  userOrWorker,
} from '@/api/login';
import { getUnlimitedQRCode } from '@/api/qrcode'
const imagePath = '/static/9efd1.png'

// 获取全局配置
// const globalConfig = getApp().globalData.config;
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
  referrerType: '',
  referrerId: '',
  referrerQrCodeVersion: '',
  latitude: 0,
  longitude: 0,
})


const checkboxValue = ref(false)
const globalData = ref({
  statusBarHeight: 47,
  navBarHeight: 91,
})


const router = useRouter()

// 获取小程序码参数
onLoad((options) => {
  // 处理从二维码扫描进入的场景
  // debugger
  // if (options.scene) {
    console.log('options.scene:>>>>>>>123123s', options.scene)
    const scene = decodeURIComponent(options.scene)
    const params = scene.split(':')
    if (params.length >= 3) {
      loginForm.referrerType = params[0]
      loginForm.referrerId = params[1]
      loginForm.referrerQrCodeVersion = params[2]
      // console.log('从二维码获取参数:', loginForm.referrerType, loginForm.referrerId)
    }
  // }

  // 如果有直接传入的参数也可以获取
  if (options.referrerType) {
    loginForm.referrerType = options.referrerType
  }
  if (options.referrerId) {
    loginForm.referrerId = options.referrerId
  }
})

// 用户注册 - assuming this might be needed later, keeping it
const handleUserRegister = () => {
  router.push('/pages/register') // 替换为实际的路由跳转逻辑
}

const WeChat = {
  width: '530rpx',
  height: '96rpx',
  opacity: 1,
  background: '#8B4F2D',
  color: '#FFFFFF',
  borderRadius: '48rpx',
  fontWeight: '700px',
  fontSize: '32rpx',
  marginLeft: 'auto',
  marginRight: 'auto',
  marginBottom: '10rpx',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  border: 'none',
  boxShadow: 'none',
}

// 隐私协议
const handlePrivacy = () => {
  uni.navigateTo({
    url: '/pages_home/pages/login/index',
  })
}

// 用户协议
const handleUserAgrement = () => {
  uni.navigateTo({
    url: '/pages_home/pages/login/user',
  })
}

// 获取模糊位置信息
const getFuzzyLocation = () => {
  return new Promise((resolve, reject) => {
    wx.getFuzzyLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('模糊位置获取成功:', res)
        // 使用字符串格式保留6位小数，避免parseFloat去除末尾的0
        const lat = res.latitude.toFixed(6)
        const lng = res.longitude.toFixed(6)
        // 在表单中保存为数字格式
        loginForm.latitude = Number(lat)
        loginForm.longitude = Number(lng)
        console.log('处理后的经纬度:', lat, lng)
        resolve({
          latitude: lat,
          longitude: lng
        })
      },
      fail: (err) => {
        console.error('模糊位置获取失败:', err)
        // 位置获取失败时，设为默认值0，也保留6位小数
        loginForm.latitude = 0
        loginForm.longitude = 0
        resolve({
          latitude: "0.000000",
          longitude: "0.000000"
        })
      }
    })
  })
}

// 登录方法
const onLogin = () => {
  uni.$u.debounce(handleLogin, 300)
}

const handleLogin = async () => {

  if (!checkboxValue.value) {
    uni.showToast({
      title: '请先阅读并同意相关协议',
      icon: 'none',
    })

    return
  }
  uni.showLoading({
    title: '登录中，请耐心等待...',
  }) // 使用uni-app的loading方法替代$modal.loading

  try {
    // 获取模糊位置信息
    await getFuzzyLocation()
    console.log('登录位置信息:', loginForm.latitude, loginForm.longitude)
  } catch (err) {
    console.log('位置获取失败，继续登录流程')
  }

  // 获取code
  uni.login({
    provider: 'weixin',
    success: (res) => {
      if (res.code == 500) {
        uni.showLoading({
          title: '系统暂未开发，敬请期待',
        })
      } else if (res.code == 400) {
        uni.showLoading({
          title: '系统暂未开放',
        })
      }

      loginForm.code = res.code

      pwdLogin()

      uni.hideLoading()
    },
  })
}

// 密码登录
const pwdLogin = async () => {
  if (!store) {
    console.error('Store is not defined')
    return
  }
  
  // 确保经纬度已添加到loginForm
  console.log('发送登录请求，经纬度:', loginForm.latitude, loginForm.longitude)
  
  store.dispatch('Login', loginForm).then(() => {
    loginSuccess()
  })
}

// 登录成功后，处理函数
const loginSuccess = () => {
  store.dispatch('GetInfo').then((res) => {
    uni.setStorageSync('userType', store.state.user.userOrWorker)
    uni.setStorageSync('userId', res.user.userId)
    userOrWorker({ userType: store.state.user.userOrWorker })
      .then(res => {
        uni.switchTab({
          url: '/pages/index',
        })
      })
      .catch(err => {
        console.error('设置失败:', err);
      });
  })
}

// 获取胶囊位置信息
const getSystemInfo = () => {
  uni.getSystemInfo({
    success: (res) => {
      const statusBarHeight = res.statusBarHeight
      const navBarHeight =
        (res.platform === 'android') ? 48 : 44 + res.statusBarHeight
      globalData.value = { statusBarHeight, navBarHeight }
    },
  })
}

onShow(() => {
  getSystemInfo()
})

// 页面加载时
onMounted(() => {
  uni.setStorageSync('userType', 1)
  // 设置状态栏为透明
  uni.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: 'rgba(0,0,0,0)',
    animation: {
      duration: 0,
      timingFunc: 'easeIn',
    },
  })

  getSystemInfo()
})

const onCheckboxChange = (value) => {
  console.log('复选框状态改变:', value)
  checkboxValue.value = value
}

const backClick =() =>{
  console.log('back');
  
  wx.navigateBack({  
      delta: 1,  // 返回上一页 
  });
}

</script>

<style lang="scss" scoped>
.back-icon {
  height: 108rpx;
  position: fixed;
  width: 100%;
  padding: 0 34rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 99;
}
.normal-login-container {
  width: 100vw;
  height: 100vh;
  border-radius: 48rpx;
  background: linear-gradient(156deg, #f5c954 -4%, #f66c44 110%);
  position: relative;
  overflow-x: hidden;

  .wave-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
  }

  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;

  .logo-image {
    width: 232rpx;
    height: 201rpx;
    margin-top: 47rpx;
    margin-bottom: -10rpx;
    margin-right: 300rpx;
    margin-left: 300rpx;
  }

  .title {
    width: 360rpx;
    height: 128rpx;
    font-family: Poppins;
    font-size: 90rpx;
    font-weight: 600;
    line-height: 127.81rpx;
    letter-spacing: normal;
    color: #FFFFFF;
    z-index: 1;
    margin-top: 0;
    margin-bottom: 82rpx;
    margin-right: 195rpx;
    margin-left: 195rpx;
  }
}

.house-illustration {
  width: 720rpx;
  height: 334rpx;
  margin-top: 0;
  margin-bottom: 78rpx;
  margin-right: 136rpx;
  margin-left: 136rpx;
}

.slogan-content {
  margin-top: 0;
  margin-bottom: 235rpx;
  margin-right: 300rpx;
  margin-left: 300rpx;
  z-index: 1;

  .slogan-text {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 448rpx;
    height: 52rpx;
    font-family: Poppins;
    font-size: 32rpx;
    font-weight: 600;
    line-height: 52rpx;
    text-align: center;
    letter-spacing: normal;
    color: #824727;
  }
}

.actions-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  z-index: 1;
}

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

.text-blue {
  color: #1976d2;
  margin: 0 4rpx;
}

.text-grey1 {
  color: #333333;
}

.text-center {
  text-align: center;
}
</style>
