<template>
  <!-- <view class="title_bar">
		<Title-bar :titleCenter="true" :canBack="false" title="登录" />
	</view> -->
  <mj-page class="login_page">
    <view class="title"> 欢迎使用学小乐 </view>
    <view class="login_form">
      <view class="login_form_item">
        <view class="left">
          <image
            :src="`${OSS_URL}/iconfont/phone_icon.png`"
            mode=""
            class="login_form_item_icon"
          ></image>
          <input
            v-model="formatPhone"
            class="input_box"
            type="text"
            placeholder="请输入手机号"
            placeholder-style="color:rgba(169, 170, 181, 1);text-align: left;font-size:30rpx;"
            @input="phoneDivision"
          />
        </view>
      </view>
      <view class="login_form_item">
        <view class="left">
          <image
            :src="`${OSS_URL}/iconfont/code_icon.png`"
            mode=""
            class="login_form_item_icon"
          ></image>
          <input
            v-model="loginForm.verifyCode"
            class="input_box"
            type="number"
            placeholder="请输入验证码"
            placeholder-style="color:rgba(169, 170, 181, 1);text-align: left;font-size:30rpx;"
          />
        </view>
        <view class="code_btn">
          <template v-if="codeTime > 0">
            <text class="time_tip">{{ codeTimeContet }} 秒后重新发送</text>
          </template>
          <template v-else>
            <text class="time_tip" @click="getCode">获取验证码</text>
          </template>
        </view>
      </view>
      <button class="phone_btn" @click="handleLogin">登录</button>
    </view>

    <!-- 多层身份弹窗 -->
    <wd-popup
      v-model="adminPopup"
      safe-area-inset-bottom
      position="bottom"
      custom-style="border-radius: 20px 20px 0 0;padding-bottom: 30px;"
    >
      <view class="popup_box">
        <view class="header_title"> 请选择身份 </view>
        <view class="method_list">
          <view v-for="(i, idx) in userAdmin" :key="idx" class="item" @click="chooseAdmin(i)">
            {{ i.adminTypeName }}
          </view>
        </view>
      </view>
    </wd-popup>
  </mj-page>
</template>

<script setup lang="tsx">
import { ref, computed, nextTick, onMounted } from 'vue'

import {
  getBindPhoneTypeApi,
  sendCodeMessageApi,
  getAdminTypeByPhoneApi,
  smsLoginApi,
  getUserInfoApi,
  getAuthUrlApi,
} from '@/api'
import { setCache, getCache } from '@/utils'
import { getUserInfo as dx_getUserInfoApi } from '@/api/inspector/mine'
import { user } from '@/store'
import router from '@/router/router'
import db from '@/utils/db'
import hud from '@/utils/hud'

const emits = defineEmits(['reloadFun'])
const OSS_URL = import.meta.env.VITE_OSS_HOST
const { getUserInfo, setToken } = user()

const formatPhone = ref('')
const adminPopup = ref()
const userAdmin = ref([]) // 用户身份列表
const loginForm = ref({
  adminType: 16, // 家长
  clientType: 'MOBILE',
  phone: '',
  verifyCode: '',
})
const codeTime = ref(0)
const codeTimeContet = computed(() => {
  return codeTime.value
})

