<template>
  <div class="el-transfer">
    <transfer-panel
      v-bind="$props"
      ref="leftPanel"
      :sourceData="sourceData"
      :title="titles[0] || t('el.transfer.titles.0')"
      :default-checked="leftDefaultChecked"
      :placeholder="filterPlaceholder || t('el.transfer.filterPlaceholder')"
      :fixedList="fixedList"
      :pagination="pagination"
      :page-size="pageSize"
      :isOverflowHidden="isOverflowHidden"
      @changeItem="changeItem"
      @changeTreeItem="changeTreeItem"
      @changeAllItem="changeAllItem"
      @checked-change="onSourceCheckedChange">
      <slot name="left-footer"></slot>
    </transfer-panel>

    <transfer-view
      v-bind="$props"
      ref="rightPanel"
      :targetData="targetData"
      :title="titles[1] || t('el.transfer.titles.1')"
      :placeholder="filterPlaceholder || t('el.transfer.filterPlaceholder')"
      :fixedList="fixedList"
      :pagination="pagination"
      :page-size="pageSize"
      @clearItem="clearItem"
      @dragEnter="dragEnter"
      @delItem="delItem"
      @handleDealData="handleDealData"
    >
      <template v-slot:right-btn="{item, index}">
        <slot name="right-btn" v-bind="{item, index}"></slot>
      </template>
      <slot name="right-footer"></slot>
    </transfer-view>
  </div>
</template>
<script>
  import ElButton from 'modesign-ui/packages/button';
  import Emitter from 'modesign-ui/src/mixins/emitter';
  import Locale from 'modesign-ui/src/mixins/locale';
  import TransferPanel from './transfer-panel.vue';
  import TransferView from './transfer-view.vue';
  import Migrating from 'modesign-ui/src/mixins/migrating';

  export default {
    name: 'ElTransfer',

    mixins: [Emitter, Locale, Migrating],

    components: {
      TransferPanel,
      TransferView,
      ElButton
    },

    props: {
      data: {
        type: Array,
        default() {
          return [];
        }
      },
      pagination:{
        type:Boolean,
        default() {
          return false;
        }
      },
      pageSize:{
        type:Number,
        default() {
          return 10;
        }
      },
      filterPlaceholder: {
        type: String,
        default: ''
      },
      filterMethod: Function,
      leftDefaultChecked: {
        type: Array,
        default() {
          return [];
        }
      },
      renderContent: Function,
      value: {
        type: Array,
        default() {
          return [];
        }
      },
      filterable: Boolean,
      props: {
        type: Object,
        default() {
          return {
            label: 'label',
            key: 'key',
            disabled: 'disabled'
          };
        }
      },
      type: {
        type: String,
        default: 'checkbox'
      },
      treeProps: {
        type: Object
      },
      userList: {
        type: Array,
        default() {
          return [];
        }
      },
      showLine: {
        // 树型 右侧是否显示路径
        type: Boolean,
        default: false
      },
      simple: {
        // 简单用法
        type: Boolean,
        default: false
      },
      dragable: {
        type: Boolean,
        default: false
      },
      fixedList: {
        type: Array,
        default: () => []
      },
      titles: {
        type: Array,
        default: () => []
      },
      isOverflowHidden: {
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        dataTotal:[], //总数据
        Rdata:[], //右侧总数据
        pafinationReset: true, //右侧分页重置当前页0
        pageR:1,
      };
    },
    mounted() {
      this.changeChecked();
    },
    created() {
      this.dataTotal = JSON.parse(JSON.stringify(this.data))
    },
    computed: {
      dataObj() {
        const key = this.props.key;
        return this.data.reduce((o, cur) => (o[cur[key]] = cur) && o, {});
      },
      sourceData() {
        return this.dataTotal
      },
      targetData() {
        let result = [];
        // 这里需要判断是分组还是不分组的
        if (this.type === 'checkbox') {
          for (let i = 0; i < this.value.length; i++) {
            if (this.data[0].options) {
              // 分组 暂时只支持一级分组
              this.data.forEach(item => {
                item.options.forEach(foo => {
                  if (foo[this.props.key] === this.value[i]) {
                    result.push(foo);
                  }
                })
              })
            } else {
              const itemIndex = this.data.findIndex(x => x[this.props.key] === this.value[i]);
              if (itemIndex > -1) {
                result.push(this.data[itemIndex]);
              }
            }
          }
        } else {
          // 树型
          result = this.getCheckedTreeNode()
        }
        return result;
      }
    },
    watch: {
      value(val) {
        this.dispatch('ElFormItem', 'el.form.change', val);
        this.pafinationReset = !(val && val.length > 0)
        this.changeChecked();
      },
      data: {
        handler(newVal) {
          this.dataTotal = JSON.parse(JSON.stringify(newVal))
        },
        deep: true
      }
    },

    methods: {
      // 左侧为树型结构时，获取选中的数据
      getCheckedTreeNode() {
        const checkedNodes = [];
        const { value, props } = this;
        const findTreeNode = function(nodeList, name) {
          nodeList.forEach(node => {
            if (node.children) {
              findTreeNode(node.children, `${name}${node.label} / `)
            } else {
              const nodeIndex = value.findIndex(x => x === node[props.key])
              if (nodeIndex > -1) {
                node.labelway = name + node.label;
                checkedNodes[nodeIndex] = node;
              }
            }
          })
        };

        findTreeNode(this.data, '');
        return checkedNodes;
      },

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

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

      // 切换绑定值选中状态
      changeItem(bool, item, direction) {
        let currentValue = this.value.slice();
        const key = this.props.key;
        if (bool && !currentValue.includes(item[key])) {
          currentValue.push(item[key])
        } else if (!bool) {
          const delIndex = currentValue.findIndex(x => x === item[key]);
          if (delIndex > -1) {
            currentValue.splice(delIndex, 1);
          }
        }
        this.$emit('input', currentValue);
        this.$emit('change', currentValue, direction);
      },

      changeTreeItem(list) {
        this.$emit('input', list);
        this.$emit('change', list, 'left');
      },

      // 点击全选按钮
      changeAllItem(value) {
        this.$emit('input', value);
        this.$emit('change', value, 'left');
      },

      // 清空右侧所有项
      clearItem(arr) {
        if (this.fixedList.length > 0) {
          const result = arr.filter(x => this.fixedList.includes(x[this.props.key])).map(x => x[this.props.key]);
          this.$emit('input', result);
          this.$emit('change', result, 'right');
        } else {
          this.$emit('input', []);
          this.$emit('change', [], 'right');
        }
        this.$nextTick(() => {
          this.changeChecked()
        });
      },

      // 删掉所选项
      delItem(item) {
        this.changeItem(false, item, 'right');
        this.$nextTick(() => {
          this.changeChecked();
          this.$emit('right-delete', this.value, item[this.props.key]);
        });
      },

      // 对数据进行处理
      handleDealData(list) {
        this.$emit('handleDealData', list);
      },

      // 拖拽结束
      dragEnter(list) {
        const currentValue = list.map(x => x[this.props.key])
        this.$emit('input', currentValue);
        this.$emit('change', currentValue, 'right');
      },

      // 初始化数据或改变右侧值时，同步panel里checked的值
      changeChecked() {
        this.$refs.leftPanel.changeChecked(this.value);
      }
    }
  };
</script>
