/* eslint-disable @typescript-eslint/no-explicit-any */
import { defineComponent, PropType, reactive, ref } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import './change-password.scss';

interface UserData {
  oldPwd: string;
  newPwd: string;
  comfirmPwd: string;
}

export const ChangePassword = defineComponent({
  name: 'ChangePassword',
  props: {
    dismiss: {
      type: Function as PropType<(_result: IParams) => void>,
    },
  },
  setup(props) {
    const ns = useNamespace('change-password');

    const formRef = ref<IData | null>(null);

    const userData = reactive<UserData>({
      oldPwd: '',
      newPwd: '',
      comfirmPwd: '',
    });

    const rules = {
      oldPwd: [
        {
          required: true,
          message: '请输入原密码',
          trigger: 'blur',
        },
      ],
      newPwd: [
        {
          required: true,
          message: '请输入新密码',
          trigger: 'blur',
        },
        {
          validator: (rule: IData, value: string, callback: any) => {
            // 至少8位字符
            if (value && value.length < 8) {
              callback(new Error('密码长度不能少于8位'));
            }
            // 至少1个大写字母
            if (!/[A-Z]/.test(value)) {
              callback(new Error('至少1个大写字母'));
            }
            // 至少1个小写字母
            if (!/[a-z]/.test(value)) {
              callback(new Error('至少1个小写字母'));
            }
            // 至少1个数字
            if (!/[0-9]/.test(value)) {
              callback(new Error('至少1个数字'));
            }
            // 至少1个特殊符号
            if (!/[!@#$%^&*]/.test(value)) {
              callback(new Error('至少1个特殊符号'));
            }
            callback();
          },
          trigger: 'blur',
        },
      ],
      comfirmPwd: [
        {
          required: true,
          message: '请再次输入新密码',
          trigger: 'blur',
        },
        {
          validator: (rule: IData, value: string, callback: any) => {
            const { newPwd, comfirmPwd } = userData;
            if (newPwd !== comfirmPwd) {
              callback(new Error('两次输入密码不一致'));
            }
            callback();
          },
          trigger: 'blur',
        },
      ],
    };

    const loading = ref(false);

    const onClick = () => {
      if (!ibiz.env.publicKey) {
        ibiz.message.error('请联系系统管理员配置公钥');
        return;
      }
      formRef.value!.validate(async (valid: boolean) => {
        if (valid) {
          try {
            loading.value = true;
            let { oldPwd, newPwd } = userData;
            if (ibiz.env.enableRSA) {
              oldPwd = ibiz.util.text.rsa(oldPwd);
              newPwd = ibiz.util.text.rsa(newPwd);
            }
            const res = await ibiz.net.post('/uaa/changepwd', {
              oldPwd,
              newPwd,
            });
            if (res.ok) {
              ibiz.notification.success({
                title: '修改密码成功',
              });
            } else {
              ibiz.notification.error({
                title: res.data?.message || '修改密码失败',
              });
            }
            props.dismiss?.({ ok: true, data: {} });
            loading.value = false;
          } catch (error) {
            ibiz.notification.error({
              title: (error as IData).response?.data?.message || '修改密码失败',
            });
            loading.value = false;
          }
        }
      });
    };

    return () => (
      <div class={ns.b()}>
        <div class={ns.e('header')}>修改密码</div>
        <div class={ns.e('content')}>
          <i-form ref={formRef} props={{ model: userData, rules }}>
            <i-form-item prop='oldPwd'>
              <i-input
                type='password'
                value={userData.oldPwd}
                on-on-change={(evt: InputEvent) => {
                  const { value } = evt.target as HTMLInputElement;
                  userData.oldPwd = value;
                }}
                placeholder='请输入原密码'
                size='large'
                password
              >
                <i-icon type='ios-unlock' slot='prefix'></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item prop='newPwd'>
              <i-input
                type='password'
                value={userData.newPwd}
                on-on-change={(evt: InputEvent) => {
                  const { value } = evt.target as HTMLInputElement;
                  userData.newPwd = value;
                }}
                placeholder='请输入新密码'
                size='large'
                password
              >
                <i-icon type='ios-unlock' slot='prefix'></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item prop='comfirmPwd'>
              <i-input
                type='password'
                value={userData.comfirmPwd}
                on-on-change={(evt: InputEvent) => {
                  const { value } = evt.target as HTMLInputElement;
                  userData.comfirmPwd = value;
                }}
                placeholder='请再次输入新密码'
                size='large'
                password
              >
                <i-icon type='ios-unlock' slot='prefix'></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item>
              <i-button
                type='primary'
                shape='circle'
                loading={loading.value}
                long
                on-click={onClick}
              >
                确认修改
              </i-button>
            </i-form-item>
          </i-form>
        </div>
      </div>
    );
  },
});
