<template>
  <div>
    <div class="background">
			<div class="block_3 flex-col">
			    <div class="section_1 flex-col"></div>
			    <div class="section_2 flex-col"></div>
			    <div class="section_3 flex-col"></div>
			</div>
		</div>
    <h2 class="log-tit">体检预约</h2>
    <van-form @submit="logPhoneSub" class="log-form">
      <van-field
        v-model="phoneNumber"
        name="phoneNumber"
        :placeholder="phoneNumPlaceHolder"
        @focus="focusPhoneNum"
        @blur="blurPhoneNum"
        :rules="[{ required: true, message: '请填写手机号！' }]"
        autocomplete="off"
        clearable
        style="border: 1px solid #62b0b0; background-color: #f3f9f9; font-size: 16px;"
      />
      <van-field
        v-model="verifyNum"
        name="verifyNum"
        :placeholder="veriPlaceHolder"
        @focus="focusVeri"
        @blur="blurVeri"
        :rules="[{ required: true }]"
        autocomplete="off"
        style="margin-top: 0.5rem; border: 1px solid #62b0b0; background-color: #f3f9f9; font-size: 16px; display: flex; align-items: center;"
      >
        <template #button>
          <van-button 
            style="border-radius: 0.8rem" 
            size="small" 
            type="primary"
            @click="sendVeriCode"
            :disabled="veriBtnDisable"
          >
            <span v-if="countStatus === 0">{{ time }}</span>
            <span v-if="countStatus === 1">
              <span>{{ countSecond }}</span>
              s
            </span> 
          </van-button>
        </template>
      </van-field>
      <div class="user-taps">
        <span @click="jumpForget()">忘记密码</span>
        <span @click="jumpAccount()">账号密码登录</span>
      </div>
      <div class="btn-area">
        <van-button 
          type="primary"
          native-type="submit"
          style="width: 70%; border-radius: 0.5rem; font-size: 18px;"
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">

  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { sendPhoneVeri, logWithMsg } from '../../api/MsgLogin'
  import Crypoto from '../../api/AesCbc'
  import { showToast, showFailToast } from 'vant';
  import './scss/index.scss'

  const cry: any = new Crypoto()
  const phoneNumPlaceHolder = ref<string>('手机号')
  const veriPlaceHolder = ref<string>('验证码')
  const phoneNumber = ref<any>('')
  const verifyNum = ref<any>('')
  const router = useRouter()
  const time = ref<any>('发送验证码')
  const countStatus = ref<number>(0)
  const countSecond = ref<number>(60)
  const veriBtnDisable = ref<boolean>(false)
  const msgInfo = ref<any>({})

  // 输入框获得焦点
  const focusPhoneNum = () => {
    phoneNumPlaceHolder.value = ''
  }
  const focusVeri = () => {
    veriPlaceHolder.value = ''
  }

  // 输入框失去焦点
  const blurPhoneNum = () => {
    phoneNumPlaceHolder.value = '手机号'
  }
  const blurVeri = () => {
    veriPlaceHolder.value = '验证码'
  }

  // 跳转到忘记密码
  const jumpForget = () => {
    router.push({
      path: '/forgetPassword'
    })
  }

  // 跳转到账号密码登录
  const jumpAccount = () => {
    router.push({
      path: '/accountLogin'
    })
  }

  // 点击发送验证码
  const sendVeriCode = () => {
    if (phoneNumber.value.length !== 11) {
      showToast({
        message: '请输入正确格式的手机号！',
        icon: 'fail',
        duration: 1500, 
        onClose: () => {
          phoneNumber.value = ''
        }
      })
    } else {
      veriBtnDisable.value = true
      sendPhoneVeri({
        telephone: phoneNumber.value
      }).then((res: any) => {
        console.log(res)
        if (res.data === '') {
          showToast({
            message: '此人员不在系统中，请联系后台管理员添加账号！',
            icon: 'fail',
            duration: 3000,
            onClose: () => {
              phoneNumber.value = ''
              veriBtnDisable.value = false
            }
          })
        } else {
          // 设置验证码60s倒计时
          localStorage.setItem('veriPhoneCode', res.data)
          countStatus.value = 1
          const phoneTimeOut = setTimeout(() => {
            localStorage.removeItem('veriPhoneCode')
            countStatus.value = 0
            countSecond.value = 60
            veriBtnDisable.value = false
            clearInterval(phoneInterval)
            clearTimeout(phoneTimeOut)
          }, 60 * 1000)
          const phoneInterval = setInterval(() => {
            countSecond.value -= 1
          }, 1000)
        }
      }).catch((err: any) => {
        console.log(err)
      })
    }
  }

  // 提交表单
  const logPhoneSub = (val: any) => {
    // 条件判断
    if (Number(verifyNum.value) !== Number(localStorage.getItem('veriPhoneCode'))
        || phoneNumber.value === null // 手机号不能为空
        || !localStorage.getItem('veriPhoneCode') // 本地存储为空
        || phoneNumber.value.length !== 11 // 手机号长度不符
    ) {
      showToast({
        message: '手机号或验证码不正确！',
        icon: 'fail',
        duration: 1500,
        onClose: () => {
          verifyNum.value = ''
        }
      })
    } else {
      console.log('修改成功！', val)
      msgInfo.telephone = val.phoneNumber
      // 短信登录接口
      logWithMsg({
        telephone: cry.encrypt(msgInfo.telephone)
      }).then((res: any) => {
        console.log(res)
        if (res.data.resMsg === 'success') {
          showToast({
            message: '登录成功！',
            icon: 'success',
            duration: 1500,
            onClose: () => {
              localStorage.setItem('token', res.data.obj)
              localStorage.setItem('avatarUrl', 'https://img.zcool.cn/community/0104c958b69c23a801219c77ba5da2.png?x-oss-process=image/auto-orient,1/resize,m_lfit,w_1280,limit_1/sharpen,100')
              localStorage.setItem('phoneNumber', msgInfo.telephone)
              localStorage.removeItem('veriPhoneCode')
              // 设置登录状态码持续时间为3h
              const overDate = new Date().getTime() - 8 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000
              document.cookie = `loginStatus=0;expires=${new Date(overDate)}`
              router.replace({
                path: '/home'
              })
            }
          })
        }else{
			showFailToast('登录失败！没有找到这个号码')
		}
      }).catch(() => {
        showFailToast('登录失败！')
      })
    }
  }

  onMounted(() => {
    
  })

