<template>
  <van-nav-bar
        title="重置密码"
    />
    <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>
  <van-form 
    @submit="subNewPwd" 
    class="forget-area"
  >
      <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="newPwd"
        name="newPwd"
        :type="newPwdType"
        :placeholder="pwdPlaceHolder"
        @focus="focusPwd"
        @blur="blurPwd"
        :rules="[{ 
          required: true, 
          message: '请输入新密码！',
          validator: iptPwd
        }]"
        autocomplete="off"
        clearable
        style="margin-top: 0.5rem; border: 1px solid #62b0b0; background-color: #f3f9f9; font-size: 16px;"
      >
        <template #button>
            <van-button
              style="font-size: 16px; background-color: transparent; color: #1989fa; border: none;"
              size="small" 
              type="primary"
            >
              <span v-if="newPwdStatus === 0" @click="showNewPwd">查看</span>
              <span v-if="newPwdStatus === 1" @click="hideNewPwd">隐藏</span>
            </van-button>
        </template>
      </van-field>
      <van-field
        v-model="confirmNewPwd"
        name="confirmNewPwd"
        type="password"
        :placeholder="confirmPwdPlaceHolder"
        @focus="focusConfirmPwd"
        @blur="blurConfirmPwd"
        :rules="[{ 
          required: true, 
          message: '请确认新密码！' ,
          validator: confirmPwd
        }]"
        autocomplete="off"
        style="margin-top: 0.5rem; border: 1px solid #62b0b0; background-color: #f3f9f9; font-size: 16px;"
      >
      </van-field>
      <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="sendCode"
            :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="btn-area">
        <van-button 
          type="primary"
          native-type="submit"
          style="width: 70%; border-radius: 0.5rem; font-size: 18px;"
        >
          确认修改
        </van-button>
      </div>
  </van-form>
</template>

