<template>
  <div class="login">
    <van-nav-bar title="自然人开票" />

    <div class="login-content">
      <div class="text">感谢您参加{{ pubName }}项目，请您登录系统开具发票。</div>

      <div class="bold-text">已注册电子税务局</div>

      <div class="form">
        <!-- 手机号输入 -->
        <van-cell-group inset class="grop">
          <van-field
            class="input"
            v-model="formData.mobile"
            placeholder="请输入手机号"
            clearable
            type="tel"
            maxlength="30"
            @update:model-value="onInputMobile"
          />
        </van-cell-group>

        <!-- 验证码输入 + 按钮 -->
        <van-cell-group inset class="grop">
          <van-field
            class="input code-input"
            v-model="formData.code"
            placeholder="请输入验证码"
            clearable
            type="tel"
            maxlength="6"
            @update:model-value="onInputCode"
          />
          <button class="code-btn" :disabled="isCounting || !formData.mobile" @click="sendCode">
            {{ isCounting ? countDown + 's后重发' : '获取验证码' }}
          </button>
        </van-cell-group>

        <!-- 同意协议 -->
        <div class="agree">
          <label>
            <van-checkbox v-model="agree" checked-color="#fe783d" shape="square" icon-size="4vw">
              我已阅读并同意
              <a @click="toAgreement('auth')">《授权协议》</a>
              <a @click="toAgreement('privacy')">《隐私权政策》</a>
            </van-checkbox>
          </label>
        </div>

        <!-- 登录按钮 -->
        <div class="login-btn btn" @click="login">登录</div>
      </div>

      <div class="bold-text">未注册电子税务局</div>
      <div class="register-btn btn">立即注册</div>

      <div class="footer">技术支持：要易云（北京）科技有限公司</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showFailToast, showSuccessToast, showToast } from 'vant'
import { getPubNameApi, sendEtsSmsApi, loginEtssmsApi } from '@/services/modules/login'
import type { SendTtsSmsRequest, LoginEtssmsRequest } from '@/services/modules/login/type.d'
import { useUserStore } from '@/stores/modules/user'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

/* 表单数据 */
const formData = reactive<LoginEtssmsRequest>({
  mobile: '',
  code: '',
})

const sendEtsSms = reactive<SendTtsSmsRequest>({
  mobile: '',
  pushRecordId: '',
})

/* 限制手机号只能输入数字，最多 30 位 */
const onInputMobile = (val: string) => {
  formData.mobile = val.replace(/\D/g, '').slice(0, 30)
}

/* 限制验证码只能输入数字，最多 6 位 */
const onInputCode = (val: string) => {
  formData.code = val.replace(/\D/g, '').slice(0, 6)
}

/* 是否同意协议 */
const agree = ref(false)

/* 验证码按钮逻辑 */
const isCounting = ref(false)
const countDown = ref(60)
let timer: number | undefined

/* 发送验证码 */
const sendCode = async () => {
  if (!/^1\d{10}$/.test(formData.mobile)) {
    showToast('请输入正确的手机号')
    return
  }
  sendEtsSms.mobile = formData.mobile
  const res = await sendEtsSmsApi(sendEtsSms)
  if (res.code === 0 && res.data) {
    showSuccessToast('发送成功')
    startCountDown()
  } else {
    showFailToast(res.data.msg)
  }
}

/* 倒计时逻辑 */
const startCountDown = () => {
  isCounting.value = true
  countDown.value = 60
  timer = window.setInterval(() => {
    countDown.value--
    if (countDown.value <= 0) {
      isCounting.value = false
      clearInterval(timer)
    }
  }, 1000)
}

/* 登录逻辑 */
const login = async () => {
  if (!formData.mobile) {
    showFailToast('请输入手机号和验证码')
    return
  }
  if (!formData.code) {
    showFailToast('验证码不能为空')
    return
  }

  if (!agree.value) {
    showFailToast('请勾选阅读并同意')
    return
  }

  try {
    const res: any = await loginEtssmsApi(formData)
    if (res?.access_token) {
      userStore.setAccessToken(res.access_token)
      router.replace({ path: '/invoice-information' })
    }
  } catch (err: any) {
    const { code, message } = err
    if (code && message) {
      showFailToast(message)
    }
  }
}

