<template>
  <view>
    <cu-custom bgImage="/static/bg.png" :isBack="true">
      <template v-slot:content>
        修改密码
      </template>
    </cu-custom>
    <view class="padding">
      <uni-forms ref="pwdFormX" :model="pwdForm" :label-width="80" :rules="rules">
        <uni-forms-item label="旧密码" name="oldPassword">
          <uni-easyinput type="password" v-model="pwdForm.oldPassword"/>
        </uni-forms-item>
        <uni-forms-item label="新密码" name="newPassword">
          <uni-easyinput type="password" v-model="pwdForm.newPassword"/>
        </uni-forms-item>
        <uni-forms-item label="确认密码" name="confirmPassword">
          <uni-easyinput type="password" v-model="pwdForm.confirmPassword"/>
        </uni-forms-item>
        <view class="margin-top text-center">
          <button class="cu-btn bg-cyan lg margin-top" style="width: 100%;" @tap="submit">保存</button>
        </view>
      </uni-forms>
    </view>

  </view>
</template>

<script setup lang="ts">
import CuCustom from '@/colorui/components/cu-custom.vue'
import {reactive, ref} from "vue";
import {useUserStore} from "@/store/userStore";
import UniForms from "@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UserApi from "@/api/UserApi";
import MessageUtils from "@/utils/MessageUtils";

const userStore = useUserStore();
const pwdFormX = ref();
const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const equalToPassword = (rule:any, value:any,data:any, callback:(err?:string)=>{}) => {
  if (pwdForm.newPassword !== value) {
    callback('两次输入的密码不一致')
  } else {
   return true
  }
}
const rules = {
  oldPassword: {
    rules: [
      { required: true, errorMessage: '旧密码不能为空', trigger: 'blur' }
    ]
  },
  newPassword: {
    rules: [
      { required: true, errorMessage: '新密码不能为空', trigger: 'blur' },
      {
        minLength: 3,
        maxLength: 10,
        errorMessage: '长度在 {minLength} 到 {maxLength} 个字符',
      }
    ]
  },
  confirmPassword: {
    rules: [
      { required: true, errorMessage: '确认密码不能为空', trigger: 'blur' },
      { required: true, validateFunction: equalToPassword, trigger: 'blur' }
    ]
  }
}

/** 提交按钮 */
function submit() {
  pwdFormX.value.validate().then(() => {
    UserApi.updateUserPwd(pwdForm.oldPassword, pwdForm.newPassword).then(
        () => {
          pwdForm.oldPassword = '';
          pwdForm.newPassword = '';
          pwdForm.confirmPassword = '';
          MessageUtils.success('修改成功');
          uni.navigateBack()
        }
    )
  })
}
</script>

<style scoped>

</style>
