<!-- @desc:表格筛选  @auth:周兴  @time:2022/12/1 15:04 -->
<template>
  <DkModal :loading="loading"
           v-model="visible"
           :saveFlag="true"
           ref="modal_editAdd"
           title="表格设置"
           @modalOk="submitForm"
           @modalCancel="clear"
  >
    <div class="header-div">
      <div style="width: 200px; display: flex">
        <Button @click="sortTableRight(1)"
                :disabled="currentIndex === null || currentIndex === undefined || currentIndex===0"
                icon="iconfont iconfont icon-quanbuxiangshang-"></Button>
        <Button @click="sortTableRight(2)"
                :disabled="currentIndex === null || currentIndex === undefined || currentIndex===0"
                style="margin-left: 2px" icon="iconfont iconfont icon-shang-"></Button>
        <Button @click="sortTableRight(3)"
                :disabled="currentIndex === null || currentIndex === undefined || currentIndex === tableData.length-1"
                style="margin-left: 2px" icon="iconfont iconfont icon-xia-"></Button>
        <Button @click="sortTableRight(4)"
                :disabled="currentIndex === null || currentIndex === undefined || currentIndex === tableData.length-1"
                style="margin-left: 2px" icon="iconfont iconfont icon-quanbuxiangxia-"></Button>
      </div>
      <!--      <div style="display: flex;width: 50%">-->
      <!--        <SelectPop v-model="displayNo" ref="displayNo" :multiple="false"-->
      <!--                   :show-clear-flag="false"-->
      <!--                   placeholder="请选择顺序"-->
      <!--                   :options="options"-->
      <!--                   labelKey="name"-->
      <!--                   valueKey="id">-->
      <!--        </SelectPop>-->
      <!--        <DkButton ref="confirm" type="primary"-->
      <!--                  @click="change" style="margin-right: 10px;margin-left: 10px;height: 28px">{{ '确定' }}-->
      <!--        </DkButton>-->
      <!--    </div>-->
    </div>
    <!--  主体部分  -->
    <div class="content-div">
      <DkTable :pageFlag="false" :pageTotalFlag="false" primaryKey="itemId"
               :id="'table-'+$options.name"
               :choose-flag="false"
               name="table" ref="table-select" :data="tableData" :height="500"
               :show-setting-flag="false"
               @current-change="handleCurrentChange">
        <DkTableColumn field="label" width="auto" :filter="false" :freeze="false" :sortable="false"
                       title="列名"></DkTableColumn>
        <DkTableColumn type="switch" field="visible" width="100" :filter="false" :switch-disabled="false"
                       :freeze="false"
                       :sortable="false" title="显示"></DkTableColumn>
      </DkTable>
    </div>
  </DkModal>
</template>

<script>

import Sortable from "sortablejs";
import {mapActions} from "vuex";