// 项目名称
const pubName = ref('')
const getPubName = async () => {
  try {
    const res = await getPubNameApi({
      pushRecordId: sendEtsSms.pushRecordId,
    })
    if (res.code === 0) {
      pubName.value = res.data.projectName
    }
  } catch (err) {
    console.log('err', err)
  }
}
/* 协议跳转 */
const toAgreement = (type: string) => {
  router.push({
    path: '/agreement',
    query: { type },
  })
}

onBeforeMount(() => {
  const pushRecordId = route?.query.pushRecordId || ''
  if (pushRecordId) {
    sendEtsSms.pushRecordId = pushRecordId as string
    userStore.setPushRecordId(pushRecordId as string)
    getPubName()
  } else {
    showToast('登录链接存在不完整或者输入错误，请重新复制链接登录')
  }
})
</script>

<style lang="scss" scoped>
.login {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #ffffff 0%, #f5f7fb 100%);
  overflow-x: hidden;

  .van-nav-bar {
    background-color: #fff;
    border-bottom: 1px solid #f2f2f2;
    font-weight: 600;
  }

  .login-content {
    flex: 1;
    padding: 6vw 6vw 12vw;
    display: flex;
    flex-direction: column;
    align-items: center;

    .text {
      width: 90%;
      font-size: 4vw;
      text-align: center;
      line-height: 6vw;
      color: #333;
      margin-top: 8vw;
      margin-bottom: 6vw;
    }

    .bold-text {
      width: 100%;
      font-weight: 700;
      font-size: 4.5vw;
      text-align: left;
      color: #222;
      margin: 4vw 0 2vw;
    }

    .form {
      width: 96%;
      margin-top: 20px;
      background: #fff;
      border-radius: 3vw;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      padding: 6vw 4vw;
      margin-bottom: 8vw;

      .grop {
        margin-top: 3vw;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .input {
        width: 100%;
        border-radius: 6vw;
        border: 1px solid #e5e5e5;
        padding-left: 5vw;
        font-size: 3.8vw;
        background: #fff;
        transition: 0.3s;
        &:focus {
          border-color: #fe783d;
          box-shadow: 0 0 8px rgba(254, 120, 61, 0.3);
        }
      }

      .code-input {
        width: 55%;
      }

      .code-btn {
        background: linear-gradient(90deg, #fe783d 0%, #ff994f 100%);
        border: none;
        border-radius: 25px;
        height: 9vw;
        width: 30%;
        color: #fff;
        font-weight: 600;
        font-size: 3.4vw;
        cursor: pointer;
        transition: all 0.3s;
        &:active {
          opacity: 0.85;
        }
        &:disabled {
          background: #ccc;
          cursor: not-allowed;
        }
      }

      .agree {
        text-align: left;
        font-size: 3vw;
        line-height: 5vw;
        margin: 4vw 0;
        color: #666;
        padding-left: 36px;
        .custom-checkbox {
          accent-color: #fe783d;
        }
        label {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          input {
            width: 3.5vw;
            height: 3.5vw;
            margin-right: 6px;
          }
        }
        a {
          color: #fe783d;
          text-decoration: none;
          margin-left: 2px;
        }
      }
    }

    .btn {
      box-sizing: border-box;
      width: 80%;
      height: 12vw;
      border-radius: 6vw;
      color: #fff;
      font-size: 4vw;
      line-height: 12vw;
      text-align: center;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      margin: 4vw 0;
      &:active {
        transform: scale(0.98);
      }
    }

    .login-btn {
      margin: 0 auto;
      background: linear-gradient(90deg, #ff8036 0%, #ffa253 100%);
      box-shadow: 0 4px 12px rgba(255, 128, 54, 0.3);
    }

    .register-btn {
      background: linear-gradient(90deg, #0072f8 0%, #3a9fff 100%);
      box-shadow: 0 4px 12px rgba(0, 114, 248, 0.25);
    }

    .footer {
      width: 100%;
      text-align: center;
      color: #999;
      font-size: 3vw;
      margin-top: auto;
      padding-bottom: 4vh;
    }
  }
}
</style>