</script>

<style scoped lang="scss">
  .background {
      width: 10rem;
		  height: 8rem;
		  background: url('../../static/bg.jpg')
		    100% no-repeat;
		  background-size: 100% 100%;
		  width: 100%;
		  position: absolute;
		  left: 0;
		  top: 0;
		  .section_1 {
			  background-color: rgba(255, 255, 255, 0.1);
			  border-radius: 50%;
			  width: 4rem;
			  height: 4rem;
			  position: absolute;
			}
		
		.section_2 {
			  background-color: rgba(255, 255, 255, 0.1);
			  border-radius: 50%;
			  position: absolute;
			  left: 0.1rem;
			  top: 1.2rem;
			  width: 6rem;
			  height: 6rem;
			}
		
		.section_3 {
			  background-color: rgba(255, 255, 255, 0.0624);
			  border-radius: 50%;
			  position: absolute;
			  left: 6rem;
			  top: 0.5rem;
			  width: 4rem;
			  height: 4rem;
			}
		}
    .log-tit{
      width: 100%;
      padding-top: 4rem;
      text-align: center;
      font-size: 30px;
      font-weight: bold;
    }
    .log-form{
      width: 80%;
      height: 8rem;
      margin: 3.5rem auto;
      box-sizing: border-box;
      padding: 0.5rem;
      .user-taps{
        width: 100%;
        margin-top: 0.3rem;
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 0.2rem;
        span{
          font-size: 14px;
          color: #49b3f2;
        }
      }
      .btn-area{
        width: 100%;
        margin-top: 0.6rem;
        display: flex;
        justify-content: center;
      }
    }
</style>