import ElButton from 'element-ui-for-gov/packages/button';
import ElInput from 'element-ui-for-gov/packages/input';

import SectionHeader from './section-header';

const prefix = 'el-user-picker';
export default {
  name: 'SelectedList',
  props: {
    label: String,
    checkedUsers: Array,
    renderChecked: Function,
    renderCheckedItem: Function,
    selectPanelButton: Function,
    height: Number
  },
  components: {ElButton, ElInput, SectionHeader},
  data() {
    return {
      keyword: ''
    };
  },
  methods: {
    uncheckedUser(user) {
      const index = this.checkedUsers.findIndex(item => item === user);
      this.checkedUsers.splice(index, 1);
      this.$emit('unchecked-user');
    }
  },
  computed: {
    sortedUsers() {
      const filteredUsers = this.checkedUsers.filter(item => this.keyword ? item[this.label].indexOf(this.keyword) > -1 : true);
      if (this.renderChecked && typeof this.renderChecked === 'function') {
        return this.renderChecked(filteredUsers);
      }
      return filteredUsers;
    }
  },

  render() {
    const {label, sortedUsers, renderCheckedItem, selectPanelButton} = this;
    const searchWrapHeight = 64;
    return (<div class={`${prefix}__section-wrapper`} >
      <SectionHeader title="已选列表" selectPanelButton={selectPanelButton} />
      <div class="filter-wrapper">
        <ElInput value={this.keyword}
          {...{
            on: {
              input: value => {
                this.keyword = value;
              }
            }
          }} prefixIcon="sg-icon sg-icon-fangdajing" placeholder="请输入关键词"/>
      </div>
      <div class={`${prefix}__section-content`} style={{height: `${this.height ? this.height - searchWrapHeight - 1 : 400}px`}}>
        <ul class={`${prefix}__section-list`}>
          {sortedUsers.map(item => (
            item._classify && item.list.length
              ? (
                <ul class={`${prefix}__section-list-children`}>
                  <li class={`${prefix}__section-list-title`}>{item._classify}</li>
                  {item.list.map(item => {
                    return <li>
                      {(renderCheckedItem && typeof renderCheckedItem === 'function') ? renderCheckedItem(item) : item[label]}
                      <i class="el-icon-close" {...{on: {click: this.uncheckedUser.bind(this, item)}}} />
                    </li>;
                  })}</ul>)
              : (item[label] && <li>
                {(renderCheckedItem && typeof renderCheckedItem === 'function') ? renderCheckedItem(item) : item[label]}
                <i class="el-icon-close" {...{on: {click: this.uncheckedUser.bind(this, item)}}} />
              </li>)))}
        </ul>
      </div>
    </div>);
  }
};
