<template>
  <div class="top-right-btn" :style="style">
    <el-row>
      <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top" v-if="search">
        <el-button size="mini" circle icon="el-icon-search" @click="toggleSearch()" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button size="mini" circle icon="el-icon-refresh" @click="refresh()" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="显隐列" placement="top" v-if="columns">
        <el-button size="mini" circle icon="el-icon-menu" @click="showColumn()" v-if="showColumnsType == 'transfer'" />
        <el-dropdown trigger="click" :hide-on-click="false" style="padding-left: 12px"
          v-if="showColumnsType == 'checkbox'">
          <el-button size="mini" circle icon="el-icon-menu" />
          <el-dropdown-menu slot="dropdown">
            <template>
              <el-dropdown-item v-for="item in columns" :key="item.key">
                <el-checkbox :checked="item.visible" @change="checkboxChange($event, item.label)" :label="item.label" />
              </el-dropdown-item>
            </template>
          </el-dropdown-menu>
        </el-dropdown>
      </el-tooltip>
    </el-row>
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-transfer :titles="['显示', '隐藏']" v-model="value" :data="columns" @change="dataChange"
        @left-check-change="handleLeftCheckChange">
        <template #left-footer>
          <el-button size="mini" icon="el-icon-arrow-up" @click="moveItem('up')"></el-button>
          <el-button size="mini" icon="el-icon-arrow-down" @click="moveItem('down')"></el-button>
        </template>
        <!-- 添加 moveDown 方法 -->
      </el-transfer>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存设置</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { updateCOLUMN } from "@/api/system/column";
import {
  getConfig,
  addConfig,
  listConfig,
  updateConfig
} from "@/api/system/user_config";
import { find, merge } from "lodash";
export default {
  name: "RightToolbar",
  data () {
    return {
      // 当前用户配置信息
      configData: null,
      // 显隐数据
      value: [],
      // 弹出层标题
      title: "显示/隐藏",
      // 是否显示弹出层
      open: false,
      hideColumn: [],
      leftCheckedKeys: [] // 选中项的键值数组
    };
  },
  props: {
    /* 是否显示检索条件 */
    showSearch: {
      type: Boolean,
      default: true,
    },
    /* 显隐列信息 */
    columns: {
      type: Array,
    },
    /* 是否显示检索图标 */
    search: {
      type: Boolean,
      default: true,
    },
    /* 显隐列类型（transfer穿梭框、checkbox复选框） */
    showColumnsType: {
      type: String,
      default: "checkbox",
    },
    /* 右外边距 */
    gutter: {
      type: Number,
      default: 10,
    },
    businessCode: {
      type: String,
      default: "",
    },
    tableNo: {
      type: Number,
      default: 0
    }
  },
  computed: {
    style () {
      const ret = {};
      if (this.gutter) {
        ret.marginRight = `${this.gutter / 2}px`;
      }
      return ret;
    }
  },
  created () {
    let params = {
      userId: this.$store.state.user.id,
      routerPath: this.$route.path,
      compName: "table"
    }
    let customCols = [];
    // 根据当前用户的ID和路径和组件名，查询当用户在当前页面中针对指定组件的配置信息。
    listConfig(params).then((req) => {
      if (req.rows.length > 0) {
        this.configData = req.rows[0];
        customCols = eval(req.rows[0].cnfJson);
        this.$emit("customCols", customCols);
        // 显隐列初始默认隐藏列
        for (let item of customCols) {
          if (item.visible === false) {
            this.value.push(item.columnName);
          }
        }
      }

    });
    if (this.showColumnsType == 'transfer') {
      // 显隐列初始默认隐藏列
      for (let item in this.columns) {
        if (this.columns[item].visible === false) {
          this.value.push(parseInt(item));
        }
      }
    }
  },
  methods: {
    saveConfig (userCnf) {
      this.configData = {
        userId: this.$store.state.user.id,
        routerPath: this.$route.path,
        compName: "table",
        cnfJson: JSON.stringify(this.columns)
      };
      updateConfig(this.configData);
    },
    // 搜索
    toggleSearch () {
      this.$emit("update:showSearch", !this.showSearch);
    },
    // 刷新
    refresh () {
      this.$emit("queryTable");
    },
    // 右侧列表元素变化
    dataChange (data) {

      for (let item in this.columns) {
        const key = this.columns[item].key;
        this.columns[item].visible = !data.includes(key);
      }
    },
    //左边
    handleLeftCheckChange (newChecked) {

      this.leftCheckedKeys = newChecked;

    },
    // 打开显隐列dialog
    showColumn () {
      this.open = true;
    },
    // 勾选
    checkboxChange (event, label) {
      this.columns.filter(item => item.label == label)[0].visible = event;
    },
    submitForm () {
      console.log(this.businessCode)
      // 日照项目增加－－保存用户自定义列信息
      // 判断用户配置数据是否存在，存在更新，不存在新增。

      this.configData = {
        userId: this.$store.state.user.id,
        routerPath: this.$route.path,
        compName: "table",
        cnfJson: JSON.stringify(this.columns)
      };
      updateConfig(this.configData);
      this.$emit("customCols", this.columns);
      // 显隐列初始默认隐藏列
      this.hideColumn = []
      for (let item in this.columns) {
        if (this.columns[item].visible === false) {
          this.hideColumn.push(this.columns[item].columnName);
        }
      }
      console.log(this.businessCode)

      if (this.hideColumn.length > 0) {
        this.form = {
          businessCode: this.businessCode,
          tableNo: this.tableNo,
          columnHide: this.hideColumn.join(","),
        };
        updateCOLUMN(this.form).then(response => {
          this.$modal.msgSuccess("字段设置成功");
        });
      }
      this.open = false;
    },
    cancel () {
      this.open = false;
    },
    moveItem (direction) {
      debugger
      const selectedItems = this.columns.filter(item => this.leftCheckedKeys.includes(item.key));
      if (direction === 'up') {
        for (let item of selectedItems) {
          const index = this.columns.indexOf(item);
          if (index > 0) {
            this.columns[index - 1].seq = this.columns[index].seq;
            this.columns[index].seq = this.columns[index].seq - 1;
            this.columns.sort((a, b) => {
              if (a.seq < b.seq) {
                return -1; // a 应该排在 b 前面
              }
              if (a.seq > b.seq) {
                return 1; // a 应该排在 b 后面
              }
              return 0; // a 和 b 相等
            })
          } else {
            // 已经在最顶部，不能再向上移动
            this.$message.error('已经是最顶部了，不能再向上移动！');
            break;
          }
        }
      }
      if (direction === 'down') {
        debugger
        selectedItems.reverse();
        for (let item of selectedItems) {
          const index = this.columns.indexOf(item);
          if (index < this.columns.length - 2) {
            this.columns[index + 1].seq = this.columns[index].seq;
            this.columns[index].seq = this.columns[index].seq + 1;
            this.columns.sort((a, b) => {
              if (a.seq < b.seq) {
                return -1; // a 应该排在 b 前面
              }
              if (a.seq > b.seq) {
                return 1; // a 应该排在 b 后面
              }
              return 0; // a 和 b 相等
            })
          } else {
            // 已经在最底部，不能再向下移动
            this.$message.error('已经是最底部了，不能再向下移动！');
            return;
          }
        }
      }
      // 更新左侧选中状态以反映移动后的位置
      this.leftCheckedKeys = selectedItems.map(item => item.key);
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-transfer__button {
  border-radius: 50%;
  padding: 12px;
  display: block;
  margin-left: 0px;
}

::v-deep .el-transfer__button:first-child {
  margin-bottom: 10px;
}
</style>
