let targets = [];

const isFunc = v => typeof v === 'function';

function createInput(options) {
  const input = document.createElement('input');
  input.className = options.inputClass || 'v-field';
  input.type = options.inputType || 'text';
  input.value = isFunc(options.value) ? options.value() : options.value;
  return input;
}

export default {
  // el 指令绑定的元素 binding {name指令名 value指令绑定的值}
  inserted: (el, binding) => {
    const options = binding.value || {};
    let targetEl = el;
    if (targetEl) {
      let target = targets.find(v => v.el === targetEl),
        inputEl, disabled;
      // 当前 el 未初始化过，从头初始化一遍
      if (!target) {
        target = {
          options,
          el: targetEl
        };
        targets.push(target);
        targetEl.style.position = 'relative';
        targetEl.addEventListener(options.event || 'click', () => {
          disabled = isFunc(options.disabled) ? options.disabled() : options.disabled;
          if (!disabled && !inputEl) {
            inputEl = createInput(target.options);
            targetEl.appendChild(inputEl);
            inputEl.focus();
            inputEl.onblur = () => {
              target.options.input && target.options.input(inputEl.value);
              targetEl.removeChild(inputEl);
              inputEl = undefined;
            };
          }
        });
      }
      // 当前 el 已经初始化，只需要替换一下配置项即可 
      else {
        target.options = options;
      }
    }
  },
  update: (el, binding) => {
    const options = binding.value || {};
    let targetEl = el;
    if (targetEl) {
      let target = targets.find(v => v.el === targetEl),
        inputEl, disabled;
      if (!target) {
        target = {
          options,
          el: targetEl
        };
        targets.push(target);
        targetEl.style.position = 'relative';
        targetEl.addEventListener(options.event || 'click', () => {
          disabled = isFunc(options.disabled) ? options.disabled() : options.disabled;
          if (!disabled && !inputEl) {
            inputEl = createInput(target.options);
            targetEl.appendChild(inputEl);
            inputEl.focus();
            inputEl.onblur = () => {
              target.options.input && target.options.input(inputEl.value);
              targetEl.removeChild(inputEl);
              inputEl = undefined;
            };
          }
        });
      } else {
        target.options = options;
      }
    }
  }
}
