<template>
  <div class="el-transfer" :class="{mirrored}">
    <transfer-panel
      v-bind="$props"
      ref="leftPanel"
      @query_update="emit_left_query_update"
      side='left'
      :data="sourceData"
      :title="titles[0] || t('el.transfer.titles.0')"
      :default-checked="leftDefaultChecked"
      :placeholder="filterPlaceholder || t('el.transfer.filterPlaceholder')"
      @checked-change="onSourceCheckedChange">
      <slot></slot>
    </transfer-panel>
    <div class="el-transfer__buttons">
      <el-button
        type="primary"
        :class="['el-transfer__button', hasButtonTexts ? 'is-with-texts' : '']"
        @click.native="addToLeft"
        :disabled="rightChecked.length === 0">
        <i class="el-icon-arrow-left"></i>
        <span v-if="buttonTexts[0] !== undefined">{{ buttonTexts[0] }}</span>
      </el-button>
      <el-button
        type="primary"
        :class="['el-transfer__button', hasButtonTexts ? 'is-with-texts' : '']"
        @click.native="addToRight"
        :disabled="leftChecked.length === 0">
        <span v-if="buttonTexts[1] !== undefined">{{ buttonTexts[1] }}</span>
        <i class="el-icon-arrow-right"></i>
      </el-button>
    </div>
    <transfer-panel
      v-bind="$props"
      ref="rightPanel"
      side='right'
      :data="targetData"
      :title="titles[1] || t('el.transfer.titles.1')"
      :default-checked="rightDefaultChecked"
      :placeholder="filterPlaceholder || t('el.transfer.filterPlaceholder')"
      @move="sortRight"
      @checked-change="onTargetCheckedChange">
      <slot name="rightfooter"></slot>
    </transfer-panel>
  </div>
</template>

<script>
  import ElButton from 'pimax-ui/packages/button';
  import Emitter from 'pimax-ui/src/mixins/emitter';
  import Locale from 'pimax-ui/src/mixins/locale';
  import TransferPanel from './transfer-panel.vue';
  import Migrating from 'pimax-ui/src/mixins/migrating';

  export default {
    name: 'ElTransfer',

    mixins: [Emitter, Locale, Migrating],

    components: {
      TransferPanel,
      ElButton
    },

    props: {
      pagination:{
        type:Boolean,
        default:false
      },
      query:{
        type:String,
        default:""
      },
      data: { // data == left-side-data  -- source
        type: Array,
        default() {
          return [];
        }
      },
      value: { // v-model === value === trans === right-side-data  -- target
        type: Array,
        default() {
          return [];
        }
      },
      mirrored:{
        type:Boolean,
        default:false,
      },
      titles: {
        type: Array,
        default() {
          return [];
        }
      },
      buttonTexts: {
        type: Array,
        default() {
          return [];
        }
      },
      filterPlaceholder: {
        type: String,
        default: ''
      },
      filterMethod: Function,
      leftDefaultChecked: {
        type: Array,
        default() {
          return [];
        }
      },
      rightDefaultChecked: {
        type: Array,
        default() {
          return [];
        }
      },
      renderContent: Function,

      format: {
        type: Object,
        default() {
          return {};
        }
      },
      filterable: Boolean,
      props: {
        type: Object,
        default() {
          return {
            label: 'label',
            key: 'key',
            disabled: 'disabled'
          };
        }
      },
      targetOrder: {
        type: String,
        default: 'unshift'
      }
    },

    data() {
      return {
        leftChecked: [],
        rightChecked: []
      };
    },

    computed: {
      dataObj() {
        const key = this.props.key;
          console.log("this.data---",this.data)
         // data -- source
        return this.data.reduce((o, cur) => (o[cur[key]] = cur) && o, {});
      },
      sourceData() {
        return this.data.filter(
          item => this.value.indexOf(item[this.props.key]) === -1);
      },
      targetData() {
        //value: // v-model -- target
        let result;
        if (this.targetOrder === 'original') {
          result = this.data.filter(
            item => this.value.indexOf(item[this.props.key]) > -1);
        } else {
          // console.log("this.dataObj---",this.dataObj)
          result = this.value.reduce((arr, cur) => {
            const val = this.dataObj[cur];
            // console.log('wtf--',val)
            if (val) {
              arr.push(val);
            }
            return arr;
          }, []);
        }
        // console.log(result)
        return result;
      },

      hasButtonTexts() {
        return this.buttonTexts.length === 2;
      }
    },

    watch: {
      value(val) {
        this.dispatch('ElFormItem', 'el.form.change', val);
      }
    },

    methods: {
      emit_left_query_update(query){
        this.$emit('left_query_update',query)
      },
      getMigratingConfig() {
        return {
          props: {
            'footer-format': 'footer-format is renamed to format.'
          }
        };
      },

      onSourceCheckedChange(val, movedKeys) {
        this.leftChecked = val;
        if (movedKeys === undefined) return;
        this.$emit('left-check-change', val, movedKeys);
      },

      onTargetCheckedChange(val, movedKeys) {
        this.rightChecked = val;
        if (movedKeys === undefined) return;
        this.$emit('right-check-change', val, movedKeys);
      },

      addToLeft() {
        let currentValue = this.value.slice();
        this.rightChecked.forEach(item => {
          const index = currentValue.indexOf(item);
          if (index > -1) {
            currentValue.splice(index, 1);
          }
        });
        this.$emit('input', currentValue);
        this.$emit('change', currentValue, 'left', this.rightChecked);
      },

      addToRight() {
        let currentValue = this.value.slice();
        const itemsToBeMoved = [];
        const key = this.props.key;
        this.data.forEach(item => {
          const itemKey = item[key];
          if (
            this.leftChecked.indexOf(itemKey) > -1 &&
            this.value.indexOf(itemKey) === -1
          ) {
            itemsToBeMoved.push(itemKey);
          }
        });
        currentValue = this.targetOrder === 'unshift'
          ? itemsToBeMoved.concat(currentValue)
          : currentValue.concat(itemsToBeMoved);
        this.$emit('input', currentValue);
        this.$emit('change', currentValue, 'right', this.leftChecked);
      },
      sortRight:function({dir,checked}){
         // v-model === value === trans === right-side-data
        //  targetData -> right-panel
        let rightval = this.value.slice();
        // console.log(dir, rightval, checked);
        // this.value.push(4)
        // console.log("before:--",this.value);
        let a;
        for(let i=0;i<checked.length;i++){
          a = rightval.indexOf(checked[i]);
          if(a!=0 && dir=='up'){
            this.swap(rightval,a,a-1);
          }else if(a!=rightval.length-1 && dir=='down'){
            this.swap(rightval,a,a+1);
          }
        }
        // console.log("after:--",this.value);
        this.$emit('input', rightval);

      },
      swap:function(arr,a,b){
        let tmp;
        tmp = arr[a]
        arr[a] = arr[b]
        arr[b] = tmp
      },

      clearQuery(which) {
        if (which === 'left') {
          this.$refs.leftPanel.query = '';
        } else if (which === 'right') {
          this.$refs.rightPanel.query = '';
        }
      }
    }
  };
</script>
