import { post } from '@/services/ajax';
import { App, Button, Input, Spin } from 'antd';
import { stringify } from 'qs';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';

type IProps = {
  close: () => void;
};

type IProps2 = {
  value: string;
};
const StrokeCheck: React.FC<IProps2> = (props) => {
  const { value } = props;
  const strokeColor = ['#e74242', '#ffa500', '#EFBD47', '#1bbf1b', '#008000'];
  const [strong, setStrong] = useState(0);
  useEffect(() => {
    let s = 0;
    if (value.length >= 6) {
      if (value.length >= 6) {
        s++;
      }
      let pattern = new RegExp(
        "[`~!@#$%^&?*()_\\-\\+=|{}':;',\\[\\].<>《》./~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]",
      );
      if (value.match(/\d/g)) {
        s++;
      }
      if (value.match(/[a-z]/g)) {
        s++;
      }
      if (value.match(/[A-Z]/g)) {
        s++;
      }
      if (pattern.test(value)) {
        s++;
      }
    }
    setStrong(s);
  }, [value]);

  return (
    <div className={styles.passwordStrong}>
      <div className={styles.strokeColorMask} style={{ width: `${((5 - strong) / 5) * 100}%` }} />
      <div className={styles.mark} />
      <div className={styles.mark} />
      <div className={styles.mark} />
      <div className={styles.mark} />
      {strokeColor.map((item) => {
        return <div className={styles.strokeColor} key={item} style={{ background: item }} />;
      })}
    </div>
  );
};
export const EditPassword: React.FC<IProps> = (props) => {
  const [param, setParam] = useState({
    old_pass: '',
    new_pass: '',
    new_pass1: '',
  });

  const [loading, setLoading] = useState(false);

  const pwdFocusRef = useRef([0, 0, 0]);
  const { notification } = App.useApp();

  const save = () => {
    if (
      param.old_pass.length < 6 ||
      param.new_pass.length < 6 ||
      param.new_pass1 !== param.new_pass ||
      param.new_pass == param.old_pass
    ) {
      pwdFocusRef.current = [1, 1, 1];
      setParam({ ...param });
    } else {
      setLoading(true);
      post({ url: '/User/ChangePass', data: stringify(param) }).then((res) => {
        setLoading(false);
        if (res.err_code == 0) {
          notification.success({
            message: '密码修改成功',
          });
          props.close();
        }
      });
    }
  };

  return (
    <Spin spinning={loading}>
      <div style={{ marginTop: 16 }}>
        <Input.Password
          autoFocus
          defaultValue={param.old_pass}
          addonBefore="原先密码"
          placeholder="原先账号密码"
          maxLength={20}
          autoComplete="off"
          onChange={(e) => {
            param.old_pass = e.target.value;
            pwdFocusRef.current[0] = 1;
            setParam({ ...param });
          }}
          status={
            (pwdFocusRef.current[0] == 1 && param.old_pass.length < 6) ||
            (param.old_pass.length >= 6 && param.new_pass == param.old_pass)
              ? 'error'
              : ''
          }
        />
        <div className={styles.errMsg}>
          {pwdFocusRef.current[0] == 1 ? (
            <>
              {param.old_pass.length < 6 ? '密码长度不能小于6位' : ''}
              {param.old_pass == '' ? '，该字段是必填字段' : ''}
              {param.old_pass.length >= 6 && param.new_pass == param.old_pass
                ? '新密码和旧密码不能一样'
                : ''}
            </>
          ) : null}
        </div>
        <Input.Password
          defaultValue={param.new_pass}
          addonBefore="修改密码"
          placeholder="账号新密码"
          maxLength={20}
          autoComplete="off"
          onChange={(e) => {
            param.new_pass = e.target.value;
            pwdFocusRef.current[1] = 1;
            setParam({ ...param });
          }}
          status={pwdFocusRef.current[1] == 1 && param.new_pass.length < 6 ? 'error' : ''}
        />
        <StrokeCheck value={param.new_pass} />
        <div className={styles.errMsg} style={{ marginTop: 4 }}>
          {pwdFocusRef.current[1] == 1 ? (
            <>
              {param.new_pass.length < 6 ? '密码长度不能小于6位' : ''}
              {param.new_pass == '' ? '，该字段是必填字段' : ''}
            </>
          ) : null}
        </div>

        <Input.Password
          defaultValue={param.new_pass1}
          addonBefore="确认密码"
          placeholder="确认新密码"
          maxLength={20}
          autoComplete="off"
          onChange={(e) => {
            param.new_pass1 = e.target.value;
            pwdFocusRef.current[2] = 1;
            setParam({ ...param });
          }}
          status={pwdFocusRef.current[2] == 1 && param.new_pass1 !== param.new_pass ? 'error' : ''}
        />
        <div className={styles.errMsg}>
          {pwdFocusRef.current[2] == 1 ? (
            <>{param.new_pass1 !== param.new_pass ? '新密码与确认密码输入不一致' : ''}</>
          ) : null}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Button type="primary" style={{ marginRight: 12 }} onClick={save}>
            修改密码
          </Button>
          <Button
            type="default"
            onClick={() => {
              props.close();
            }}
          >
            关闭
          </Button>
        </div>
      </div>
    </Spin>
  );
};
