import { CSSProperties, VNode, h, ref } from 'vue';
import { getRuleMatchResult, IpasswordForce, IpasswordRule, isMatchForceResultConfig, MatchResultConfig, passwordBreakKey } from './passwordUtil';

interface props {
  color?: string;
  style?: CSSProperties;
  className?: string;
  customRule?: IpasswordRule[];
}
enum ForceMap {
  high = '密码安全',
  middle = '密码普通',
  low = '密码简单',
}
const boolNumSum = (list: boolean[]) => list.reduce<number>((previousValue, currentValue) => (currentValue ? previousValue + 1 : previousValue), 0);

const usePasswordForce: (props?: props) => {
  View: (params: { color?: string }) => VNode<any>;
  validate: (inputValue: string) => boolean;
  force: IpasswordForce;
  getForce: () => IpasswordForce;
} = props => {
  const { customRule = [] } = props ?? {};
  const force = ref<IpasswordForce>(false);
  const forceRef = ref<IpasswordForce>(false);

  const validate = (inputValue: string) => {
    force.value = false;
    forceRef.value = false;
    const inputValueLen = inputValue?.length || 0;
    // const isFirstWordUp = inputValueLen > 0 && inputValue[0] === inputValue[0].toLocaleUpperCase();
    const ruleRsult = getRuleMatchResult(customRule, inputValue, undefined, '');
    const matchNum = boolNumSum(ruleRsult.list.map(e => e[passwordBreakKey]));
    const matchResultConfig: MatchResultConfig[] = [
      { min: 0, max: 20, matchNum: 1, value: 'low' },
      { min: 0, max: 7, matchNum: 2, value: 'low' },
      { min: 0, max: 7, matchNum: 3, value: 'low' },
      { min: 7, max: 20, matchNum: 2, value: 'middle' },
      { min: 7, max: 20, matchNum: 3, value: 'middle' },
      { min: 7, max: 20, matchNum: 4, value: 'high' },
      // { min: 15, max: 20, matchNum: 3, value: 'high', need: isFirstWordUp },
    ];
    matchResultConfig.forEach(config => {
      if (isMatchForceResultConfig(config, matchNum, inputValueLen)) {
        force.value = config.value;
        forceRef.value = config.value;
      }
    });
    return ruleRsult.invaildWord;
  };

  const getForce = () => forceRef.value;

  return {
    View: ({ color }) => (force.value ? h('span', { style: { color } }, force.value ? ForceMap[force.value] : '') : undefined),
    validate,
    getForce,
    force,
  };
};

export default usePasswordForce;
