<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import mPage from "@/components/mPage.vue";
import { raiInterface } from "@/api/api.js";
import { ElMessage,ElMessageBox } from "element-plus";
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";

const bannerTableColumn = computed(() => {
  return BannerTableColumn;
});

const isDrag = computed(() => {
  return statusValue.value == "1" ? true : false;
});

const dataList = ref([
  { 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 },
]);
const statusValue = ref("1");
const statusOptions = ref([
  {
    label: "已发布",
    value: "1",
  },
  {
    label: "已下线",
    value: "0",
  },
]); // 状态的筛选条件
const tableList = ref([]); // 列表的数据



const bannerVisibleText = ref("");
const editBannerList = ref({});
const addBannerRef = ref(null);
// 获取列表数据
function getDataList() {
  dataList.value.forEach(async (item, index) => {
    const res = await raiInterface.getBannerList({
      PageSize: item.pageSize,
      CurrentIndex: item.page_no,
      ListType: item.name,
      Status: statusValue.value,
    });
    if (res.Ret === 200) {
      item.tableList = res.Data.List;
      item.total = res.Data.Paging.Totals;
    }
  });
}
// 获取一个的单独数据 不想写if了
async function getOneDataList(item) {
  const res = await raiInterface.getBannerList({
    PageSize: item.pageSize,
    CurrentIndex: item.page_no,
    ListType: item.name,
    Status: statusValue.value,
  });
  if (res.Ret === 200) {
    item.tableList = res.Data.List;
    item.total = res.Data.Paging.Totals;
  }
}
// 获取弹框图片的数据
async function getSelectImgList() {
  const res = await raiInterface.getBannerImgList({
    CurrentIndex: page_no_img.value,
    PageSize: 10,
  });
  if (res.Ret === 200) {
    banerImgList.value = res.Data.List;
    totalImg.value = res.Data.Paging.Totals;
  }
}

const selectImgVisible = ref(false); //选择图片的弹框
const banerImgList = ref([]); //选择图片的数据
const banerImgListArr = ref([]); //选择图片的数据
// 获取弹框图片的数据
async function getSelectImgListAll() {
  const res = await raiInterface.getBannerImgList({
    CurrentIndex: 1,
    PageSize: 100000,
  });
  if (res.Ret === 200) {
    banerImgListArr.value = res.Data.List;
    totalImg.value = res.Data.Paging.Totals;
    banerImgList.value = _.cloneDeep(banerImgListArr.value).splice(0, 10);
  }
}


const addBannerVisible = ref(false); // 添加编辑banner的弹框
const isShowPreview = ref(false); // 预览的弹框
const previewList = ref({}); // 预览的数据
const detailsDlgVisible = ref(false); //详情的弹框
const tableDetailList = ref({}); //详情的数据
// 添加banner
async function addHandlerBanner(type, item) {
  bannerVisibleText.value = type;
  addBannerVisible.value = true;
  editBannerList.value = item;
}


// banner弹框的确认事件
// function addBannerHandler() {
//   this.$refs["form"].validate((valid) => {
//     if (valid) {
//     }
//   });
// }
// // banner弹框的关闭事件
// function handleClose() {
//   this.$refs["form"].resetFields();
//   this.popData = {
//     type: "",
//     showTime: "",
//     order: "",
//     link: "",
//     imgUrl: "",
//   };
//   this.bannerVisible = false;
// }


// 点击选择添加图片事件
function handleshowChooseImgPop() {
  selectImgVisible.value = true;
}
// 点击图片的事件
function clickSelectImg(item) {
  addBannerRef.value.addBannerForm.imgUrl = item.IndexImg;
  addBannerRef.value.addBannerForm.imgId = item.ImgId;
  selectImgVisible = false;
}
// 筛选框的change事件
function handleChange() {
  dataList.value.forEach((item) => (item.page_no = 1));
  getDataList();
}

