import ElDialog from 'element-ui-for-gov/packages/dialog';
import ElTabs from 'element-ui-for-gov/packages/tabs';
import ElTabPane from 'element-ui-for-gov/packages/tabs/src/tab-pane';
import ElButton from 'element-ui-for-gov/packages/button';
import Message from 'element-ui-for-gov/packages/message';

import PickerPanel from './picker-panel';

export default {
  name: 'UserPicker',
  components: {ElDialog, ElTabs, ElTabPane, ElButton, PickerPanel},
  props: {
    title: {
      type: String,
      default: '选择人员'
    },
    visible: {
      type: Boolean
    },
    required: {
      type: Boolean,
      default: true
    },

    requiredTips: {
      type: String,
      default: '请选择人员'
    },

    userUniqueId: {type: String, default: 'id'},

    defaultChecked: {
      type: Array,
      default: () => []
    },

    tabs: {
      type: Array,
      default: () => []
    },

    confirmText: {
      type: String,
      default: '确定'
    },

    cancelText: {
      type: String,
      default: '取消'
    },
    renderChecked: {
      type: Function
    },
    renderCheckedItem: {
      type: Function
    },
    selectPanelButton: {
      type: Function
    },
    radio: {
      type: Boolean,
      default: false
    },
    isSearchCheckAll: {
      type: Boolean,
      default: true
    },
    dialogProps: {
      type: Object,
      default: () => {}
    },
    poppable: {
      type: Boolean,
      default: true
    },
    loading: Boolean,
    height: String,
    checkOnClickNode: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      checkedUsers: [],
      defaultCheckUsers: [],
      treeInstances: {},
      currTabsVal: this.tabs[0] ? this.tabs[0].key : '0'
    };
  },

  provide() {
    return {
      handleChangeUser: this.handleChangeUser,
      clearChecked: this.clearChecked,
      nodeKey: this.userUniqueId,
      setTreeInstance: this.setTreeInstance
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.defaultCheckUsers = this.defaultChecked.slice();
        }
      },
      immediate: true
    },
    defaultChecked: {
      handler() {
        if (!this.poppable) {
          this.defaultCheckUsers = this.defaultChecked.slice();
        }
      },
      immediate: true
    },
    checkedUsers: {
      handler(val) {
        // console.log('watch-checkedUsers', val);
        this.$emit('changeUser', val);
      },
      immediate: true
    },
    tabs(val, old) {
      if (old.length === 0 && val.length > 0) {
        if (val[0]) this.currTabsVal = val[0].key;
      }
    }
  },

  methods: {
    getTreeInstance() {
      return this.treeInstances;
    },
    setTreeInstance(key, $tree) {
      // console.log('setTreeInstance', key);
      this.treeInstances[key] = $tree;
      this.$emit('mounted-tree', {key, $tree});
    },
    handleChangeUser(users, deleteUsers = []) {
      if (this.radio) {
        this.checkedUsers = users;
      } else {
        const arr = [];
        let unique = {};
        // console.log('handleChangeUser-this.checkedUsers', this.checkedUsers);
        this.checkedUsers.concat(users).forEach(user => {
          let del = deleteUsers.find(del => del[this.userUniqueId] === user[this.userUniqueId]);
          if (!unique[user[this.userUniqueId]] && !del) {
            arr.push(user);
            unique[user[this.userUniqueId]] = user;
          }
        });
        this.checkedUsers = arr;
      }
    },

    clearChecked() {
      this.checkedUsers = [];
      this.defaultCheckUsers = [];
    },

    handleCancel(e) {
      this.checkedUsers = [];
      this.$emit('cancel');
    },
    handleConfirm() {
      if (this.required && this.checkedUsers.length === 0) {
        Message.error(this.requiredTips);
        return;
      }
      this.$emit('confirm', this.checkedUsers.slice(0));
      this.checkedUsers = [];
    },
    onTabClick(tab) {
      try {
        if (tab.$children && tab.$children[0] && tab.$children[0].$refs.tree) {
          tab.$children[0].$refs.tree.adjustFilterHeight();
        }
      } catch (e) {}
    },
    onTabsChange(val) {
      this.currTabsVal = val;
    }
  },

  render() {
    const { title, visible,
      checkedUsers,
      defaultCheckUsers,
      tabs,
      confirmText,
      cancelText,
      renderChecked,
      renderCheckedItem,
      selectPanelButton,
      radio,
      isSearchCheckAll,
      dialogProps,
      poppable,
      loading,
      checkOnClickNode
    } = this;
    const HEADER_HEIGHT = 59;
    const TAB_HEIGHT = tabs.length > 1 ? 56 : 0;
    const TRAN_HEIGHT = this.height ? Number(this.height.replace('px', '')) - TAB_HEIGHT - HEADER_HEIGHT : null;

    if (poppable) {
      return <ElDialog
        append-to-body={true}
        close-on-click-modal={false}
        title={title}
        visible={visible}
        {...{on: {'update:visible': this.handleCancel}, props: {...dialogProps}}}
        width={'1000px'} >
        {
          this.$slots.header && <template slot="header">{this.$slots.header}</template>
        }
        <div class="el-user-picker" style={{height: this.height}} v-loading={loading}>
          {tabs.length > 1 && <ElTabs value={this.currTabsVal} onInput={this.onTabsChange} {...{
            on: {
              'tab-click': this.onTabClick
            }
          }}>
            {tabs.map((tab, i) => (<ElTabPane key={tab.key} label={tab.title} name={tab.key || (i + '')}>
              <PickerPanel checkOnClickNode={checkOnClickNode} height={TRAN_HEIGHT} defaultChecked={defaultCheckUsers} checkedUsers={checkedUsers} treeProps={tab} renderChecked={renderChecked} renderCheckedItem={renderCheckedItem} selectPanelButton={selectPanelButton} radio={radio} isSearchCheckAll={isSearchCheckAll} />
            </ElTabPane>))}
          </ElTabs> }
          {tabs.length === 1 && <PickerPanel checkOnClickNode={checkOnClickNode} height={TRAN_HEIGHT} defaultChecked={defaultCheckUsers} checkedUsers={checkedUsers} treeProps={tabs[0]} renderChecked={renderChecked} renderCheckedItem={renderCheckedItem} selectPanelButton={selectPanelButton} radio={radio} isSearchCheckAll={isSearchCheckAll} />}
        </div>

        <span class="dialog-footer" slot="footer">
          <ElButton {...{
            on: {
              click: this.handleCancel
            }
          }}>{cancelText}</ElButton>
          <ElButton type="primary" {...{
            on: {
              click: this.handleConfirm
            }
          }}>{confirmText}</ElButton>
        </span>
      </ElDialog>;
    } else {
      return <div class="el-user-picker" style={{height: this.height}} v-loading={loading}>
        {tabs.length > 1 && <ElTabs value={this.currTabsVal} onInput={this.onTabsChange}>
          {tabs.map((tab, i) => (<ElTabPane key={tab.key} label={tab.title} name={tab.key || (i + '')}>
            <PickerPanel height={TRAN_HEIGHT} defaultChecked={defaultCheckUsers} checkOnClickNode={checkOnClickNode} checkedUsers={checkedUsers} treeProps={tab}
              renderChecked={renderChecked} selectPanelButton={selectPanelButton} renderCheckedItem={renderCheckedItem} radio={radio} isSearchCheckAll={isSearchCheckAll}/>
          </ElTabPane>))}
        </ElTabs>}
        {tabs.length === 1 &&
        <PickerPanel height={TRAN_HEIGHT} defaultChecked={defaultCheckUsers} checkOnClickNode={checkOnClickNode} checkedUsers={checkedUsers} treeProps={tabs[0]}
          renderChecked={renderChecked} renderCheckedItem={renderCheckedItem} selectPanelButton={selectPanelButton} radio={radio} isSearchCheckAll={isSearchCheckAll}/>}
      </div>;
    }
  }
};
