<template>
  <el-container class="home">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <Select
        width="200"
        radius
        v-model="sprojectId"
        @change="getProject"
        :selectdata="ProjectData"
        :placeholder="'请选择'"
        :hideClear="true"
      />
      <el-popover
        placement="top"
        width="320"
        v-model="popVisible"
        popper-class="createPopper"
        trigger="manual"
      >
        <p>点击这里即可快速创建拓扑图。</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="popVisible = false"
            >我知道了</el-button
          >
        </div>
        <el-button
          @click="createProject"
          slot="reference"
          size="small"
          type="primary"
          >新建拓扑图</el-button
        >
      </el-popover>
    </el-header>
    <!-- body部分 -->
    <el-container class="bodys">
      <!-- 左侧树状导航栏部分 -->
      <el-aside class="aside" width="200px">
        <leftAsideTree
          ref="leftAsideTree"
          @changeNode="changeNode"
          @noTree="(noTreeFlag = false), (popVisible = true)"
          @getDataSuc="getTreeSuc"
        ></leftAsideTree>
        <div
          class="recycle"
          :style="!isShowDelete ? 'cursor:not-allowed' : ''"
          @click="showRecycleDialog"
        >
          <img :src="require('@/assets/images/recycle.png')" />
          <span>回收站</span>
        </div>
      </el-aside>
      <!-- 展示部分 -->
      <el-main class="main">
        <div class="main-head" v-if="noTreeFlag">
          <div class="showType" v-show="!selectCard.length">
            <el-radio-group v-model="isPub" size="small" @change="changePub">
              <el-radio-button :label="1">已发布</el-radio-button>
              <el-radio-button :label="0">未发布</el-radio-button>
            </el-radio-group>
            <div class="head-right">
              <el-input
                placeholder="搜索"
                prefix-icon="el-icon-search"
                size="small"
                v-model="queryText"
                @keyup.native.enter="changeQueryText"
                clearable
                @clear="changeQueryText"
              >
              </el-input>
              <Dropdown class="Dropdown" v-model="selVal" :data="dataSelect">
                <span class="drop-text">{{ selText }}</span>
              </Dropdown>
            </div>
          </div>
          <div class="showAction" v-show="selectCard.length">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <span style="margin-left: 10px">|</span>
            <span class="sum"
              >已选择<span style="color: #252b30; margin: 0 5px">{{
                selectCard.length
              }}</span
              >项目</span
            >
            <el-button size="mini" @click="groupMove">移动到</el-button>
            <el-button size="mini" @click="groupDownload" v-if="isPub"
              >下载</el-button
            >
            <el-button size="mini" @click="groupDelete">删除</el-button>
            <i
              class="el-icon-close"
              style="float: right; line-height: 28px; margin-right: 5px"
              @click="handleCheckAllChange(false)"
            ></i>
          </div>
        </div>
        <div class="main-body" v-loading="cardLoading">
          <div class="has-data-body" v-if="noTreeFlag && cardList.length">
            <template v-for="t in cardList">
              <topoImageCard
                :isPub="isPub"
                :data="t"
                :key="t.id"
                @changeCheck="changeCheck"
                @rename="rename"
                @publishSuc="updateSuc"
                @moveTo="moveTo"
                @delete="deleteGraph"
                @editTag="editTag"
                @toEdit="toEdit"
                @download="download"
              ></topoImageCard>
            </template>
          </div>
          <div class="no-data-body" v-else style="margin-top: 112px">
            <img
              src="@/assets/images/no-data.png"
              style="width: 116px; height: 116px"
            />
            <p style="font-size: 16px; margin-top: 15px">暂无数据</p>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 创建弹框 -->
    <createGraphDialog ref="createGraphDialog"></createGraphDialog>
    <!-- 重命名 -->
    <rename ref="rename" :isPub="isPub" @updateSuc="updateSuc"></rename>
    <!-- 移动到 -->
    <move ref="move" :isPub="isPub" @moveSuc="moveSuc"></move>
    <!-- 删除二次确认 -->
    <deleteDialog
      ref="deleteDialog"
      :isPub="isPub"
      @deleteSuc="deleteSuc"
    ></deleteDialog>
    <!-- 修改标签 -->
    <tagDialog
      ref="tagDialog"
      :isPub="isPub"
      @updateSuc="updateSuc"
    ></tagDialog>
    <!-- 回收站全屏弹窗 -->
    <recycle ref="recycle" @recycleDialogClose="recycleDialogClose"></recycle>
  </el-container>
