<template>
  <div class="container bannar-container">
    <div class="container-top" style="margin-bottom: 20px">
      <el-select v-model="statusValue" clearable placeholder="请选择状态" @change="handleChange">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
    </div>
    <div class="content-box">
      <div class="content-table" :style="{ margin: item.name == 'B' ? '0 35px' : '' }" v-for="(item, index) in dataList" :key="item.name">
        <el-table :data="item.tableList" border :ref="'table' + index" :style="isDrag && { cursor: 'move' }">
          <el-table-column
            v-for="column_list in bannerTableColumn"
            :key="column_list.key"
            :label="column_list.label"
            :prop="column_list.key"
            :width="column_list.widthsty"
            :align="column_list.key === 'Title' ? '' : 'center'"
          >
            <template #header>
              <div style="text-align: center">{{ column_list.label }}</div>
            </template>
            <template slot-scope="{ row }">
              <span @click="handleRowClick(row, column_list.key)" :style="handleRowStyle(column_list.key, row)">
                {{ handleRowContent(row, column_list.key) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="125">
            <template slot-scope="{ row }">
              <span v-if="row.Status === 1" class="editsty" @click="handleRowButton(item, row)">下线 &nbsp;&nbsp;</span>
              <span class="editsty" @click="addHandlerBanner('编辑', row)"> 编辑</span>
            </template>
          </el-table-column>
        </el-table>
        <el-col :span="24" class="toolbar">
          <m-page :total="item.total" :page_no="item.page_no" :pageSize="item.pageSize" @handleCurrentChange="handleCurrentChange(item, $event)" />
        </el-col>
        <span class="add-btn" @click="addHandlerBanner('添加', item)">添加banner</span>
      </div>
    </div>
    <!-- 选择图片的弹框 -->
    <el-dialog title="选择图片" :visible.sync="selectImgVisible" width="80%" v-dialogDrag :close-on-click-modal="false" :modal-append-to-body="false" center>
      <div class="seleect-img-box">
        <div class="content-img" @click="clickSelectImg(item)" v-for="item in banerImgList" :key="item.ImgId">
          <img :src="item.IndexImg" alt="" class="item-img" />
        </div>
      </div>
      <el-col :span="24" class="toolbar">
        <m-page :total="totalImg" :page_no="page_no_img" :pageSize="10" @handleCurrentChange="handleCurrentChangeSelectImg" />
      </el-col>
    </el-dialog>
    <!-- 预览图片 -->
    <preview-banner v-if="isShowPreview" :previewList="previewList" />
    <!-- 添加或者编辑banner -->
    <add-banner-dlg
      ref="addBannerRef"
      :addBannerVisible.sync="addBannerVisible"
      :bannerVisibleText.sync="bannerVisibleText"
      :editBannerList="editBannerList"
      @showImgPop="handleshowChooseImgPop"
      @previewImg="handlePreviewImg"
      @preserveAndPublish="preserveAndPublish"
    />
    <!-- 详情的弹框 -->
    <details-dlg :detailsDlgVisible.sync="detailsDlgVisible" :tableDetailList="tableDetailList" @previewImg="handlePreviewImg" />
  </div>
</template>

<script>
import mPage from "@/components/mPage.vue";
import { raiInterface } from "@/api/api.js";
import { BannerTableColumn } from "./bannerCommon/bannerData";
import AddBannerDlg from "./bannerCommon/addBannerDlg.vue";
import PreviewBanner from "./bannerCommon/previewBanner.vue";
import DetailsDlg from "./bannerCommon/detailsDlg.vue";
import Sortable from "sortablejs";
export default {
  name: "",
  computed: {
    bannerTableColumn() {
      return BannerTableColumn;
    },
    isDrag() {
      return this.statusValue == "1" ? true : false;
    },
  },
  components: {
    mPage,
    AddBannerDlg,
    PreviewBanner,
    DetailsDlg,
    Sortable,
  },
  data() {
    return {
      dataList: [
        { name: "A", tableList: [], total: 0, page_no: 1, pageSize: 10 },
        { name: "B", tableList: [], total: 0, page_no: 1, pageSize: 10 },
        { name: "C", tableList: [], total: 0, page_no: 1, pageSize: 10 },
      ],
      statusValue: "1",
      statusOptions: [
        {
          label: "已发布",
          value: "1",
        },
        {
          label: "已下线",
          value: "0",
        },
      ], // 状态的筛选条件
      tableList: [], // 列表的数据
      selectImgVisible: false, //选择图片的弹框
      banerImgList: [], //选择图片的数据
      banerImgListArr: [], //选择图片的数据
      totalImg: 0,
      page_no_img: 1,
      addBannerVisible: false, // 添加编辑banner的弹框
      isShowPreview: false, // 预览的弹框
      previewList: {}, // 预览的数据
      detailsDlgVisible: false, //详情的弹框
      tableDetailList: {}, //详情的数据
      bannerVisibleText: "",
      editBannerList: {},
    };
  },
  mounted() {
    const tables = this.$refs;
    Object.keys(tables).forEach((key) => {
      if (key.includes("table")) {
        const table = tables[key][0];
        const tbody = table.$el.querySelector("tbody");
        const index = parseInt(key.slice(5));
        this.setupSortable(tbody, index);
        tbody.setAttribute("data-index", index);
      }
    });
    this.getDataList();
    this.getSelectImgListAll();
  },
  methods: {
    // 获取列表数据
    async getDataList() {
      this.dataList.forEach(async (item, index) => {
        const res = await raiInterface.getBannerList({
          PageSize: item.pageSize,
          CurrentIndex: item.page_no,
          ListType: item.name,
          Status: this.statusValue,
        });
        if (res.Ret === 200) {
          item.tableList = res.Data.List;
          item.total = res.Data.Paging.Totals;
        }
      });
    },
    // 获取一个的单独数据 不想写if了
    async getOneDataList(item) {
      const res = await raiInterface.getBannerList({
        PageSize: item.pageSize,
        CurrentIndex: item.page_no,
        ListType: item.name,
        Status: this.statusValue,
      });
      if (res.Ret === 200) {
        item.tableList = res.Data.List;
        item.total = res.Data.Paging.Totals;
      }
    },
    // 获取弹框图片的数据
    async getSelectImgList() {
      const res = await raiInterface.getBannerImgList({
        CurrentIndex: this.page_no_img,
        PageSize: 10,
      });
      if (res.Ret === 200) {
        this.banerImgList = res.Data.List;
        this.totalImg = res.Data.Paging.Totals;
      }
    },
    // 获取弹框图片的数据
    async getSelectImgListAll() {
      const res = await raiInterface.getBannerImgList({
        CurrentIndex: 1,
        PageSize: 100000,
      });
      if (res.Ret === 200) {
        this.banerImgListArr = res.Data.List;
        this.totalImg = res.Data.Paging.Totals;
        this.banerImgList = _.cloneDeep(this.banerImgListArr).splice(0, 10);
      }
    },

    // 添加banner
    async addHandlerBanner(type, item) {
      this.bannerVisibleText = type;
      this.addBannerVisible = true;
      this.editBannerList = item;
    },
    // banner弹框的确认事件
    addBannerHandler() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
        }
      });
    },
    // banner弹框的关闭事件
    handleClose() {
      this.$refs["form"].resetFields();
      this.popData = {
        type: "",
        showTime: "",
        order: "",
        link: "",
        imgUrl: "",
      };
      this.bannerVisible = false;
    },
    // 点击选择添加图片事件
    handleshowChooseImgPop() {
      this.selectImgVisible = true;
    },
    // 点击图片的事件
    clickSelectImg(item) {
      this.$refs.addBannerRef.addBannerForm.imgUrl = item.IndexImg;
      this.$refs.addBannerRef.addBannerForm.imgId = item.ImgId;
      this.selectImgVisible = false;
    },
    // 筛选框的change事件
    handleChange() {
      this.dataList.forEach((item) => (item.page_no = 1));
      this.getDataList();
    },
    //分页
    async handleCurrentChange(item, page) {
      item.page_no = page;
      this.getOneDataList(item);
    },
    // 选择图片的分页
    handleCurrentChangeSelectImg(page) {
      this.page_no_img = page;
      this.getSelectImgList();
    },
    // 预览图片
    handlePreviewImg(imgId, obj) {
      this.banerImgListArr.forEach((item) => {
        if (imgId === item.ImgId) {
          this.previewList = { ...item, ...obj };
        }
      });
      this.$nextTick(() => {
        this.isShowPreview = true;
      });
    },
    // table下线的操作事件
    async handleRowButton(item, row) {
      this.$confirm(`确定要下线此banner吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await raiInterface.bannerPublishAndcancel({ BannerId: row.BannerId });
          if (res.Ret === 200) {
            this.$message.success("下线成功！");
            let page_num = Math.ceil((item.total - 1) / item.pageSize);
            if (item.page_no > page_num) {
              item.page_no = page_num;
            }
            this.getOneDataList(item);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消下线`,
          });
        });
    },
    // 添加或者编辑的确定事件
    preserveAndPublish(item) {
      this.dataList.forEach((key) => {
        if (key.name === (item.name || item.ListType)) {
          this.getOneDataList(key);
        }
      });
    },

    // 拖拽的初始化和处理伙计
    setupSortable(dom, index) {
      const _this = this;
      let fromIndexNumber = null;
      const sortableInstanceIs = Sortable.create(dom, {
        sort: _this.isDrag,
        // 停靠位置样式
        ghostClass: "sortable_ghost",
        group: { name: "tableGroup", pull: true, put: true },
        onStart(item) {
          const { from } = item;
          fromIndexNumber = parseInt(from.getAttribute("data-index"));
        },
        onEnd(obj) {
          const { from, to, newIndex, oldIndex } = obj;
          const fromIndex = parseInt(from.getAttribute("data-index"));
          const toIndex = parseInt(to.getAttribute("data-index"));
          if (newIndex == oldIndex && fromIndex == toIndex) return;
          const currRow = _.cloneDeep(_this.dataList[fromIndex].tableList[oldIndex]); //拷贝数据
          const newList = _.cloneDeep(_this.dataList[toIndex].tableList);

          let PreviousBannerId = 0;
          let NextBannerId = 0;

          if (newIndex === 0) {
            PreviousBannerId = 0;
            if (newList && newList[newIndex]) NextBannerId = newList[newIndex].BannerId;
          } else if (fromIndex != toIndex && newIndex === newList.length) {
            PreviousBannerId = newList[newIndex - 1].BannerId;
            NextBannerId = 0;
          } else if (fromIndex === toIndex && newIndex === newList.length - 1) {
            PreviousBannerId = newList[newIndex].BannerId;
            NextBannerId = 0;
          } else {
            if (fromIndex === toIndex && newIndex > oldIndex) {
              PreviousBannerId = newList[newIndex].BannerId;
              NextBannerId = newList[newIndex + 1].BannerId;
            } else {
              PreviousBannerId = newList[newIndex - 1].BannerId;
              NextBannerId = newList && newList[newIndex] ? newList[newIndex].BannerId : 0;
            }
          }

          let params = {
            BannerId: currRow.BannerId,
            PreviousBannerId,
            NextBannerId,
            ListType: toIndex == 0 ? "A" : toIndex == 1 ? "B" : "C",
          };
          _this.bannerDrag(params, currRow);
        },
      });
      // 动态控制拖拽功能
      this.$watch("isDrag", (newVal) => {
        if (newVal) {
          sortableInstanceIs.option("disabled", false); // 启用拖拽
        } else {
          sortableInstanceIs.option("disabled", true); // 禁用拖拽
        }
      });
    },

    // 拖拽后的接口
    async bannerDrag(params, currRow) {
      const res = await raiInterface.bannerMoveDrag(params);
      this.dataList = [];

      if (res.Ret === 200) {
        this.$message.success("拖动成功!");
        this.dataList = [
          { name: "A", tableList: [], total: 0, page_no: 1, pageSize: 10 },
          { name: "B", tableList: [], total: 0, page_no: 1, pageSize: 10 },
          { name: "C", tableList: [], total: 0, page_no: 1, pageSize: 10 },
        ];
        await this.getDataList();
      }
    },

    /* 三件套*/
    handleRowClick(row, key) {
      if (key === "Title") {
        this.tableDetailList = row;
        this.detailsDlgVisible = true;
      }
    },
    handleRowStyle(key, row) {
      let obj = {
        Title: "color: #409eff; cursor: pointer",
        Status: key == "Status" && row.Status == 1 ? "color: #FF8A00" : "",
      };
      return obj[key] ? obj[key] : "";
    },
    handleRowContent(row, key) {
      if (key == "Status") {
        return row[key] == 1 ? "已发布" : "已下线";
      } else {
        return row[key];
      }
    },
    /* 三件套*/
  },
};
</script>
<style>
.sortable_ghost {
  background-color: #999 !important;
}
</style>
<style scoped lang="scss">
.bannar-container {
  .tabs-content {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120px;
    height: 40px;
    color: #409eff;
    background: #ecf5ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
  }
  .tabs-active {
    color: #ffffff;
    background: #409eff;
    border: none;
  }
  .pre-img-box {
    position: relative;
    width: 120px;
    height: 120px;
    .del {
      display: none;
      color: #fff;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      text-align: center;
      line-height: 24px;
      background-color: rgba($color: #000000, $alpha: 0.8);
      cursor: pointer;
    }
    &:hover {
      .del {
        display: block;
      }
    }
  }
  .seleect-img-box {
    display: flex;
    flex-wrap: wrap;
    .content-img {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 236px;
      height: 133px;
      flex-shrink: 0;
      margin: 0 50px 50px 0;
      border: 1px solid #dcdfe6;
      cursor: pointer;
      .item-img {
        width: 222px;
        height: 119px;
      }
    }
  }
  .content-box {
    display: flex;
  }
  .content-table {
    width: 530px;
    height: 720px;
    background: #ffffff;
    box-shadow: 2px 6px 6px rgba(0, 0, 0, 0.05);
    .add-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 120px;
      height: 40px;
      background: #409eff;
      border-radius: 4px;
      color: #fff;
      margin: 80px auto 0;
      cursor: pointer;
    }
  }
  .container-top {
    width: 1620px;
    padding: 20px;
    background: #ffffff;
    box-shadow: 2px 6px 6px rgba(0, 0, 0, 0.05);
  }
}
</style>
