<template>
  <el-dialog title="修改密码" modal-append-to-body append-to-body v-model="dialogVisible" @close="reset" width="400px">
    <el-form ref="refForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="手机号">
        <el-input :value="maskPhone(shopInfo.phone)" disabled></el-input>
      </el-form-item>
      <el-form-item label="旧密码" prop="originalPassword">
        <el-input type="password" show-password v-model="form.originalPassword" placeholder="请输入旧密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" show-password v-model="form.password" placeholder="请输入新密码"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: -10px;"><el-text :type="isPws ? 'danger' : 'info'" size="small"
          style="line-height: 16px;">注意：新密码必须至少包含字母、数字、特殊符号中的两种，且长度6-18位</el-text></el-form-item>
      <el-form-item label="确认新密码" prop="checkPassword">
        <el-input type="password" show-password v-model="form.checkPassword" placeholder="请再次输入新密码"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div class="center">
          <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
          <captcha-btn type="shopPwd" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="formLoading" @click="submitHandle">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import sysUser from "@/api/account/sysUser";
import { ElNotification } from "element-plus";
import { maskPhone } from "@/utils";
import CaptchaBtn from "./CaptchaBtn.vue";

const props = defineProps({
  // 修改成功后的跳转类型 1- 跳转到登录页 2- 留在当前页
  type: {
    type: [String, Number],
    default: 1
  }
})

const shopInfo = ref({
  phone: ''
})

const router = useRouter();

const dialogVisible = ref(false);
const formLoading = ref(false);

const isPws = ref(false);

const form = reactive({
  id: '',
  originalPassword: "",     // 原密码
  code: '',                 // 验证码
  checkPassword: "",        // 确认新密码
  password: "",             // 新密码
});

function reset() {
  form.originalPassword = "";
  form.checkPassword = "";
  form.password = "";
  form.code = "";
  refForm.value.resetFields();
}

const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,}$/;
const validateNewPass = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!form.password) {
    callback(new Error(" "));
  } else if (form.password === form.originalPassword) {
    callback(new Error("请输入与旧密码不同的新密码"));
  } else if (form.password.length < 6 || form.password.length > 18) {
    // 密码长度6 - 18位
    callback(new Error("密码长度应为6-18位"));
  } else if (!reg.test(form.password)) {
    // 新密码长度不能小于6 需包含字母、数字、特殊符号中至少两种
    isPws.value = true;
    callback(new Error(""));
  } else {
    isPws.value = false;
    callback();
  }
};
const validateRnewPass = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!form.checkPassword) {
    callback(new Error(" "));
  } else if (form.checkPassword !== form.password) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const rules = {
  originalPassword: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      validator: validateNewPass,
      trigger: "blur",
    },
  ],
  checkPassword: [
    {
      required: true,
      validator: validateRnewPass,
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
};

const emit = defineEmits(['success'])

const refForm = ref();
// 提交修改密码
function submitHandle() {
  refForm.value.validate(async (vaild: boolean) => {
    if (vaild) {
      try {
        formLoading.value = true;
        await sysUser.pwd(form);
        if (props.type == 1) {
          ElNotification.success("密码修改成功，请重新登录");
          setTimeout(() => {
            router.push("/login");
          }, 1000);
        } else {
          ElNotification.success("密码修改成功");
          dialogVisible.value = false;
        }
        emit('success')
      } catch (error) {
        formLoading.value = false;
        console.log(error);
      }
    }
  });
}

function show(e: object) {
  console.log(e);
  shopInfo.value = e
  form.id = e.id
  dialogVisible.value = true
}

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.center {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>