</template>

<script>
import { Select, Dropdown } from "meri-design";
import leftAsideTree from "@/components/homeView/leftAsideTree.vue";
import topoImageCard from "@/components/homeView/topoImageCard.vue";
import { queryDraftsGraph, queryPubGraph } from "@/api/home";
import rename from "@/components/homeView/rename";
import move from "@/components/homeView/move";
import deleteDialog from "@/components/homeView/deleteDialog";
import tagDialog from "@/components/homeView/tagDialog";
import recycle from "@/components/homeView/recycle";
import createGraphDialog from "@/components/homeView/createGraphDialog";
import { SNetUtil } from "@persagy-web/base";
import { mapMutations, mapState, mapActions } from "vuex";
////////////////////////////////
// 常量
// 图服务路径
const imgBaseUrl = window.__systemConf.imgServeUri;
const ProjectData = window.__systemConf.ProjectData;
export default {
  name: "home",
  data() {
    return {
      ProjectData,
      selVal: "lastUpdate", // 排序方式
      selText: "按最后修改", // 排序方式文字
      dataSelect: [
        { id: "lastUpdate", name: "按最后修改" },
        { id: "name", name: "按字母顺序" },
        { id: "createTime", name: "按创建时间" },
      ], // 排序选项
      queryText: "", // 搜索文字
      isPub: 1, // 发布类型()
      cardList: [], // 当前显示的卡片列表
      checkAll: false, // 全选
      selectCard: [], // 当前选中的卡片列表
      isIndeterminate: true, // 全选按钮
      curCategory: {}, // 当前选中的树节点
      noTreeFlag: true, // 左侧树是否有数据-默认有
      popVisible: false,
      categoryName: "", // 跳转编辑页面时分类名称
      cardLoading: false,
      sprojectId: "",
      isShowDelete: true, //是否允许打开回收站
    };
  },
  computed: {
    ...mapState(["projectId"]),
  },
  methods: {
    ...mapMutations(["SETPROJECTID"]),
    ...mapActions(['getAllCategoryType']),
    getProject(data) {
      this.SETPROJECTID(data.id);
      // 判断垃圾箱是否可以点击
      this.getRecycleData();
    },
    // 创建拓扑图
    createProject() {
      this.$refs.createGraphDialog.showDialog();
    },
    // 选项改变
    changeCheck(v) {
      const index = this.selectCard.indexOf(v);
      if (index > -1) {
        this.selectCard.splice(index, 1);
      } else {
        this.selectCard.push(v);
      }
      this.cardList.map(t => {
        t.showCheckFlag = this.selectCard.length > 0;
      })
    },
    // 全选按钮
    handleCheckAllChange(val) {
      this.cardList = this.cardList.map((t) => {
        t.checked = val;
        t.showCheckFlag = val;
        return t;
      });
      this.selectCard = val
        ? this.cardList.map((t) => {
            t.checked = true;
            return t;
          })
        : [];
      this.isIndeterminate = false;
    },
    // 批量移动到
    groupMove() {
      this.$refs.move.showDialog(this.selectCard);
    },
    // 批量下载
    groupDownload() {
      if (this.selectCard.length) {
        this.selectCard.forEach((t) => {
          this.download(t);
        });
      }
    },
    // 单独下载
    download(data) {
      if (data.pic) {
        SNetUtil.downLoad(data.name + ".png", imgBaseUrl + data.pic);
      } else {
        // this.$message.warning(`${data.name}未绘制`)
      }
    },
    // 删除
    groupDelete() {
      // 判断垃圾箱是否可以点击
      this.getRecycleData();
      this.$refs.deleteDialog.showDialog(this.selectCard);
    },
    // 重命名
    rename(data) {
      this.$refs.rename.showDialog(data);
    },
    // 移动到
    moveTo(data) {
      this.$refs.move.showDialog([data]);
    },
    // 单独删除
    deleteGraph(data) {
      // 判断垃圾箱是否可以点击
      this.getRecycleData();
      this.$refs.deleteDialog.showDialog([data]);
    },
    // 更新成功-发布成功
    updateSuc() {
      this.queryGraph();
    },
    // 移动成功
    moveSuc() {
      this.queryGraph();
      this.$refs.leftAsideTree.getCategoryGraph();
    },
    // 删除成功
    deleteSuc() {
      this.$refs.leftAsideTree.getCategoryGraph();
    },
    // 选中节点变化
    changeNode(data) {
      this.noTreeFlag = true
      this.curCategory = data;
      this.categoryName = data.name;
      this.queryGraph();
    },
    // 树数据获取成功
    getTreeSuc() {
      this.noTreeFlag = true;
      this.cardList = [];
      this.queryGraph();
    },
    // 发布修改
    changePub() {
      this.queryGraph();
    },
    // 修改标签
    editTag(data) {
      this.$refs.tagDialog.showDialog(data);
    },
    // 输入内容变化
    changeQueryText() {
      this.queryGraph();
    },
    // 回收站点击
    showRecycleDialog() {
      // 判断回收站是否打开
      if (this.isShowDelete) {
        this.$refs.recycle.showDialog();
      }
    },
    // 回收站关闭
    recycleDialogClose() {
      this.$refs.leftAsideTree.getCategoryGraph();
    },
    // 新建拓扑图成功
    toEdit(data) {
      // 如果跳入草稿则直接跳入、如果调已发布图判断是否是有草稿、有则提示是否要跳入草稿
      if (this.isPub) {
        this.getDraft(data).then((res) => {
          // 是否有对应草稿 如果有出弹窗
          if (res) {
            this.$confirm("该图片已存在最新版草稿，是否选择编辑已有草稿", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
              .then(() => {
                let routeUrl = this.$router.resolve({
                  name: "Editer",
                  query: {
                    graphId: res.graphId,
                    id: res.id,
                    categoryName: encodeURI(this.categoryName),
                    isPub: 0,
                    projectId: this.projectId,
                  },
                });
                window.open(routeUrl.href, "_blank");
              })
              .catch(() => {});
          } else {
            let routeUrl = this.$router.resolve({
              name: "Editer",
              query: {
                graphId: data.graphId,
                id: data.id,
                categoryName: encodeURI(this.categoryName),
                isPub: this.isPub,
                projectId: this.projectId,
              },
            });
            window.open(routeUrl.href, "_blank");
          }
        });
      } else {
        // 进入草稿
        let routeUrl = this.$router.resolve({
          name: "Editer",
          query: {
            graphId: data.graphId,
            id: data.id,
            categoryName: encodeURI(this.categoryName),
            isPub: this.isPub,
            projectId: this.projectId,
          },
        });
        window.open(routeUrl.href, "_blank");
      }
    },
    /////////////////接口
    // 查询图形信息
    queryGraph() {
      if (!this.curCategory.code) {
        return;
      }
      this.cardLoading = true;
      this.selectCard = [];
      const pa = {
        filters: `categoryId="${this.curCategory.code}"`,
        orders: `${this.selVal} desc`,
      };
      if (this.queryText) {
        pa.filters += `;name contain "${this.queryText}"`;
      }
      if (this.isPub) {
        queryPubGraph(pa).then((res) => {
          this.cardList = res.content.map((t) => {
            t.checked = false;
            t.showCheckFlag = false;
            return t;
          });
          this.cardLoading = false;
        });
      } else {
        pa.filters += ";state=1";
        queryDraftsGraph(pa).then((res) => {
          this.cardList = res.content.map((t) => {
            t.checked = false;
            t.showCheckFlag = false;
            return t;
          });
          this.cardLoading = false;
        });
      }
    },
    // 查询是否存在对应的得草稿图
    getDraft(data) {
      if (!this.curCategory.code) {
        return;
      }
      const pa = {
        filters: `categoryId="${this.curCategory.code}"`,
        orders: `${this.selVal} desc`,
      };
      if (this.queryText) {
        pa.filters += `;name contain ""`;
      }
      pa.filters += ";state=1";
      pa.filters += `;id='${data.id}';graphId='${data.graphId}'`;
      const cardList = [];
      return new Promise((resolve, reject) => {
        queryDraftsGraph(pa)
          .then((res) => {
            if (res.content.length) {
              resolve(res.content[0]);
            } else {
              resolve(false);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 请求回收站相关数据
    getRecycleData() {
      const pa = {
        Filters: `state=4`,
      };
      queryDraftsGraph(pa).then((res) => {
        if (res.content && res.content.length) {
          this.isShowDelete = true;
        } else {
          this.isShowDelete = false;
        }
      });
    },
  },
  components: {
    Select,
    leftAsideTree,
    Dropdown,
    topoImageCard,
    rename,
    move,
    deleteDialog,
    recycle,
    tagDialog,
    createGraphDialog,
  },
  watch: {
    // 排序方式修改
    selVal(n, o) {
      if (n === o) return;
      this.selText = this.dataSelect.find((d) => d.id === n).name;
      this.selectCard = [];
      this.queryGraph();
    },
  },
  beforeCreate() {},
  created() {
    // 如果传参获取项目、则项目id为该项目
    const urlData = this.$route.query;
    if (Object.keys(urlData).length == 0) {
      this.sprojectId = this.projectId;
    } else {
      this.ProjectData = [{ id: urlData.projectId, name: urlData.projectName }];
      this.SETPROJECTID(urlData.projectId);
      this.sprojectId = urlData.projectId;
    }

    // 判断垃圾箱是否可以点击
    this.getRecycleData();
    this.getAllCategoryType()
  },
};
</script>
<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
  .header {
    width: 100%;
    height: 60px;
    background: #f7f9fa;
    padding: 0 16px 0 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .bodys {
    width: 100%;
    height: calc(100% - 60px);
    .aside {
      .recycle {
        line-height: 48px;
        border-top: 1px solid #e4e5e7ff;
        box-sizing: border-box;
        background: #f7f9fa;
        padding-left: 16px;
        cursor: pointer;
        img {
          width: 16px;
          height: 16px;
          margin: -3px 8px 0 0;
        }
      }
    }
    .main {
      width: 100%;
      height: 100%;
      background: #fff;
      padding: 5px 20px;
      box-sizing: border-box;
      .main-head {
        position: relative;
        width: 100%;
        height: 46px;
        margin-bottom: 5px;
        .showType {
          width: 100%;
          padding: 7px 0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          /deep/
            .el-radio-button__orig-radio:checked
            + .el-radio-button__inner {
            color: #0091ff;
            border-color: #0091ff;
            background: #e1f2ff;
          }
          .head-right {
            display: flex;
            align-items: center;
            .Dropdown {
              min-width: 100px;
              margin-left: 20px;
              .drop-text {
                font-size: 14px;
                color: #1f2329;
                line-height: 16px;
              }
            }
          }
        }
        .showAction {
          background: #e1f2ff;
          border-radius: 4px;
          border: 1px solid #82c7fc;
          padding: 8px;
          span.sum {
            margin: 0 10px;
            color: #778089;
          }
        }
      }
      .main-body {
        display: block;
        height: calc(100% - 51px);
        overflow: auto;
        & > div {
          display: flex;
          flex-wrap: wrap;
        }
        .no-data-body {
          flex-direction: column;
          // justify-content: center;
          align-items: center;
        }
      }
    }
  }
  .create-dialog {
    .dialog-bodys {
      width: 367px;
      margin: 0 auto;
    }
  }
  .create-dialog-inner {
    .inner-dialog-body {
      width: 100%;
      display: flex;
      .left {
        flex: 1;
        border-right: 1px solid #ccc;
      }
    }
  }
}
</style>
<style lang="less">
.createPopper.el-popover {
  background: #0091ffff;
  color: #fff;
  border-color: #0091ffff;
  .el-button {
    background: #ffffff;
    border-radius: 4px;
    padding: 5px 8px;
  }
  .popper__arrow::after {
    border-bottom-color: #0091ffff;
  }
}
</style>
