<template>
  <view class="normal-login-container">
    <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>

        <!-- 备用方案：使用原生checkbox -->
        <!-- <checkbox :checked="checkboxValue.value" @change="onNativeChange" style="transform:scale(0.7)" />
        <text class="text-grey1">我已认真阅读、理解并同意</text> -->

        <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';
const imagePath = '/static/9efd1.png' // Path to the logo image (red tree)

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


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

// const codeUrl = ref(""); // Not used in the new design
// const captchaEnabled = ref(true); // Not used in the new design

const router = useRouter()

// 获取小程序码参数
onLoad((options) => {
  console.log('onLoad options:', options)
  // 处理从二维码扫描进入的场景
  if (options.scene) {
    const scene = decodeURIComponent(options.scene)
    const params = scene.split(':')
    if (params.length >= 2) {
      loginForm.referrerType = params[0]
      loginForm.referrerId = params[1]
      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 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


  // 获取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
  }
  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', 0)
  // 设置状态栏为透明
  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
}


</script>

<style lang="scss" scoped>
.normal-login-container {
  // border: 2px solid red;
  width: 100vw;
  height: 100vh;
  // 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>