const totalImg = ref(0);
const page_no_img = ref(1);
//分页
async function handleCurrentChange(item, page) {
  item.page_no = page;
  getOneDataList(item);
}
// 选择图片的分页
function handleCurrentChangeSelectImg(page) {
  page_no_img.value = page;
  getSelectImgList();
}
// 预览图片
function handlePreviewImg(imgId, obj) {
  banerImgListArr.value.forEach((item) => {
    if (imgId === item.ImgId) {
      previewList.value = { ...item, ...obj };
    }
  });
  nextTick(() => {
    isShowPreview.value = true;
  });
}
// table下线的操作事件
async function handleRowButton(item, row) {
  ElMessageBox.confirm(`确定要下线此banner吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await raiInterface.bannerPublishAndcancel({ BannerId: row.BannerId });
      if (res.Ret === 200) {
        ElMessage.success("下线成功！");
        let page_num = Math.ceil((item.total - 1) / item.pageSize);
        if (item.page_no > page_num) {
          item.page_no = page_num;
        }
        getOneDataList(item);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消下线`,
      });
    });
}
// 添加或者编辑的确定事件
function preserveAndPublish(item) {
  dataList.value.forEach((key) => {
    if (key.name === (item.name || item.ListType)) {
      getOneDataList(key);
    }
  });
}

// 拖拽的初始化和处理数据
function setupSortable(dom, index) {
  let fromIndexNumber = null;
  // 获取表格row的父节点
  const sortableInstanceIs = Sortable.create(dom, {
    sort: isDrag.value,
    // 停靠位置样式
    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(dataList.value[fromIndex].tableList[oldIndex]); //拷贝数据
      // const newList = _.cloneDeep(dataList.value[toIndex].tableList);
      const currRow = dataList.value[fromIndex].tableList[oldIndex]; //拷贝数据
      const newList = dataList.value[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",
      };
      bannerDrag(params, currRow);
    },
  });
  // // 动态控制拖拽功能
  // this.$watch("isDrag", (newVal) => {
  //   if (newVal) {
  //     sortableInstanceIs.option("disabled", false); // 启用拖拽
  //   } else {
  //     sortableInstanceIs.option("disabled", true); // 禁用拖拽
  //   }
  // });
}

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

  if (res.Ret === 200) {
    ElMessage.success("拖动成功!");
    dataList.value = [
      { 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 getDataList();
  }
}

/* 三件套*/
function handleRowClick(row, key) {
  if (key === "Title") {
    tableDetailList.value = row;
    detailsDlgVisible.value = true;
  }
}
function handleRowStyle(key, row) {
  let obj = {
    Title: "color: #409eff; cursor: pointer",
    Status: key == "Status" && row.Status == 1 ? "color: #FF8A00" : "",
  };
  return obj[key] ? obj[key] : "";
}
function handleRowContent(row, key) {
  if (key == "Status") {
    return row[key] == 1 ? "已发布" : "已下线";
  } else {
    return row[key];
  }
}
/* 三件套*/

/* 获取表格的实例*/
const tables = ref([]);
const setItemRef = (el) => {
  tables.value.push(el);
};
nextTick(() => {
  tables.value.forEach((key,index) => {
    const tbody = key.$el.querySelector("tbody");
    setupSortable(tbody);
    tbody.setAttribute("data-index",index);
  });
});


onMounted(async () => {
  await getDataList();
  getSelectImgListAll()
});

setTimeout(() => {}, 1000);
</script>

<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="setItemRef" :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 #default="{ 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 #default="{ 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="选择图片" v-model="selectImgVisible" width="80%" draggable :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="addBannerVisible"
      :bannerVisibleText="bannerVisibleText"
      :editBannerList="editBannerList"
      @showImgPop="handleshowChooseImgPop"
      @previewImg="handlePreviewImg"
      @preserveAndPublish="preserveAndPublish"
    />
    <!-- 详情的弹框 -->
    <!-- <details-dlg :detailsDlgVisible="detailsDlgVisible" :tableDetailList="tableDetailList" @previewImg="handlePreviewImg" /> -->
  </div>
</template>

<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>
