<template>
  <!-- @visibleChange="handleVisibleChange" -->
  <a-dropdown :overlayClassName="'p-table'" :trigger="['click']" :placement="'bottomLeft'" :visible.sync="sVisible" @visibleChange="visibleChange">
    <div slot="overlay" class="ant-table-filter-dropdown">
      <a-menu ref="menuList" class="ant-dropdown-menu" :selectedKeys="selectedKeys" :style="{ maxHeight: menuheight }">
        <!-- @mouseleave="handleMouseleave" -->

        <a-menu-item
          v-for="(item, i) in list"
          :key="item.dataIndex"
          :class="['ant-dropdown-menu-item', 'flex-item', (item._s = i), hover === item.dataIndex ? 'hover' : '']"
          style="content-visibility: auto"
          @mousemove="() => (hover = item.dataIndex)"
        >
          <a-checkbox :defaultChecked="!item.hidden" :checked="!item.hidden" @change="handleCheckboxChange($event, item)">
            {{ item.title || item.dataIndex }}
          </a-checkbox>
          <div class="columns-move">
            <div class="show">
              <a-button
                :disabled="i === (list[0].dataIndex === defaultCountKey ? 1 : 0)"
                style="margin-right: 3px"
                type="dashed"
                icon="arrow-up"
                shape="circle"
                size="small"
                @click="handleMoveUp($event, item, i)"
              ></a-button>
              <a-button :disabled="i === list.length - 1" style="margin-right: 3px" type="dashed" icon="arrow-down" shape="circle" size="small" @click="handleMoveDown($event, item, i)"></a-button>
            </div>
          </div>
        </a-menu-item>
      </a-menu>
      <a-row type="flex" :style="{ borderTop: '1px solid #e8e8e8', padding: '10px' }" justify="space-between">
        <!-- :disabled="!table.backupColMap" -->
        <a-button icon="redo" type="link" size="small" :disabled="!table.backupColMap" @click="handleClearFilters">重置</a-button>
        <a-popconfirm :overlayStyle="{ zIndex: 9999 }" placement="topLeft" autoAdjustOverflow title="是否保存序列数据?" ok-text="Yes" cancel-text="No" @confirm="handleConfirm">
          <a-badge :dot="show">
            <a-button :disabled="!show" icon="save" size="small" type="link">保存</a-button>
          </a-badge>
        </a-popconfirm>
      </a-row>
    </div>
    <a-icon title="Filter menu" type="layout" theme="filled" />
  </a-dropdown>
</template>

<script>
import Sortable from 'sortablejs';
function _onConfirm(columns, fn) {
  const { SERVICE_PLATFORM_POWER_BASE } = require('@/config/serviceSettings.js');
  const id = this.ids;
  const { extendedObjectCode } = this;
  const { menuId } = this.$route.meta;
  const store = this.$store;
  let customize = columns;

  if (id) {
  store.dispatch('getUserColumn', {
    menuId,
  });
  return this.axios({
    method: 'post',
    url: SERVICE_PLATFORM_POWER_BASE + '/customize/edit',
    data: {
      menuId,
      listId: id,
      extendedObjectCode: extendedObjectCode || 0,
      customize: JSON.stringify(customize),
    },
  }).then((response) => {
    if (response.success) {
      store.dispatch('updateColumnPosition', {
        data: customize,
        menuId,
        listId: id,
      });
      fn();
      this.$message.success(response.message);
    } else {
      this.$exception(response);
    }
  });
  } else {
    fn();
  }

}
function _onReset(fn) {
  let confirmLoading = false;
  let _this = this;
  const { SERVICE_PLATFORM_POWER_BASE } = require('@/config/serviceSettings.js');
  const store = this.$store;
  return this.$confirm({
    title: '是否重置默认序列?',
    confirmLoading,
    onOk(clear) {
      confirmLoading = true;
      const id = _this.ids;
      const { menuId } = _this.$route.meta;
      return _this
        .axios({
          url: SERVICE_PLATFORM_POWER_BASE + '/customize/reset',
          method: 'post',
          data: {
            menuId,
            listId: id,
          },
        })
        .then((response) => {
          confirmLoading = false;
          if (response.success) {
            clear();
            store
              .dispatch('getUserColumn', {
                menuId,
              })
              .then((response) => {
                //  _this.setState()
              });
            fn();

            _this.$message.success(response.message);
          } else {
            _this.$exception(response);
          }
          return response;
        });
    },
  });
}
import isEqual from 'lodash/isEqual';

