<template>
  <x-cell
    class="co-field"
    :title="label"
    :icon="icon"
    v-clickoutside="doCloseActive"
    :class="[{
      'is-textarea': type === 'textarea',
      'is-required': required === true,
      'is-nolabel': !label
    }]">
    <textarea
      @change="$emit('change', currentValue)"
      ref="textarea"
      class="co-field-core"
      :placeholder="placeholder"
      v-if="type === 'textarea'"
      :rows="rows"
      :disabled="disabled"
      :readonly="readonly"
      v-model="currentValue">
    </textarea>
    <input
      @change="$emit('change', currentValue)"
      ref="input"
      class="co-field-core"
      :placeholder="placeholder"
      :number="type === 'number'"
      v-else
      :type="type"
      @focus="active = true"
      :disabled="disabled"
      :readonly="readonly"
      :value="currentValue"
      @input="handleInput">
    <div
      @click="handleClear"
      class="co-field-clear"
      v-if="!disabled && !disableClear"
      v-show="currentValue && type !== 'textarea' && active">
      <i class="coicon coicon-delete_fill"></i>
    </div>
    <span class="co-field-state" v-if="state" :class="['is-' + state]">
      <i class="coicon" :class="getFieldCls(state)"></i>
    </span>
    <div class="co-field-other">
      <slot></slot>
    </div>
  </x-cell>
</template>

<script>
import XCell from 'CoUI/packages/cell/index.js';
import Clickoutside from 'CoUI/src/utils/clickoutside';
if (process.env.NODE_ENV === 'component') {
  require('CoUI/packages/cell/style.css');
}

/**
 * co-field
 * @desc 编辑器，依赖 cell
 * @module components/field
 *
 * @param {string} [type=text] - field 类型，接受 text, textarea 等
 * @param {string} [icon] - 图标，label前面
 * @param {string} [label] - 标签
 * @param {string} [required] - 是否必填 0/1
 * @param {string} [rows] - textarea 的 rows
 * @param {string} [placeholder] - placeholder
 * @param {string} [disabled] - disabled
 * @param {string} [readonly] - readonly
 * @param {string} [state] - 表单校验状态样式，接受 error, warning, success
 *
 * @example
 * <co-field v-model="value" label="用户名"></co-field>
 * <co-field v-model="value" label="密码" placeholder="请输入密码"></co-field>
 * <co-field v-model="value" label="自我介绍" placeholder="自我介绍" type="textarea" rows="4"></co-field>
 * <co-field v-model="value" label="邮箱" placeholder="成功状态" state="success"></co-field>
 */
export default {
  name: 'co-field',

  data() {
    return {
      active: false,
      currentValue: this.value
    };
  },

  directives: {
    Clickoutside
  },

  props: {
    type: {
      type: String,
      default: 'text'
    },
    required: Boolean,
    rows: String,
    label: String,
    icon: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    disableClear: Boolean,
    state: {
      type: String,
      default: 'default'
    },
    value: {},
    attr: Object
  },

  components: { XCell },

  methods: {
    getFieldCls(state) {
      var iconNS = 'coicon';
      if (state === 'error') {
        return `${iconNS}-delete_fill`;
      } else if (state === 'warning') {
        return `${iconNS}-warning_fill`;
      } else if (state === 'success') {
        return `${iconNS}-success_fill`;
      }
      return '';
    },
    doCloseActive() {
      this.active = false;
    },

    handleInput(evt) {
      this.currentValue = evt.target.value;
    },

    handleClear() {
      if (this.disabled || this.readonly) return;
      if (this.$listeners && typeof this.$listeners.clear === 'function') {
        this.$emit('clear', this.currentValue);
      } else {
        this.currentValue = '';
      }
    }
  },

  watch: {
    value(val) {
      this.currentValue = val;
    },

    currentValue(val) {
      this.$emit('input', val);
    },

    attr: {
      immediate: true,
      handler(attrs) {
        this.$nextTick(() => {
          const target = [this.$refs.input, this.$refs.textarea];
          target.forEach(el => {
            if (!el || !attrs) return;
            Object.keys(attrs).map(name => el.setAttribute(name, attrs[name]));
          });
        });
      }
    }
  }
};
</script>

<style lang="css">
  @import "../../../src/style/var-ios9.css";

  @component-namespace co {
    @component field {
      display: flex;

      @when textarea {
        align-items: inherit;

        .co-cell-title {
          padding: 0.5rem 0;
        }

        .co-cell-value {
          padding: 0.25rem 0;
        }
      }

      .co-cell-title {
        width: 5.25rem;
        flex: none;
      }

      .co-cell-value {
        flex: 1;
        color: inherit;
        display: flex;
      }

      @descendent core {
        appearance: none;
        border-radius: 0;
        border: 0;
        flex: 1;
        outline: 0;
        line-height: 1.6;
        font-size: inherit;
        width: 100%;
      }

      @descendent clear {
        opacity: .2;
      }

      @descendent state {
        color: inherit;
        margin-left: 1rem;

        .coicon {
          font-size: 1rem;
        }

        @when error {
          color: $error-color;
        }

        @when warning {
          color: $warning-color;
        }

        @when success {
          color: $success-color;
        }

        @when default {
          margin-left: 0;
        }
      }

      @descendent other {
        position: absolute 0 0 * *;
      }

      @when nolabel {
        .co-cell-title {
          display: none;
        }
      }

      @when required {
        .co-cell-title:after {
          content: '*';
          color: $error-color;
        }
      }
    }
  }
</style>
