<script setup lang="ts">
import type { FormRules, FormInstance } from 'element-plus'
import settingApi from '@/api/system/setting'
import type { ChangePasswordFormType } from '../interface'
const props = withDefaults(
  defineProps<{
    modelValue: boolean
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue'])
const showDia = computed({
  get() {
    return props.modelValue
  },
  set(newVal) {
    emits('update:modelValue', newVal)
  },
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const hidePassword = ref({
  oldPassword: true,
  newPassword: true,
  confirmPassword: true,
})
const validateOldPassword = async (rule, value, callback) => {
  try {
    const { data } = await settingApi.checkPasswordApi({ oldPassword: value })
    if (data.code === 200) {
      callback()
    }
  } catch (error) {
    callback(new Error('旧密码输入不正确'))
  }
}
const validateNewPassword = (rule, value, callback) => {
  const hasNumber = /\d/.test(value)
  const hasLetter = /[a-zA-Z]/.test(value)
  const isValidLength = value.length >= 8 && value.length <= 16
  if (hasNumber && hasLetter && isValidLength) {
    callback()
  } else {
    callback(new Error('密码 8～16 位，数字、字母，至少包含两种字符'))
  }
}
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== ruleForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const ruleForm = reactive<ChangePasswordFormType>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const rules = reactive<FormRules<ChangePasswordFormType>>({
  oldPassword: [
    {
      required: true,
      message: '请输入旧密码',
      trigger: ['change', 'blur'],
    },
    { required: true, validator: validateOldPassword, trigger: 'blur' },
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: ['change', 'blur'],
    },
    { required: true, validator: validateNewPassword, trigger: ['blur'] },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请输入确认密码',
      trigger: ['change', 'blur'],
    },
    { required: true, validator: validateConfirmPassword, trigger: 'blur' },
  ],
})
// 确认修改密码
function handleChangePassword() {
  formRef.value?.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        await settingApi.modifyPersonalConfigApi(ruleForm)
        showDia.value = false
        formRef.value?.resetFields()
      } catch (err) {
        console.log(err)
      } finally {
        loading.value = false
      }
    }
  })
}

watch(
  () => showDia.value,
  val => {
    if (!val) {
      formRef.value?.resetFields()
    }
  },
  {
    immediate: true,
  },
)
</script>
<template>
  <div class="change_pwd">
    <mj-dialog v-model="showDia" title="修改密码" :hideFooter="true">
      <el-form ref="formRef" :model="ruleForm" :rules="rules" class="pwd_form">
        <el-form-item label="旧密码:" prop="oldPassword">
          <el-input
            v-model="ruleForm.oldPassword"
            :type="hidePassword.oldPassword ? 'password' : ''"
            placeholder="请输入密码"
          >
            <template #suffix>
              <Icon
                :name="hidePassword.oldPassword ? 'eye_close' : 'eye_open'"
                size="32"
                @click="hidePassword.oldPassword = !hidePassword.oldPassword"
              />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassword">
          <el-input
            v-model="ruleForm.newPassword"
            :type="hidePassword.newPassword ? 'password' : ''"
            placeholder="请输入密码"
          >
            <template #suffix>
              <Icon
                :name="hidePassword.newPassword ? 'eye_close' : 'eye_open'"
                size="32"
                @click="hidePassword.newPassword = !hidePassword.newPassword"
              />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码:" prop="confirmPassword">
          <el-input
            v-model="ruleForm.confirmPassword"
            :type="hidePassword.confirmPassword ? 'password' : ''"
            placeholder="请输入密码"
          >
            <template #suffix>
              <Icon
                :name="hidePassword.confirmPassword ? 'eye_close' : 'eye_open'"
                size="32"
                @click="hidePassword.confirmPassword = !hidePassword.confirmPassword"
              />
            </template>
          </el-input>
        </el-form-item>

        <div class="footer">
          <Btn
            width="100%"
            size="48"
            type="primary"
            :loading="loading"
            @click="handleChangePassword"
            >确认</Btn
          >
        </div>
      </el-form>
    </mj-dialog>
  </div>
</template>
<style lang="scss" scoped>
.change_pwd {
  :deep(.x-dia) {
    width: 720px;
    height: 43.75vh;
    .el-dialog__header {
      height: 7.33vh;
      .header {
        height: 7.33vh;
      }
    }
    .el-dialog__body {
      padding: 3.33vh 48px 2.67vh 48px;
    }
  }
  .pwd_form {
    font-family: $font-special;
    font-size: $font-size-7;

    :deep(.el-form-item) {
      height: 7.33vh;
      line-height: 7.33vh;
      display: flex;
      align-items: center;
      padding: 0 $space-4;
      border-radius: $radius-6;
      background: #fff;
      margin-bottom: 0;
      margin-bottom: $space-5_h;
      box-shadow: 0 0.17vh 0.17vh 0 rgba(0, 0, 0, 0.25);

      .el-form-item__label {
        font-size: $font-size-7;
        width: 160px;
        color: $font-tag-color;
        display: inline-block;
        text-align: justify;
        text-align-last: justify;
        white-space: nowrap;

        &::before {
          color: $error-color;
          display: none;
        }
      }
      .el-form-item__content {
        position: relative;
        .el-input {
          height: 7.33vh;
          font-size: $font-size-7;
          .el-input__wrapper {
            box-shadow: none;
            .el-input__inner {
              font-family: $font-special;
            }
            input[type='password'] {
              -webkit-text-security: disc;
              text-security: disc;
            }
          }
        }
        .el-form-item__error {
          font-size: $font-size-3;
          line-height: 1.5em;
          margin-left: -160px;
          color: $error-color;
        }
      }
    }
    .footer {
      text-align: center;
      :deep(.x-button) {
        width: 100%;
        height: 6.67vh;
        .x-button-text {
          line-height: 4vh;
          font-size: $font-size-7;
        }
      }
    }
  }
}
</style>