export default {
  name: 'tFilterColumn',
  props: {
    table: null,
    isSave: false,
    columns: [],
    visibleKey: [],
    fixed: {},
    isExp: false,
    defaultCountKey: '',
    ids:{type:null},
    extendedObjectCode: 0,
    list: {
      type: Array,
      default: () => [],
    },
    // backupColMap:null
    //visible:false,
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
    }
  },
  watch: {

    list(values, old) {
      // if (this.id == '734762691092156416-main-table-1') {
      //     debugger
      //   }
      console.log(!isEqual(values, old));
      // if (this.$attrs.id =='RES1000000413_dispatched') {
      //   debugger
      //         }
      if (!isEqual(values, old)) {
        this.table.backupColMap = null;
        this.sortCol();
      }
    },
  },
  created() {

  },
  data() {
    this.cacheCol = {};
    return {
      menuheight: '345px',
      show: false,
      sVisible: false,
      selectedKeys: [],
      columnVisibleKey: [],
      vColumnSort: [],
      vColumnFixed: {},
      hover: null,
    };
  },

  mounted() {
    // if (this.$attrs.id =='RES1000000413_dispatched') {
    //     debugger
    //           }
    this.sortCol();

  },
  methods: {
    sortCol() {
      const id = this.ids;

      if (!id || !this.$route || !this.$route.meta) return;

      const { menuId } = this.$route.meta;
      const store = this.$store;
      let { columnPosition } = store.getters;
      try {
        let _columnPosition = columnPosition[menuId];

        if (_columnPosition && id && Object.prototype.toString.call(_columnPosition[id]) === '[object Object]' && Object.keys(_columnPosition[id]).length > 0) {
          console.log('_columnPosition[id]', _columnPosition);
          if (!id || !this.$route || !this.$route.meta) return;
          _columnPosition = _columnPosition[id];
          this.backList();
          for (let i = 0; i < this.list.length; i++) {
            let item = this.list[i];
            let old = _columnPosition[item.dataIndex];
            for (let key in old) {
              item[key] = old[key];
            }
          }
          this.list.sort((a, b) => {
            return a._s - b._s;
          });
          this.$emit('columnPosition', _columnPosition);
        }
      } catch (e) {
        throw new Error(e);
      }
    },
    _onConfirm,
    _onReset,
    visibleChange(v) {
      this.sVisible = v;
      if (v && !this.sortable) {
        this.rowDrop();
      }
    },
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.menuList;
        this.sortable = Sortable.create(xTable.$el, {
          handle: '.flex-item',
          animation: 150,
          sort: true,
          onEnd: (data) => {
            const { newIndex, oldIndex } = data;
            if (oldIndex == newIndex) return;
            this.backList();

            this.show = true;

            let oldItem = this.list[oldIndex];
            let newItem = this.list[newIndex];
            let cur = this.list.splice(oldIndex, 1)[0];
            this.list.splice(newIndex, 0, cur);
            this.$nextTick(() => {
              this.cacheCol[oldItem.dataIndex] = {...oldItem};
              this.cacheCol[newItem.dataIndex] = {...newItem};
            });
          },
        });
      });
    },
    backList() {
      if (!this.table.backupColMap) {
        let map = {},
          valuelist = [...this.list];
        for (let i = 0; i < valuelist.length; i++) {
          let item = valuelist[i];
          if ('dataIndex' in item) {
            map[item.dataIndex] = { ...item };
          }
        }

        this.table.backupColMap = map;
      }
    },
    handleMoveDown(e, item, i) {
      this.backList();
      this.show = true;
      let k = item.dataIndex;
      e.stopPropagation();

      //向下
      // this.$emit("move", "down", item, i);
      this.hover = k;
      this.selectedKeys = [k];

      let next = this.list[i + 1];
      let old = this.list[i];
      if (next) {
        //把上一删掉
        this.list.splice(i + 1, 1);
        //再插入删掉那个
        this.list.splice(i, 0, next);
        this.$nextTick(() => {
          this.cacheCol[old.dataIndex] = {...old};
          this.cacheCol[next.dataIndex] = {...next};
        });
      }
    },
    handleMoveUp(e, item, i) {
      this.backList();
      this.show = true;
      let k = item.dataIndex;
      e.stopPropagation();
      // this.$emit("move", "up", item, i);
      //向上
      this.hover = item.dataIndex;
      this.selectedKeys = [k];
      //prev
      //向上
      let prev = this.list[i - 1];
      let old = this.list[i];

      if (prev) {
        //把上一删掉
        this.list.splice(i - 1, 1);
        //再插入删掉那个
        this.list.splice(i, 0, prev);
        this.$nextTick(() => {
          this.cacheCol[old.dataIndex] = {...old};
          this.cacheCol[prev.dataIndex] = {...next};
        });
        // this.$emit("columnsChange", { [prev.dataIndex]: prev, [k]: item });
      }
    },
    handleCheckboxChange(e, item) {
      this.backList();
      let key = item.dataIndex;
      this.show = true;

      e.preventDefault();

      if (e.target.checked) {
        this.columnVisibleKey.push(key);
      } else {
        let i = this.columnVisibleKey.indexOf(key);
        i >= 0 && this.columnVisibleKey.splice(i, 1);
      }
      this.columnVisibleKey = Array.from(new Set(this.columnVisibleKey));
      this.selectedKeys = [key];
      item.hidden = !e.target.checked;
      if (item) {
        this.cacheCol[item.dataIndex] = {...item};
      }
    },
    handleConfirm(e) {
      this.sVisible = false;
      let _this = this;
      // let map = { ...this.cacheCol };
      let map = {},valuelist = this.list;
          for (let i = 0; i < valuelist.length; i++) {
            let item = valuelist[i];
            if ("dataIndex" in item) {
              map[item.dataIndex] = item;
            }
          }
      this._onConfirm(map, () => {
        return setTimeout(() => {
          _this.$emit('confirm', map, async () => {
            _this.show = false;
            _this.cacheCol = {};
          });
        }, 0);
      });
    },
    //重置
    handleClearFilters(e) {
      if (!this.table.backupColMap) return;
      this.sVisible = false;
      this._onReset(() => {
        for (let i = 0; i < this.list.length; i++) {
          let item = this.list[i];
          let old = this.table.backupColMap[item.dataIndex];
          for (let key in old) {
            item[key] = old[key];
          }
        }
        this.$emit('reset', this.table.backupColMap);
        this.$nextTick(() => {
          this.show = false;
          this.table.backupColMap = null;
        });
      });
    },
  },
};
</script>
<style lang="less" >
.ant-dropdown-menu-item.hover {
  .ant-checkbox-wrapper {
    cursor: move;
  }
}
</style>
