<template>
  <Dialog :flag="passwordDialogVisible" width="496px" msg-title="修改密码" @submit-form="submitHandler" @reset-form="togglePasswordDialog(false)">
    <div class="dialog-content">
      <div v-if="securityData && securityData.pwd_type == 4" class="ruleDesc">
        特殊字符：!、@、#、$、%、^、&、*、(、)、+、{、}、"、:、?、,、.、/、'、;、=、-、\、|
      </div>
      <div class="ruleDesc">
        密码规则：长度为6-{{securityData.pwd_cons || ''}}个字符，并且必须包含{{renderText}}
      </div>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top" class="password-form">
        <el-form-item label="旧密码" prop="old">
          <el-input v-model="formData.old" autocomplete="off" size="default" placeholder="请输入旧密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new">
          <el-input v-model="formData.new" size="default" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="再次确认新密码" prop="repeat">
          <el-input v-model="formData.repeat" size="default" placeholder="请再次确认新密码" show-password></el-input>
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { changePassword } from "@/api/newLogin";
import Dialog from "@/components/dialog/index.vue";
import { useUserStore } from "@/store/user";
import { ElMessage, FormInstance } from "element-plus";
import MD5 from "blueimp-md5";
import { Query } from "@/api/webApi";
import { onMounted, computed } from "vue";

const emit = defineEmits(["logout"]);

const userStore = useUserStore();
const { passwordDialogVisible, UserId } = storeToRefs(userStore);
const { togglePasswordDialog } = userStore;

const securityData = ref<any>(sessionStorage.getItem("securityData") || null);
const formRef = ref<FormInstance | null>(null);
const formData = reactive({
  old: "",
  new: "",
  repeat: "",
});
const repeatValidator = (rule: any, value: any, callback: any) => {
  if (value !== formData.new) {
    return callback(new Error("两次输入的密码不一致，请重新输入"));
  }
  return callback();
};
// 表单验证
const formRules = {
  old: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  new: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  repeat: [
    { required: true, message: "请再次确认新密码", trigger: "blur" },
    { validator: repeatValidator, trigger: "blur" },
  ],
};
const renderText = computed(() => {
  const renderData = securityData.value;
  if (renderData?.pwd_type) {
    const { pwd_type, pwd_case } = renderData;
    switch (Number(pwd_type)) {
      case 1:
        return "英文";
        break;
      case 2:
        return "数字";
        break;
      case 3:
        return "英文、数字";
        break;
      case 4:
        let str: string = "";
        if (pwd_case == 1) {
          str = `（英文不区分大小写）`;
        } else {
          str = `（英文区分大小写）`;
        }
        return "英文、数字、特殊字符" + str;
        break;

      default:
        return "英文";
        break;
    }
  } else {
    return "";
  }
});
const submitHandler = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      submitNewPassword();
    } else {
      return false;
    }
  });
};
const submitNewPassword = async () => {
  try {
    const { code, message }: any = await changePassword({
      userId: UserId.value,
      originPassword: MD5(formData.old),
      newPassword: formData.new,
    });
    if (Number(code) !== 0) {
      throw new Error("修改失败");
    }
    ElMessage.success("修改成功");
    togglePasswordDialog(false);
    setTimeout(() => {
      ElMessage.info("请重新登录");
      emit("logout");
    }, 2000);
  } catch (error: any) {
    // ElMessage.error(error.message ?? "修改失败");
  }
};

const getSecurityPolicy = async () => {
  try {
    const {
      code,
      returnData: { listValues },
      message,
    } = await Query({
      id: DATACONTENT_ID.securityPolicy,
      dataContent: [],
    });
    if (String(code) !== "0") {
      throw new Error(message ?? "失败");
    }
    if (!listValues.length) {
      throw new Error("未查询到策略信息");
    }
    const data = listValues[0];
    securityData.value = data;
    sessionStorage.setItem("securityData", JSON.stringify(data));
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getSecurityPolicy();
});
</script>

<style lang="scss" scoped>
.dialog-content {
  margin-left: 20px;
  .ruleDesc {
    line-height: 2;
    margin-bottom: 22px;
    color: #101611;
  }
}
</style>
