<script setup lang="ts">
import { ref } from 'vue';
import { Dialog } from '@/components/Dialog';
import { Form } from '@/components/Form';
import { useForm } from '@/hooks/web/useForm';
import { reactive, computed } from 'vue';
import { useValidator } from '@/hooks/web/useValidator';
import { FormSchema } from '@/components/Form';
import {ElButton, ElMessage} from 'element-plus';
import { useDesign } from '@/hooks/web/useDesign';
import usePasswordForce from './usePasswordForce';
import {updatePasswordApi} from "@/api/system/SysUser";
import SM4Util from '@/utils/sm4';
import { getUserIdByUserInfo } from '@/utils/auth';
import Cookies from "js-cookie";
import {ACCESS_TOKEN} from "@/config/axios/config";
import {resetRouter} from "@/router";
import {useStorage} from "@/hooks/web/useStorage";
import {useTagsViewStore} from "@/store/modules/tagsView";
import {useLockStore} from "@/store/modules/lock";
import {useRouter} from "vue-router";
import { loginOutApi } from '@/api/login'

// 获取用户名
const { getPrefixCls } = useDesign();
const prefixCls = getPrefixCls('lock-dialog');

const { required } = useValidator();

const PasswordForce = usePasswordForce();
const { formRegister, formMethods } = useForm();

const { getFormData, getElFormExpose } = formMethods;

const props = defineProps({
  modelValue: {
    type: Boolean,
  },
});

const emit = defineEmits(['update:modelValue']);

const { clear } = useStorage()
const tagsViewStore = useTagsViewStore()
const lockStore = useLockStore()
const { replace } = useRouter()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => {
    console.log('set: ', val);
    emit('update:modelValue', val);
  },
});

const dialogTitle = ref('密码修改');

const rules = reactive({
  oldPassword: [
    required(),
    // {
    //   validator(_, value) {
    //     if (isNotEmpty(value)) {
    //       return valiOldPwd({ param: value });
    //     }
    //     return Promise.resolve();
    //   },
    //   message: '您输入的旧密码不正确！',
    // },
  ],
  password: [
    required(),
    {
      async validator(_, value) {
        const formData = await getFormData();
        if (PasswordForce.validate(value)) {
          return Promise.reject(new Error('密码包含非法字符！'));
        } else if (value === formData['oldPassword']) {
          return Promise.reject(new Error('不能使用旧密码！'));
        } else if (value?.length > 20) {
          return Promise.reject(new Error('密码过长！'));
        } else if (PasswordForce.getForce() !== 'high') {
          return Promise.reject(new Error('密码必须包含大小写字母、数字和特殊符号，长度8-20位'));
        }
        return Promise.resolve();
      },
    },
  ],
  confirmPassword: [
    required(),
    {
      validator: async (_, value, callback) => {
        const formData = await getFormData();
        if (value !== formData.password) {
          callback('您两次输入的密码不一致！');
        }
        callback();
      },
    },
  ],
});

const schema: FormSchema[] = reactive([
  {
    label: '原密码',
    field: 'oldPassword',
    component: 'Input',
    colProps: { span: 24 },
    componentProps: {
      type: 'password',
      showPassword: true,
      placeholder: '请填写当前账号密码',
    },
  },
  {
    label: '设置新密码',
    field: 'password',
    component: 'Input',
    colProps: { span: 24 },
    componentProps: {
      type: 'password',
      showPassword: true,
      placeholder: '请设置新密码',
    },
  },
  {
    label: '确认新密码',
    field: 'confirmPassword',
    component: 'Input',
    colProps: { span: 24 },
    componentProps: {
      type: 'password',
      showPassword: true,
      placeholder: '请重复输入新密码',
    },
  },
]);

const saveLoading = ref(false);

const loginId = getUserIdByUserInfo();
const updatePassword = async () => {
  const formExpose = await getElFormExpose();
  formExpose?.validate(async valid => {
    if (valid) {
      dialogVisible.value = false;
      const formData = await getFormData();
      const sm4 = new SM4Util();
      formData.oldPassword = sm4.encryptData_ECB(formData.oldPassword);
      formData.password = sm4.encryptData_ECB(formData.password);
      formData.confirmPassword = sm4.encryptData_ECB(formData.confirmPassword);
      formData.id = loginId;
      // console.log(formData);
      const res = await updatePasswordApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
      });
      if(res){
         if (+res.head.status === 500) {
            ElMessage.warning(res.head.msg || '密码修改失败');
          } else {
            ElMessage.success('密码修改成功,请重新登录');
            setTimeout(() => {
              goLogin()
            }, 2000); 
            
          }
      }
    }
  });
};

async function goLogin() {
  const res = await loginOutApi().catch(() => {})
  if (res) {
    Cookies.remove(ACCESS_TOKEN)
    clear()
    tagsViewStore.delAllViews()
    resetRouter() // 重置静态路由表
    lockStore.resetLockInfo()
    replace('/login')
  }
}

</script>

<template>
  <Dialog v-model="dialogVisible" width="500px" max-height="170px" :class="prefixCls" :title="dialogTitle">
    <Form :is-col="false" :schema="schema" :rules="rules" @register="formRegister" />
    <template #footer>
      <ElButton type="primary" @click="updatePassword">立即修改</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
:global(.v-lock-dialog) {
  @media (width <= 767px) {
    max-width: calc(100vw - 16px);
  }
}
</style>