export default {
  name: "modalTableFilter",
  data() {
    const vm = Window.vm;
    return {
      vm: vm,
      loading: false,
      displayNo: null,
      visible: false,
      currentIndex: null,
      userTableSetInfo: null,
      okFunc: () => {
      },//确定回调
      options: [],
      tableData: [],
      changeFlag: false,
      sortable: null,
    }
  },
  watch: {
    visible(n, o) {
      if (n) {
        this.setDisplayTable();
      }
    },
  },
  methods: {
    currentPageChange() {
    },
    /**
     * @desc   : 切换
     * @author : 周兴
     * @date   : 2022/12/5 12:43
     */
    change() {
      if ((this.currentIndex || this.currentIndex == 0) && this.displayNo) {
        let index = this.displayNo - 1;
        if (!index && index != 0) {
          return;
        }
        this.changeFlag = true;
        let arr = this.tableData.filter((it, ind) => {
          return ind !== this.currentIndex
        })
        arr.splice(index, 0, this.tableData[this.currentIndex])
        this.currentIndex = index
        this.tableData = [...arr]

        setTimeout(() => {
          this.$refs['table-select'].setCurrentRow(this.tableData[this.currentIndex])
          this.$refs['table-select'].$refs['table'].setRadioRow(this.tableData[this.currentIndex]);
          this.$refs['table-select'].$refs['table'].scrollToRow(this.tableData[this.currentIndex]);
        }, 10)
        setTimeout(() => {
          this.changeFlag = false;
        }, 300)
      }
    },
    /**
     * @desc   : 当前行改变
     * @author : 周兴
     * @date   : 2022/12/2 10:53
     */
    handleCurrentChange(e) {
      if (this.changeFlag) {
        return;
      }
      this.currentIndex = e.rowIndex ? e.rowIndex : 0;
    },
    /**
     * @desc   : 设置序号的数据源
     * @author : 周兴
     * @date   : 2022/12/5 11:38
     */
    setDisplayTable() {
      if (this.tableData && this.tableData.length > 0) {
        let options = []
        for (let i = 0; i < this.tableData.length; i++) {
          options.push({id: i + 1, name: (i + 1) + ''})
          if (this.tableData[i].type == 'checkbox' || this.tableData[i].type == 'radio') {
            this.tableData[i].label = '选择'
          } else {
            this.tableData[i].label = this.tableData[i].title
          }
        }
        this.options = options;
      }
    },
    /**
     * @desc   : 移动行
     * @author : 周兴
     * @date   : 2022/12/15 16:28
     */
    rowDrop() {
      this.$nextTick(() => {
        let xTable = this.$refs['table-select'];
        this.sortable = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".vxe-body--row",
            animation: 150,
            onEnd: ({newIndex, oldIndex}) => {
              this.tableData.splice(newIndex, 0, this.tableData.splice(oldIndex, 1)[0]);
              let newArray = this.tableData.slice(0);
              this.tableData = [];
              this.$nextTick(function () {
                this.tableData = newArray;
              });
            },
          }
        );
      });
    },
    /**
     * @desc   : 排序事件
     * @author : 周兴
     * @date   : 2022/4/28 14:27
     */
    sortTableRight(type) {
      this.changeFlag = true;
      let scrollFlag = false;
      let arr = this.tableData.filter((it, index) => {
        return index !== this.currentIndex
      })
      switch (type) {
        //最上
        case 1 :
          arr.splice(0, 0, this.tableData[this.currentIndex])
          this.currentIndex = 0
          scrollFlag = true;
          break
        //上
        case 2 :
          arr.splice(this.currentIndex - 1, 0, this.tableData[this.currentIndex])
          this.currentIndex = this.currentIndex - 1
          break
        //下
        case 3 :
          arr.splice(this.currentIndex + 1, 0, this.tableData[this.currentIndex])
          this.currentIndex = this.currentIndex + 1
          break
        //最下
        case 4 :
          arr.push(this.tableData[this.currentIndex])
          this.currentIndex = this.tableData.length - 1
          scrollFlag = true;
          break
      }
      this.tableData = [...arr]

      setTimeout(() => {
        this.$refs['table-select'].setCurrentRow(this.tableData[this.currentIndex])
        this.$refs['table-select'].$refs['table'].setRadioRow(this.tableData[this.currentIndex]);
        if (this.currentIndex > 15 || scrollFlag) {
          this.$refs['table-select'].$refs['table'].scrollTo(0, this.currentIndex * 30);
        }
      }, 10)
      setTimeout(() => {
        this.changeFlag = false;
      }, 300)
    },
    /**
     * @desc   : 刷新客户端用户表格缓存
     * @author : 周兴
     * @date   : 2023/4/4 17:01
     */
    refreshClient(tableRef, code, tableType, columns) {
      let userTableSetting = vm.$store.state.user.userTableSetting;
      let filters = userTableSetting.filter(it => it.tableRef === tableRef && it.code === code && it.tableType === tableType)
      if (filters && filters.length > 0) {
        filters[0].columns.value = JSON.stringify(columns);
      } else {
        // 如果没有找到需要加进去
        userTableSetting.push({
          code: code,
          tableType: tableType,
          tableRef: tableRef,
          columns: {
            type: 'jsonb',
            value: JSON.stringify(columns)
          }
        })
      }
      return userTableSetting
    },
    /**
     * @desc   : 保存
     * @author : 周兴
     * @date   : 2022/12/2 13:54
     */
    submitForm() {
      this.visible = false;
      // 表格基础信息
      let params = this.userTableSetInfo
      let columns = this.tableData.map(item => {
        return {
          field: item.field,
          visible: item.visible
        }
      })
      params.columns = columns;
      // 保存到数据库
      this.excute(this.$service.userTableSetService, this.$service.userTableSetService.saveUserTableSet, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          // 保存成功
          this.$Message.success(vm.$t('I_001', {'param': vm.$t('save')}))
          // 刷新本地缓存
          this.okFunc(this.tableData,this.refreshClient(params.tableRef, params.code, params.tableType, columns))
        }
      })

    },
    clear() {
      this.visible = false;
    },
  },
  mounted() {
    this.rowDrop();
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
    }
  },
}
</script>

<style scoped>
.header-div {
  align-items: center;
  justify-content: space-between;
  display: flex;
}

/deep/.ivu-btn{
  display: flex;
  justify-content: center;
  align-items: center;
}

.content-div {
  align-items: center;
  justify-content: center;
  display: flex;
  padding-top: 10px;
}

/deep/ .vxe-body--column .nomal-class {
  padding-left: 20px !important;
}

</style>
