<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useTokenStore } from '@/store/token'
import { isPageTabbar } from '@/tabbar/store'

definePage({
  style: {
    navigationBarTitleText: '登录',
    navigationStyle: 'custom',
  },
  // 登录页不需要登录即可访问
  excludeLoginPath: true,
})

const tokenStore = useTokenStore()
const mockCode = ref('mock_admin')
const redirectPath = ref('')

onMounted(() => {
  // 获取登录后要跳转的目标页面
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = (currentPage as any).$page?.options || currentPage.options || {}
  if (options.redirect) {
    redirectPath.value = decodeURIComponent(options.redirect)
  }
})

// 登录成功后跳转
function afterLogin() {
  if (redirectPath.value) {
    // 有 redirect 参数，跳转到目标页面
    const url = redirectPath.value
    if (isPageTabbar(url)) {
      uni.switchTab({ url })
    } else {
      uni.redirectTo({ url })
    }
  }
  else {
    uni.navigateBack()
  }
}

// 暂不登录，返回上一页
function handleSkip() {
  uni.navigateBack()
}

// 微信登录
async function handleWxLogin() {
  // #ifdef MP-WEIXIN
  try {
    await tokenStore.wxLogin()
    afterLogin()
  }
  catch (error) {
    console.log('微信登录失败', error)
  }
  // #endif
  // #ifndef MP-WEIXIN
  uni.showToast({ title: '请在微信小程序中使用', icon: 'none' })
  // #endif
}
</script>

<template>
  <view class="login-page h-screen">
    <view class="mx-xl text-center pt-40">
      <wd-img round :width="80" :height="80" src="//wx.qlogo.cn/mmhead/B2EfAOZfS1hcmGxwIBm2jqd7g94iaWziaURo0f8bsAu3GKKIsTY8NMtweRMJ8H7YXBQXfibkrCAKp0/0" />

      <view class="text-white text-2xl font-bold mt-10">四川凌空天行科技有限公司</view>

      <!-- 微信登录 -->
      <view class="mt-20">
        <wd-button
          type="primary"
          size="large"
          block
          round
          @click="handleWxLogin"
        >
          微信一键登录
        </wd-button>

        <view class="mt-4">
          <wd-button
            size="large"
            block
            round
            plain
            @click="handleSkip"
          >
            暂不登录
          </wd-button>
        </view>
      </view>

    </view>

  </view>
</template>

<style lang="scss" scoped>
.login-page {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  background: url('//mmbiz.qpic.cn/sz_mmbiz_png/XekA4rfc3leUkNBAibc5GrYiaq0iaIibtdtbfHFLwJicJ5bLRjpjFDWdaib5ibLtCBSKJ7YA0JnhyK7a5orYOEOMqJy5R2h6zWicvj7HrOOceMibIdPs/0?from=appmsg')
    no-repeat;
  background-size: cover;
}

.brand-section {
  border-radius: 0 0 40% 40% / 30px;
}
</style>
