<template>

  <div :class="[
      b({
        row: isRow,
        disabled
      }),
      { 'eye-hairline': border }
    ]">
     <eye-cell
             :title="label"
             :center="center"
             :label="tip"
             :border="false"
             :required="required && !hasReadOnly"
             :isLink="isLink && !hasExtra && !hasReadOnly"
             :value="displayLabel"
             :class="{
                error,
                'has-icon': hasIcon,
                'min-height': type === 'textarea' && !autosize
              }"
             @click="handlerOnClick"
     >

        <template v-if="hasExtra">
            <slot name="extra" />
        </template>
        <template v-else>
            <template v-if="hasReadOnly">
                <div :class="b('readonly')">{{  displayLabel || currentValue}}</div>
            </template>
            <template v-else-if="!isLink">

                <div :class="b('input')">

                    <div v-if="type === 'textarea'"
                         :class="b('textarea')">

                        <textarea
                                v-bind="$attrs"
                                v-on="listeners"
                                ref="textarea"
                                :class="b('control')"
                                :disabled="disabled"
                                :placeholder="placeholder"
                                :value="currentValue"
                        />
                        <div v-if="maxLength"
                             :class="b('bar')">
                            <span @click="onClear"><i class="eye-icon-delete" />清空</span>
                            <div :class="b('tip')">{{currentValue ? currentValue.length : 0}}/{{maxLength}}</div>
                        </div>
                    </div>

                    <input
                            v-else
                            ref="input"
                            v-bind="$attrs"
                            v-on="listeners"
                            :class="b('control')"
                            :placeholder="placeholder"
                            :type="type"
                            :style="inputStyle"
                            :disabled="disabled"
                            :value="currentValue"
                    />
                    <div
                            :class="[b('tip'),'eye-ellipsis']"
                            v-if="tipMessage">
                        <span class="eye-ellipsis">{{ tipMessage }}</span>
                    </div>
                </div>

            </template>

            <template v-else>
                <div :class="!displayLabel && b('placeholder')">{{ displayLabel || placeholder}}</div>
            </template>

        </template>

    </eye-cell>

    <div v-if="errorMsg"
          :class="b('error-message')"
    >
        <i class="eye-icon eye-icon-error" />
        <span>{{errorMsg}}</span>
    </div>

    <eye-page-popup v-if="supportPopup"
             :visible.sync="currentVisible"
             :style="popupStyle"
             :title="title"
             :rightText="rightText"
             :position="position"
             @clickBack="onClickBack"
             @submit="handlerOnSubmit"
    >
      <div class="eye-popup__root">
          <slot></slot>
      </div>
    </eye-page-popup>

  </div>

</template>

<script>
import { Component,Core,FieldDelegation } from 'eye-core';

export default Component({

  name: 'field',

  inheritAttrs: false,

  mixins:[ FieldDelegation ],

  props: {
    value: null,
    icon: String,
    error: Boolean,
    center: Boolean,
    isRow: Boolean,
    autosize: [ Boolean, Object ],
    errorMessage: String,
    tipMessage: String,
    type: {
      type: String,
      default: 'text'
    },
    rightText: {
      type:String,
      default:'确定'
    },
    validatorFunction:Function,
    maxLength: {
      type: [Number,String],
      default: 0
    },
    textAlign:{
      type: String,
      default: 'right'
    },
    border: {
      type: Boolean,
      default: true
    },
    onIconClick: {
      type: Function,
      default: () => {}
    }
  },

  watch: {
    value() {
      this.$nextTick(this.adjustSize);
    }
  },

  onInit() {
    this.$nextTick(this.adjustSize);
    this.isLink = !!this.fieldSourceVue
  },



  computed: {
    hasIcon() {
      return this.$slots.icon || this.icon;
    },

    hasExtra() {
        return this.$slots.extra;
    },

    supportPopup() {
        return !!this.$slots.default
    },

    inputStyle() {
      return !this.isRow ? {
          textAlign : this.textAlign
      } : {}
    },


    listeners() {
      return {
        ...this.$listeners,
        input: this.onInput,
        focus:this.onFocus,
        keypress: this.onKeypress
      };
    }
  },

  data() {
      return {
          isLink:false
      }
  },

  methods: {

    onInput(event) {
        let value = event.target.value;
        let maxLength = Number(this.maxLength);
        if(maxLength && value && value.length > maxLength) {
            event.target.value = value.substr(0,maxLength);
            event.target.returnValue = false;
            return false;
        }
        this.syncCurrentValue(event.target.value)
    },

    onFocus() {
        this.clearError();
    },


    pushFocus() {
        const el = this.$refs.textarea || this.$refs.input;
        if (!el) {
            return;
        }
        el.focus()
        //debugger
    },


    onKeypress(e) {
        if (this.type === 'number') {
            const { keyCode } = e;
            const allowPoint = this.currentValue ? this.currentValue.indexOf('.') === -1 : false;
            const isValidKey = (keyCode >= 48 && keyCode <= 57) || (keyCode === 46 && allowPoint) || keyCode === 45;
            if (!isValidKey) {
              e.preventDefault();
            }
        }
        this.$emit('keypress', e);
    },

    onClickBack() {
      this.$emit('click-back');
    },

    onClickIcon() {
      this.$emit('click-icon');
      this.onIconClick();
    },

    handlerOnClick() {

      if(this.disabled || this.hasReadOnly) return;
      if(!this.isLink) return;

      this.clearError();
      this.setVisible(true)
      this.setVisibleField(true)
      this.$emit('clickFiled')
    },



    handlerOnSubmit() {
        let data = this.getCurrentValueField();
        let checked = true;
        if(this.validatorFunction) {
            checked = this.validatorFunction(data);
        }

        if(checked) {
            this.fieldSourceSelectChange(data)
            this.currentVisible = false;
        }
    },


    adjustSize() {
      if (!(this.type === 'textarea' && this.autosize)) {
        return;
      }

      const el = this.$refs.textarea;
      /* istanbul ignore if */
      if (!el) {
        return;
      }

      el.style.height = 'auto';

      let height = el.scrollHeight;
      if (Core._.isObject(this.autosize)) {
        const { maxHeight, minHeight } = this.autosize;
        if (maxHeight) {
          height = Math.min(height, maxHeight);
        }
        if (minHeight) {
          height = Math.max(height, minHeight);
        }
      }

      if (height) {
        el.style.height = height + 'px';
      }
    }
  }
});
</script>
