<script setup>
import { useRouter } from "vue-router"
import {checkPassWord} from '@/utils/common'
import {apiSystemUser} from '@/api/system'
import { Base64 } from 'js-base64'

const router = useRouter()

const rules = {
  OldPwd: [
    {
      required: true,
      message: "请输入原密码",
      trigger: "blur",
    },
  ],
  NewPwd: [
    {
      validator: (rule, value, callback) => {
        if (!checkPassWord(value)) {
          callback(new Error('密码要求8位及以上，包含数字、大写字母、小写字母、特殊字符中的三个类型'))
        } else {
          callback()
        }
      }
    },
    {
      required: true,
      message: "请输入确认密码",
      trigger: "blur",
    },
  ],
  twoNewPwd: [
    {
      required: true,
      message: "请输入确认密码",
      trigger: "blur",
    },
  ],
}
const addForm = reactive({
  OldPwd: '',
  NewPwd: '',
  twoNewPwd: ''
})

const formRef = ref(null)
async function addSubmit() {
  await formRef.value.validate()

  if (addForm.NewPwd != addForm.twoNewPwd) {
    ElMessage.warning("新密码两次输入不一致，请核对！");
    return false;
  }

  const res = await apiSystemUser.modifyPwd({
    OriginPassword:Base64.encode(addForm.OldPwd),
    Password:Base64.encode(addForm.NewPwd),
    RePassword:Base64.encode(addForm.twoNewPwd),
  })
  if (res.Ret == 200) {
    ElMessage.success("修改密码成功,请重新登录！");
    setTimeout(function () {
      localStorage.clear()
      router.replace({ path: "/login" });
    }, 1000);
  }
}

function historyBack() {
  router.go(-1)
}

</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="clearfix">
        <b>修改密码</b>
      </div>
    </template>

    <el-form
      :model="addForm"
      :rules="rules"
      ref="formRef"
      label-width="120px"
      style="width: 500px"
    >
      <el-form-item label="原密码" prop="OldPwd">
        <el-input
          v-model="addForm.OldPwd"
          type="password"
          clearable
          maxlength="20"
          placeholder="请输入不超过20个字符"
          show-password
        />
      </el-form-item>
      <el-form-item label="新密码" prop="NewPwd">
        <el-input
          type="password"
          v-model="addForm.NewPwd"
          placeholder="请输入长度不超过20个字符"
          maxlength="20"
          show-password
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="twoNewPwd">
        <el-input
          type="password"
          v-model="addForm.twoNewPwd"
          placeholder="请输入长度不超过20个字符"
          maxlength="20"
          show-password
          clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item style="text-align: center">
        <el-button type="primary" @click="addSubmit">确定</el-button>
        <el-button type="primary" plain @click="historyBack">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<style scoped lang="scss">
.box-card {
  .el-form-item {
    margin-bottom: 40px;
  }
}
</style>