function validatePhone() {
  loginForm.value.phone = formatPhone.value.replace(/\s+/g, '')
  let reg = /^[1][0,1,2,3, 4, 5, 6, 7, 8, 9][0-9]{9}$/
  return reg.test(loginForm.value.phone)
}
// 手机344分割
function phoneDivision() {
  nextTick(() => {
    let value = formatPhone.value.replace(/\D/g, '').substr(0, 11)
    let len = value.length // 获取长度判断
    if (len > 3 && len < 8) {
      value = value.replace(/^(\d{3})/g, '$1 ')
    } else if (len >= 8) {
      value = value.replace(/^(\d{3})(\d{4})/g, '$1 $2 ')
    }
    formatPhone.value = value
  })
}
// 督学师个人资料
async function fetchDXUserInfo() {
  const { data } = await dx_getUserInfoApi()
  db.set('dxs_userInfo', data)
}
// 获取验证码
async function getCode() {
  loginForm.value.phone = formatPhone.value.replace(/\s+/g, '')
  if (!loginForm.value.phone) {
    uni.showToast({
      icon: 'none',
      title: '请输入手机号',
    })
    return
  }
  try {
    await sendCodeMessageApi(loginForm.value.phone)
    hud.success('发送成功！')
    codeTime.value = 60
    let timer = setInterval(() => {
      codeTime.value--
      if (codeTime.value < 1) {
        clearInterval(timer)
        codeTime.value = 0
      }
    }, 1000)
  } catch (err) {
    console.log(err)
  }
}
// 登录
async function handleLogin() {
  if (!validatePhone() || !loginForm.value.verifyCode) {
    uni.showToast({
      icon: 'none',
      title: '账号或验证码不正确',
    })
    return
  }
  uni.showLoading({
    title: '登录中...',
  })
  getAdminTypeByPhone()
}
// 用户身份
async function getAdminTypeByPhone() {
  const res = await getAdminTypeByPhoneApi({
    phone: loginForm.value.phone,
  })
  userAdmin.value = res.data
  if (userAdmin.value.length <= 1) {
    // 非多个身份
    loginForm.value.adminType = userAdmin.value[0].adminType
    await smsLogin()
    if (loginForm.value.adminType === 6) return
  } else {
    // 多个身份
    uni.hideLoading()

    adminPopup.value = true
  }
}
async function smsLogin() {
  uni.showLoading({
    title: '登录中...',
  })
  const res = await smsLoginApi(loginForm.value)
  setToken(res.data)
  const data = await getUserInfo()

  if (!data.openid) {
    // 初次注册
    const authRes = await getAuthUrlApi()
    // #ifdef H5
    window.location.href = authRes.data
    // #endif
    // if (data.adminType === 16) {
    //   const authRes = await getAuthUrlApi();
    //   // #ifdef H5
    //   window.location.href = authRes.data;
    //   // #endif
    // } else {
    //   fetchDXUserInfo();
    //   uni.reLaunch({
    //     url: '/pages/inspector/schedule/index',
    //   });
    // }
  } else {
    router.reLaunch('/pages/home/index')
    // let adminType = getCache('userInfo').adminType;
    // if (adminType === 16) {
    //   uni.reLaunch({
    //     url: '/pages/home/index',
    //   });
    // } else if (adminType === 6) {
    //   fetchDXUserInfo();
    //   uni.reLaunch({
    //     url: '/pages/inspector/schedule/index',
    //   });
    // }
  }
  uni.hideLoading()
}
async function chooseAdmin(i) {
  loginForm.value.adminType = i.adminType
  adminPopup.value = false
  await smsLogin()
  if (loginForm.value.adminType === 6) return
}
</script>

<style lang="scss" scoped>
.title_bar {
  z-index: 99;
}

.login_page {
  margin-top: 120rpx;

  .title {
    margin-bottom: 87rpx;
    line-height: 56rpx;
    font-size: 40rpx;
    font-weight: 500;
    color: #333;
    text-align: center;
  }

  .login_form {
    padding: 0 30rpx;

    &_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24rpx 30rpx;
      margin-bottom: 40rpx;
      background-color: #fff;
      border-radius: 20rpx;

      .left {
        display: flex;
        align-items: center;

        .input_box {
          text-align: left;
          color: rgba(51, 51, 51, 1);
          font-size: 30rpx;
          line-height: 42rpx;
        }
      }

      &_icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 20rpx;
      }

      .code_btn {
        color: rgba(97, 93, 255, 1);
        font-size: 30rpx;
        line-height: 42rpx;
        .time_tip {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .phone_btn {
      margin: 60rpx 0 0 0;
      height: 90rpx;
      width: 100%;
      line-height: 90rpx;
      background-color: #615dff;
      color: #fff;
      font-size: 30rpx;
      border-radius: 20rpx;
    }
  }

  .popup_box {
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;

    .header_title {
      margin: 30rpx 0 0 30rpx;
      color: rgba(51, 51, 51, 1);
      font-size: 32rpx;
      font-weight: 500;
      text-align: left;
    }

    .method_list {
      text-align: center;
      padding: 0 54rpx;

      .item {
        padding: 30rpx 0;
        border-bottom: 1rpx solid rgba(235, 235, 235, 1);
        font-weight: 400;
        height: 45rpx;
        color: rgba(51, 51, 51, 1);
      }
    }
  }
}
</style>