<script setup lang="ts">

  import { showToast } from 'vant';
  import { ref, onMounted } from 'vue'
  import { editNewPwd, sendVeriCode } from '../../api/ForgetPassword'
  import { useRouter, useRoute } from 'vue-router'
  import './scss/index.scss'
  import Crypoto from '../../api/AesCbc'
  
  const cry: any = new Crypoto()

  const phoneNumPlaceHolder = ref<string>('请输入手机号')
  const pwdPlaceHolder = ref<string>('请输入新密码')
  const confirmPwdPlaceHolder = ref<string>('请确认新密码')
  const veriPlaceHolder = ref<string>('验证码')
  const router = useRouter()
  const route = useRoute()
  const phoneNumber = ref<any>('')
  const newPwd = ref<any>('')
  const confirmNewPwd = ref<any>('')
  const verifyNum = ref<any>('')
  const countStatus = ref<number>(0)
  const countSecond = ref<number>(60)
  const veriBtnDisable = ref<boolean>(false)
  const sendData = ref<any>({})
  const time = ref<any>('发送验证码')
  const pwdPattern = /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&*]+$)(?![\d!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/

  const newPwdType = ref<any>('password')
  const newPwdStatus = ref<number>(0)

  // 新密码框显示密码
  const showNewPwd = () => {
    newPwdType.value = 'input'
    newPwdStatus.value = 1
  }

  // 新密码框隐藏密码
  const hideNewPwd = () => {
    newPwdType.value = 'password'
    newPwdStatus.value = 0
  }

  // 输入框获取焦点
  const focusPhoneNum = () => {
    phoneNumPlaceHolder.value = ''
  }
  const focusPwd = () => {
    pwdPlaceHolder.value = ''
  }
  const focusConfirmPwd = () => {
    confirmPwdPlaceHolder.value = ''
  }
  const focusVeri = () => {
    veriPlaceHolder.value = ''
  }

  // 输入框失去焦点
  const blurPhoneNum = () => {
    phoneNumPlaceHolder.value = '请输入手机号'
  }
  const blurPwd = () => {
    pwdPlaceHolder.value = '请输入新密码'
  }
  const blurConfirmPwd = () => {
    confirmPwdPlaceHolder.value = '请确认新密码'
  }
  const blurVeri = () => {
    veriPlaceHolder.value = '验证码'
  }

  // 提交表单
  const subNewPwd = (val: any) => {
    if (Number(verifyNum.value) !== Number(localStorage.getItem('veriCode')) // 验证码输入错误
        || phoneNumber.value === null // 手机号不能为空
        || !localStorage.getItem('veriCode') // 本地存储为空
        || newPwd.value !== confirmNewPwd.value // 两个密码不相符
        || phoneNumber.value.length !== 11 // 手机号长度不符
        || verifyNum.value == '' // 验证码不能为空
    ) {
      showToast({
        message: '手机号或验证码不正确！',
        icon: 'fail',
        duration: 1500,
        onClose: () => {
          verifyNum.value = ''
        }
      })
    } else if (newPwd.value == 'YNsbd@123456' || confirmNewPwd.value == 'YNsbd@123456') {
      showToast({
        message: '新密码请勿与初始密码设置一致！',
        icon: 'fail',
        duration: 2000,
        onClose: () => {
          newPwd.value = ''
          confirmNewPwd.value = ''
        }
      })
    } else {
      console.log('修改成功', val.newPwd)
      sendData.password = val.newPwd
      sendData.telephone = val.phoneNumber
      console.log(sendData.password, sendData.telephone)
      editNewPwd({
        password: sendData.password,
        telephone: sendData.telephone
      }).then((res: any) => {
        console.log(res)
        if (res.data.obj.num === 1) {
          showToast({
            message: res.data.resMsg,
            icon: 'success',
            duration: 1500,
            onClose: () => {
              localStorage.removeItem('veriCode')
              router.push('/accountLogin')
            }
          })
        } else {
          showToast({
            message: '修改密码失败！',
            icon: 'fail',
            duration: 1500
          })
        }
      }).catch((err: any) => {
        console.log(err)
      })
    }
  }

  // 输入密码校验
  const iptPwd = (val: any) => {
    if (!pwdPattern.test(val)) {
      showToast({
        message: '密码必须包含大小写字母、特殊字符和数字！',
        icon: 'fail',
        duration: 3000,
        onClose: () => {
          newPwd.value = ''
        }
      })
    }
  }

  // 确认密码校验
  const confirmPwd = (val: any) => {
    if (val !== newPwd.value) {
      showToast({
        message: '请确认密码保持一致！',
        icon: 'fail',
        duration: 1500,
        onClose: () => {
          confirmNewPwd.value = ''
        }
      })
    }
  }

  // 发送验证码
  const sendCode = () => {
    console.log(phoneNumber.value.length)
    if (phoneNumber.value.length !== 11) {
      showToast({
        message: '请输入正确格式的手机号！',
        icon: 'fail',
        duration: 1500,
        onClose: () => {
          phoneNumber.value = ''
        }
      })
    } else {
      veriBtnDisable.value = true
      sendVeriCode({
        telephone: phoneNumber.value
      }).then((res: any) => {
        console.log(res)
        // 后台返回data为空时，说明数据库中不存在此号码，给出提示
        if (res.data === '') {
          showToast({
            message: '此人员不在系统中，请联系后台管理员添加账号！',
            icon: 'fail',
            duration: 3000,
            onClose: () => {
              phoneNumber.value = '',
              veriBtnDisable.value = false
            }
          })
        } else {
          // 设置验证码60s倒计时
          localStorage.setItem('veriCode', res.data)
          countStatus.value = 1
          const timeOut = setTimeout(() => {
            localStorage.removeItem('veriCode')
            countStatus.value = 0
            countSecond.value = 60
            veriBtnDisable.value = false
            clearInterval(interval)
            clearTimeout(timeOut)
          }, 60 * 1000)
          const interval =  setInterval(() => {
            countSecond.value -= 1
          }, 1000)
        }
      }).catch((err: any) => {
        console.log(err)
      })
    }
    
  }

  onMounted(() => {
    console.log(route.query.phoneNum)
    if (route.query) {
      phoneNumber.value =  cry.decrypt(route.query.phoneNum)
    } else {
      phoneNumber.value = ''
    }
  })

</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;
      margin-bottom: 7rem;
		  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;
			}
		}
  .forget-area{
    width: 80%;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 7rem 0.5rem;
  }
  .btn-area{
        width: 100%;
        margin-top: 1rem;
        display: flex;
        justify-content: center;
      }
</style>