<script setup lang="ts">
import { type PlusColumn, PlusForm } from "plus-pro-components";
import { onMounted, reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import { updatePassword } from "@/api/user";
import { ElMessage } from "element-plus";
import { md5 } from "js-md5";
import { useUserStoreHook } from "@/store/modules/user";

defineOptions({
  name: "ChangePwd"
});

const route = useRoute();

const defaultValues = {
  account: route.query.account as string
};

onMounted(() => {
  form.value = defaultValues;
});

interface State {
  form: {
    account: string;
    oldPassword: string;
    password: string;
    confirmPassword: string;
  };
}

const state = reactive<State>({
  form: {
    account: "",
    oldPassword: "",
    password: "",
    confirmPassword: ""
  }
});

const { form } = toRefs(state);

const submit = async () => {
  try {
    let params = {
      account: form.value.account,
      oldPassword: md5(form.value.oldPassword).toUpperCase(),
      password: md5(form.value.password).toUpperCase(),
      confirmPassword: md5(form.value.confirmPassword).toUpperCase()
    };
    let res = await updatePassword(params);
    if (res.code === 0) {
      ElMessage.success("修改成功");
      setTimeout(() => {
        useUserStoreHook().logOut();
      }, 1000);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.log(error);
  }
};

const rules = {
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    // 输入8到16位密码，须包括大小写字母、数字和特殊符号
    {
      pattern:
        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,16}$/,
      message: "输入8到16位密码，须包括大小写字母、数字和特殊符号",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        console.log("value", value, form.value.password);
        if (value !== form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const columns: PlusColumn[] = [
  {
    label: "账号",
    prop: "account",
    fieldProps: {
      disabled: true
    }
  },
  {
    label: "旧密码",
    prop: "oldPassword",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  },
  {
    label: "新密码",
    prop: "password",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  },
  {
    label: "确认密码",
    prop: "confirmPassword",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  }
];
</script>

<template>
  <div class="p-5">
    <el-card header="更改密码">
      <PlusForm
        v-model="form"
        :columns="columns"
        :defaultValues="defaultValues"
        label-width="120"
        :rules="rules"
        @submit="submit"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
