import $store from '@/sheep/store';
import { isString, isArray } from 'lodash';

export default (Vue) => {
  Vue.directive('auth', {
    mounted(el, binding) {
      if (!checkAuth(binding.value)) {
        el.parentNode.removeChild(el);
      }
    },
  });
  Vue.directive('preventdbclick', {
    mounted(el, binding) {
      el.addEventListener('click', () => {
        if (!el.disabled) {
          el.disabled = true;
          setTimeout(() => {
            el.disabled = false;
          }, binding.value || 3000);
        }
      });
    },
  });
  Vue.directive('focus', {
    mounted(el, binding) {
      if (binding.value) {
        el.children[0].focus();
      }
    },
    updated(el, binding) {
      if (binding.value) {
        el.children[0].focus();
      }
    },
  });
  Vue.directive('positiveinteger', {
    mounted(el) {
      el.addEventListener('keypress', function (e) {
        e = e || window.event;
        let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
        let re = /\d/;
        if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
          if (e.preventDefault) {
            e.preventDefault();
          } else {
            e.returnValue = false;
          }
        }
      });
    },
  });
  Vue.directive('enternumber', {
    mounted(el) {
      let changeValue = (el, type) => {
        const e = document.createEvent('HTMLEvents');
        e.initEvent(type, true, true);
        el.dispatchEvent(e);
      };
      el.addEventListener('keyup', function (e) {
        let input = e.target;
        let reg = new RegExp('^((?:(?:[1-9]{1}\\d*)|(?:[0]{1}))(?:\\.(?:\\d){0,2})?)(?:\\d*)?$');
        let matchRes = input.value.match(reg);
        if (matchRes == null) {
          input.value = '';
        } else {
          if (matchRes[1] != matchRes[0]) {
            input.value = matchRes[1];
          }
        }
        changeValue(input, 'input');
      });
    },
  });
};

// 检查权限
export function checkAuth(name) {
  const accountStore = $store('account');
  const info = accountStore.info;
  const apiRules = accountStore.apiRules;
  if (isString(name)) {
    return !(!info.is_super && !apiRules.includes(name));
  } else if (isArray(name)) {
    let flag = name.every((n) => {
      return apiRules.includes(n);
    });
    return !(!info.is_super && !flag);
  }
}
