<template>
  <view class="form">
    <uv-form labelPosition="left" :model="form" :rules="rules" ref="formRef" labelWidth="120">
      <uv-form-item label="新密码" prop="p1" borderBottom>
        <uv-input v-model="form.p1" type="password" border="none" clearable />
      </uv-form-item>
      <uv-form-item label="确认密码" prop="p2" borderBottom>
        <uv-input v-model="form.p2" type="password" clearable border="none" />
      </uv-form-item>
      <uv-form-item>
        <view>密码由8~16位含有大小写字母、数字、!#$%^&*@符号且不能有三位连续的数字组成</view>
      </uv-form-item>
      <uv-button
        text="提交"
        color="#6eb657"
        customStyle="margin-top: 10px"
        @click="submit"
      ></uv-button>
    </uv-form>
  </view>
</template>

<script setup lang="ts">
import { renewPwdApi } from '@/service/modules/mine'
import { reactive, ref } from 'vue'

import useLogiutFn from '@/hooks/useLoginout'

const form = reactive({
  p1: '',
  p2: '',
  code: '123456'
})
let validatePassword = (rule: any, value: any, callback: any) => {
  var regA = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!#$%^&*@])[\da-zA-Z!#$%^&*@]{8,16}$/ //密码必须是8位以上、必须含有字母、数字、特殊符号
  var regB = /(123|234|345|456|567|678|789|012)/ //不能有3个连续数字
  if (!value) {
    callback(new Error('密码不能为空'))
  }
  if (!regA.test(value)) {
    callback(new Error('密码必须是8~16位、必须含有大小写字母、数字、特殊符号'))
  } else if (regB.test(value)) {
    callback(new Error('不能有3个连续数字'))
  } else {
    callback()
  }
}
var validateCheckPass = (rule: any, value: any, callback: any) => {
  if (value !== form.p1) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}
const rules = reactive({
  p1: {
    type: 'string',
    required: true,
    trigger: ['blur'],
    validator: validatePassword
  },
  p2: {
    type: 'string',
    required: true,
    validator: validateCheckPass,
    trigger: ['blur']
  }
})

const formRef = ref()

const submit = () => {
  formRef.value.validate().then(async () => {
    const res = await renewPwdApi(form)
    if (res.code === 0) {
      uni.showToast({
        icon: 'none',
        title: '修改成功，请重新登录'
      })
      setTimeout(async () => {
        useLogiutFn()
      }, 1000)
    }
  })
}
</script>

<style lang="scss" scoped>
.form {
  padding: 30rpx;
}
</style>
