<template>
  <div id="treedom4" v-loading="loading">
    <div style="position: relative">
      <div class="nav" id="topLine">
        <div
          class="nav-cont"
          v-for="(item, index) in navList"
          :key="index"
          @click="clickNav(item)"
        >
          <img :src="cylinder" alt="" class="nav-img" />
          <div>{{ item.attr_name }}</div>
          <div class="describe-text">{{ `(${item.attr_desc})` }}</div>
        </div>
      </div>
    </div>
    <div class="wrapper">
      <div class="grid">
        <!-- 左侧 -->
        <div
          class="col fluid"
          :class="{ transp: mainTitle && mainTitle.length < 2 }"
          style="margin-left: 20px"
          id="leftLine"
        >
          <div v-if="mainTitle && mainTitle.length > 1">
            <div class="title">
              {{ mainTitle[1].attr_name
              }}<span v-if="mainTitle[0].attr_desc">{{
                `(${mainTitle[1].attr_desc})`
              }}</span>
            </div>
            <div class="attr-desc" v-if="moLeft">
              <div>
                <span class="decrip">MAC-Address:</span>
                <span class="decrip-item" v-if="!moLeft.address">无</span>
                <span v-else>{{ moLeft.address }}</span>
              </div>
              <div>
                <span class="decrip">VLAN-PRIORITY:</span>
                <span class="decrip-item" v-if="!moLeft.priority">无</span>
                <span v-else>{{ moLeft.priority }}</span>
              </div>
              <div>
                <span class="decrip">APPID:</span>
                <span class="decrip-item" v-if="!moLeft.APPID">无</span>
                <span v-else>{{ moLeft.APPID }}</span>
              </div>
              <div>
                <span class="decrip">VLAN-ID:</span>
                <span class="decrip-item" v-if="!moLeft.vlanId">无</span>
                <span v-else>{{ moLeft.vlanId }}</span>
              </div>
            </div>
            <div v-if="mainList" class="circle-all">
              <span
                v-for="(item, index) in mainTitle[1].list"
                :key="index"
                class="circel"
                :class="{ 'circel active-circel': index == activeCircel }"
                @click="clickCircel(item, index, 'moLeft')"
                ><span v-if="item.address_json != ''">{{
                  index + 1
                }}</span></span
              >
            </div>
          </div>
          <div class="child-item" v-if="mainTitle && mainTitle.length > 1">
            <div class="ldevice">LDevice</div>
            <div
              v-for="(item, index) in mainTitle[1].childList[0]"
              :key="index"
              @click="clickMain(item)"
              class="ldevice-cont"
            >
              <img :src="legislation" alt="" />
              <div class="img-title">{{ item.attr_inst }}</div>
              <div class="decrip-child">{{ item.attr_desc }}</div>
            </div>
          </div>
        </div>
        <!-- 中间 -->
        <div class="col main-middle" id="middleLine">
          <div v-if="attrsData">
            <el-tooltip
              class="box-item"
              effect="light"
              :content="attrsData.desc"
              placement="top-start"
            >
              <div class="text-overflow ied_struct_desc">
                {{ attrsData.desc }}
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="light"
              :content="attrsData.type"
              placement="top-start"
            >
              <div class="text-overflow ied_struct_type">
                {{ attrsData.type }}
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="light"
              :content="attrsData.manufacturer"
              placement="top-start"
            >
              <div class="text-overflow ied_struct_manufacturer">
                {{ attrsData.manufacturer }}
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="light"
              :content="attrsData.name"
              placement="top-start"
            >
              <div
                class="text-overflow ied_struct_manufacturer ied_struct_manufacturer1"
              >
                {{ attrsData.name }}
              </div>
            </el-tooltip>
          </div>
        </div>
        <!-- 右侧 -->
        <div
          class="col fluid"
          style="margin-right: 20px"
          :class="{ transp: mainTitle && mainTitle.length < 3 }"
          id="rightLine"
        >
          <div v-if="mainTitle && mainTitle.length > 2">
            <div class="title">
              {{ mainTitle[2].attr_name
              }}<span v-if="mainTitle[0].attr_desc">{{
                `(${mainTitle[2].attr_desc})`
              }}</span>
            </div>
            <div class="attr-desc" v-if="moRight">
              <div>
                <span class="decrip">MAC-Address:</span>
                <span class="decrip-item" v-if="!moRight.address">无</span>
                <span v-else>{{ moRight.address }}</span>
              </div>
              <div>
                <span class="decrip">VLAN-PRIORITY:</span>
                <span class="decrip-item" v-if="!moRight.priority">无</span>
                <span v-else>{{ moRight.priority }}</span>
              </div>
              <div>
                <span class="decrip">APPID:</span>
                <span class="decrip-item" v-if="!moRight.APPID">无</span>
                <span v-else>{{ moRight.APPID }}</span>
              </div>
              <div>
                <span class="decrip">VLAN-ID:</span>
                <span class="decrip-item" v-if="!moRight.vlanId">无</span>
                <span v-else>{{ moRight.vlanId }}</span>
              </div>
            </div>
            <div v-if="mainList" class="circle-all">
              <span
                v-for="(item, index) in mainTitle[2].list"
                :key="index"
                class="circel"
                :class="{ 'circel active-circel': index == activeCircel }"
                @click="clickCircel(item, index, 'moRight')"
                ><span v-if="item.address_json != ''">{{
                  index + 1
                }}</span></span
              >
            </div>
          </div>
          <div class="child-item" v-if="mainTitle && mainTitle.length > 2">
            <div class="ldevice">LDevice</div>
            <div
              v-for="(item, index) in mainTitle[2].childList[0]"
              :key="index"
              @click="clickMain(item)"
              class="ldevice-cont"
            >
              <img :src="legislation" alt="" />
              <div class="img-title">{{ item.attr_inst }}</div>
              <div class="decrip-child">{{ item.attr_desc }}</div>
            </div>
          </div>
        </div>
      </div>
      <div
        class="main-bottom"
        id="bottomLine"
        :class="{ transp: mainTitle && mainTitle.length < 1 }"
      >
        <div v-if="mainTitle && mainTitle.length > 0">
          <div class="title">
            {{ mainTitle[0].attr_name
            }}<span v-if="mainTitle[0].attr_desc">{{
              `(${mainTitle[0].attr_desc})`
            }}</span>
          </div>
          <div class="attr-desc" v-if="moBottom">
            <div>
              <span class="decrip">MAC-Address:</span>
              <span class="decrip-item" v-if="!moBottom.address">无</span>
              <span v-else>{{ moBottom.address }}</span>
            </div>
            <div>
              <span class="decrip">VLAN-PRIORITY:</span>
              <span class="decrip-item" v-if="!moBottom.priority">无</span>
              <span v-else>{{ moBottom.priority }}</span>
            </div>
            <div>
              <span class="decrip">APPID:</span>
              <span class="decrip-item" v-if="!moBottom.APPID">无</span>
              <span v-else>{{ moBottom.APPID }}</span>
            </div>
            <div>
              <span class="decrip">VLAN-ID:</span>
              <span class="decrip-item" v-if="!moBottom.vlanId">无</span>
              <span v-else>{{ moBottom.vlanId }}</span>
            </div>
          </div>
          <div v-if="mainList" class="circle-all">
            <span
              v-for="(item, index) in mainTitle[0].list"
              :key="index"
              class="circel"
              :class="{ 'circel active-circel': index == activeCircel }"
              @click="clickCircel(item, index, 'moBottom')"
              ><span v-if="item.address_json != ''">{{ index + 1 }}</span></span
            >
          </div>
        </div>
        <div class="child-item" v-if="mainTitle && mainTitle.length > 0">
          <div class="ldevice">LDevice</div>
          <div
            class="ldevice-cont"
            v-for="(item, index) in mainTitle[0].childList[0]"
            :key="index"
            @click="clickMain(item)"
          >
            <img :src="legislation" alt="" />
            <div class="img-title">{{ item.attr_inst }}</div>
            <div class="decrip-child">{{ item.attr_desc }}</div>
          </div>
        </div>
      </div>
    </div>
    <div id="wrappers"></div>
    <!-- 点击头部的弹框 -->
    <el-dialog
      @close="cancelClickNav"
      v-model="isOpennav"
      append-to-body
      draggable
      style="height: 550px"
    >
      <template #header>
        <div class="my-header">
          <div class="dialog-nav-title">
            {{ `(${clickNavTitle.attr_desc}) — FCDA列表` }}
          </div>
        </div>
      </template>
      <el-table
        :data="clickNavData"
        style="width: 100%"
        stripe
        height="450"
        :cell-style="{ color: '#000' }"
      >
        <el-table-column prop="attr_ld_inst" label="ldInst" />
        <el-table-column prop="attr_prefix" label="prefix" />
        <el-table-column prop="attr_ln_class" label="lnClass" />
        <el-table-column prop="attr_ln_inst" label="lnInst" />
        <el-table-column prop="attr_do_name" label="doName" />
        <el-table-column prop="da_datatype" label="attr_da_name" width="180" />
        <el-table-column prop="attr_fc" label="fc" />
      </el-table>
    </el-dialog>
    <!-- 点击方框的弹窗 -->
    <el-dialog
      @close="cancelClickMain"
      v-model="isOpenMain"
      append-to-body
      draggable
      style="height: 550px"
    >
      <template #header>
        <div class="my-header">
          <div class="dialog-nav-title">
            {{
              `${clickMainTitle.attr_inst}${clickMainTitle.attr_desc} — LN/LN0节点列表`
            }}
          </div>
        </div>
      </template>
      <el-table
        :data="clickMainData"
        style="width: 100%"
        stripe
        height="450"
        :cell-style="{ color: '#000' }"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attr_inst" label="inst" />
        <el-table-column prop="attr_ln_class" label="lnClass" />
        <el-table-column prop="attr_ln_type" label="lnType" />
        <el-table-column prop="attr_desc" label="desc" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineProps, onMounted, ref, inject, nextTick, watch } from "vue";
import legislation from "@/assets/image/instruct/legislation.png";
import cylinder from "@/assets/image/instruct/cylinder.png";
import {
  getNodeList,
  getNetworkInfo,
  getLdeviceList,
  nodeList,
  getNodeAttrs,
} from "@/api/iedNetwork";
import LeaderLine from "../../../../public/leader-line.min.js";
import AnimEvent from "../../../../public/anim-event.min.js";
import { CloseBold } from "@element-plus/icons-vue";
const props = defineProps({
  checkData: {
    type: Object,
    default: () => {},
  },
  isOpen: {
    type: Boolean,
    default: false,
  },
});
const scdIdValue = inject("scdId");
const navList = ref(null); //最头部的数据
const mainTitle = ref(null); //每个方框的标题
const moBottom = ref(null); //底部方框所展示的MAC-Address等desc
const moLeft = ref(null); //左侧方框所展示的MAC-Address等desc
const moRight = ref(null); //右侧方框所展示的MAC-Address等desc
const activeCircel = ref(0); //点击数字圆圈的样式
const isOpennav = ref(false); //头部点击弹窗显示
const clickNavTitle = ref(null); //头部点击弹窗数据
const clickNavData = ref(null); //头部点击弹窗数据
const isOpenMain = ref(false); //点击方框
const clickMainTitle = ref(null);
const clickMainData = ref(null);
const loading = ref(true);
const getNav = async () => {
  const navRes = await getNodeList({
    scd_id: scdIdValue,
    pagesize: 10000,
    ied_name: props.checkData.ied_name,
    name: "DataSet",
  });
  navList.value = navRes.data;
};
const getMainTitle = async () => {
  const mainRes = await getNodeList({
    scd_id: scdIdValue,
    pagesize: 10000,
    ied_name: props.checkData.ied_name,
    name: "AccessPoint",
  });
  //得到每个方框中LDevice中的内容
  Promise.all(
    mainRes.data.map(async (item) => {
      item.childList = [];
      const res = await getLdeviceList({
        accessPointId: item.node_id,
        scd_id: scdIdValue,
      });
      item.childList.push(res.data);
    })
  ).then(() => {
    //等待执行完上面的api
    loading.value = false;
    mainTitle.value = mainRes.data;
    getMainList();
  });
};
const mainList = ref({});
const titleName = ref([]);
//几个方框的数据
const getMainList = async () => {
  mainList.value = {};
  titleName.value = [];
  const newarr = [];
  const infoRes = await getNetworkInfo({
    scd_id: scdIdValue,
    ied_name: props.checkData.ied_name,
  });

  //处理分类数据
  for (let i = 0; i < infoRes.data.length; i++) {
    if (infoRes.data[i].address_json != "") {
      let newData = infoRes.data[i].address_json
        .replace("MAC-Address", "address")
        .replace("VLAN-PRIORITY", "priority")
        .replace("VLAN-ID", "vlanId");
      infoRes.data[i].address_json = JSON.parse(newData);
    }
    let item = infoRes.data[i];
    const key = item.ap_name;
    newarr.push(key);
    if (mainList.value[key] == null) {
      mainList.value[key] = {
        name: key,
        list: [item],
      };
    } else {
      mainList.value[key].list.push(item);
    }
  }
  //处理表头下方段落的描述
  if (mainList.value && mainTitle.value) {
    mainTitle.value.forEach((key) => {
      key.list = [];
      Object.keys(mainList.value).forEach((item) => {
        if (item == key.attr_name) {
          key.list = mainList.value[item].list;
        }
      });
    });
    //分布默认的左侧右侧和下侧的数据
    for (let i = 0; i < mainTitle.value.length; i++) {
      if (
        mainTitle.value[i].list.length > 0 &&
        mainTitle.value[i].list[0].address_json != ""
      ) {
        const targetElement = mainTitle.value[i];
        switch (i) {
          case 0:
            moBottom.value = targetElement.list[0].address_json;
            break;
          case 1:
            moLeft.value = targetElement.list[0].address_json;
            break;
          case 2:
            moRight.value = targetElement.list[0].address_json;
            break;
        }
      }
    }
  }
};
//弹窗打开后使得线条在指定区域中
const hiddenLine2 = () => {
  const elmWrapper = document.getElementById("wrappers");
  // 移动 line
  document.body.querySelectorAll("body .leader-line").forEach((node) => {
    elmWrapper.appendChild(node);
  });
  elmWrapper.style.transform = "none";
  var rectWrapper = elmWrapper.getBoundingClientRect();
  elmWrapper.style.transform = `translate(${
    (rectWrapper.left + window.scrollY) * -1
  }px, ${(rectWrapper.top + window.scrollX) * -1}px)`;
};
const leaderLines = ref([]); //控制线条显示
//滚动时重定位线条
const newPositionLine2 = () => {
  document.getElementById("treedom4").addEventListener(
    "scroll",
    AnimEvent.add(() => {
      leaderLines.value.forEach((line) => {
        if (line) {
          hiddenLine2();
          line.position();
          line.positionByWindowResize = false;
        }
      });
      //中间展示图片的
    }),
    false
  );
};
const getLine = () => {
  const topDom = document.getElementById("topLine");
  const leftDom = document.getElementById("leftLine");
  const rightDom = document.getElementById("rightLine");
  const bottomDom = document.getElementById("bottomLine");
  const middlDom = document.getElementById("middleLine");
  let lineStyle = {
    color: "#134BEA",
    size: 2,
    path: "straight",
    endPlug: "disc",
    startPlug: "disc",
    middleLabel: LeaderLine.captionLabel("AccessPoint", {
      fontSize: 10,
      color: "#7F8EB2",
    }),
  };
  let lineStyleTop = {
    ...lineStyle,
    middleLabel: LeaderLine.captionLabel({
      text: "DataSet",
      fontSize: 10,
      color: "#7F8EB2",
    }),
  };
  let lineStyleright = {
    ...lineStyle,
    middleLabel: LeaderLine.captionLabel("AccessPoint", {
      fontSize: 10,
      color: "#7F8EB2",
    }),
  };
  let lineStylebottom = {
    ...lineStyle,
    middleLabel: LeaderLine.captionLabel({
      text: "AccessPoint",
      fontSize: 10,
      color: "#7F8EB2",
    }),
  };
  leaderLines.value.push(new LeaderLine(middlDom, topDom, lineStyleTop)); //上面和中间连线
  if (mainTitle.value && mainTitle.value.length > 0) {
    leaderLines.value.push(
      new LeaderLine(middlDom, bottomDom, lineStylebottom)
    );
  }
  if (mainTitle.value && mainTitle.value.length > 2) {
    leaderLines.value.push(new LeaderLine(middlDom, rightDom, lineStyleright));
  }
  if (mainTitle.value && mainTitle.value.length > 1) {
    leaderLines.value.push(new LeaderLine(leftDom, middlDom, lineStyle));
  }
  newPositionLine2();
  hiddenLine2();
};
//点击数字
const clickCircel = (item, index, type) => {
  activeCircel.value = index;
  let data = JSON.stringify(item.address_json);
  let newData = data
    .replace("MAC-Address", "address")
    .replace("VLAN-PRIORITY", "priority")
    .replace("VLAN-ID", "vlanId");
  if (type == "moBottom") {
    moBottom.value = JSON.parse(newData);
  } else if (type == "moRight") {
    moRight.value = JSON.parse(newData);
  } else {
    moLeft.value = JSON.parse(newData);
  }
};
const attrsData = ref(null);
const getNode = async () => {
  const attrRes = await getNodeAttrs({
    scd_id: scdIdValue,
    ied_name: props.checkData.ied_name,
    node_id: props.checkData.node_id,
  });
  attrsData.value = attrRes.data;
};
onMounted(() => {
  getNav();
  getMainTitle();
  getNode();
  nextTick(() => {
    setTimeout(() => {
      getLine();
    }, 500);
  });
});
watch(
  () => props.isOpen,
  (newValue) => {
    nextTick(() => {
      if (!newValue) {
        removeLine2();
        leaderLines.value = [];
        loading.value = false;
      } else {
        setTimeout(() => {
          getLine();
        }, 500);
      }
    });
  }
);
watch(
  () => props.checkData,
  (newValue) => {
    removeLine2();
    if (newValue && leaderLines.value.length > 0) {
      leaderLines.value = [];
    }
    if (newValue) {
      activeCircel.value = 0;
      isOpenMain.value = false;
      isOpennav.value = false;
      getNav();
      loading.value = true;
      getMainTitle();
      getNode();
      nextTick(() => {
        setTimeout(() => {
          getLine();
        }, 500);
      });
    }
  }
);
const removeLine2 = () => {
  const elmWrapper = document.getElementById("wrappers");
  document.body.querySelectorAll("body .leader-line").forEach((node) => {
    elmWrapper.removeChild(node);
  });
};
//点击头部展示的弹框
const clickNav = async (item) => {
  clickNavTitle.value = item;
  isOpennav.value = true;
  const navRes = await nodeList({
    scd_id: scdIdValue,
    parent_node_id: item.node_id,
    pagesize: 10000,
    name: "FCDA",
  });
  clickNavData.value = navRes.data;
};
const cancelClickNav = () => {
  clickNavData.value = null;
  isOpennav.value = false;
};
const clickMain = async (item) => {
  clickMainTitle.value = item;
  isOpenMain.value = true;
  const navRes = await nodeList({
    scd_id: scdIdValue,
    parent_node_id: item.node_id,
    pagesize: 10000,
    name: "LN0",
  });
  const navRes2 = await nodeList({
    scd_id: scdIdValue,
    parent_node_id: item.node_id,
    pagesize: 10000,
    name: "LN",
  });
  clickMainData.value = [...navRes.data, ...navRes2.data];
};
const cancelClickMain = () => {
  clickMainData.value = null;
  isOpenMain.value = false;
};
</script>

<style scoped lang="scss">
#treedom4 {
  height: 72vh;
  overflow-y: auto;
}
.wrapper {
  position: relative;
}
.nav {
  height: 160px;
  background: #f3f5fa;
  overflow-y: auto;
  border: 2px dashed #a3ade0;
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
  position: relative;
  margin: 16px;
  .nav-img {
    width: 30px;
    height: 30px;
  }
  .nav-cont {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    margin: 8px 0;
    flex-basis: 14%;
    .describe-text {
      color: #134bea;
    }
  }
}
.main-bottom,
.fluid {
  border: 2px dashed #a3ade0;
  background-color: #f7f8f8;
  display: flex;
  flex-direction: column;
  max-width: 36%;
  img {
    width: 40px;
    height: 40px;
  }
  .title {
    font-size: 16px;
    font-weight: bold;
    margin: 12px 0;
    text-align: center;
  }
  .attr-desc {
    margin: 10px;
  }
  .decrip {
    color: #7484ab;
    font-size: 14px;
    margin-right: 15px;
    width: 130px;
    display: inline-block;
  }
  .decrip-child {
    color: #7484ab;
    font-size: 14px;
  }
  .decrip-item {
    font-weight: bold;
    font-size: 14px;
  }
  .child-item {
    display: flex;
    margin: 12px;
    flex-wrap: wrap;
    border: 1px solid #5182ff;
    position: relative;
    & > div {
      margin: 8px;
    }
    .ldevice {
      position: absolute;
      top: -20px;
      left: -10px;
      padding: 0 4px;
      background: #5182ff;
      color: white;
      border-radius: 10px;
    }
    .ldevice-cont {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .img-title {
    color: #134bea;
  }
}
.circle-all {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
}
.circel {
  color: #7c58a8;
  width: 20px;
  height: 20px;
  margin-bottom: 5px;
  margin-right: 5px;
  border: 1px solid #606c93;
  border-radius: 10px;
  text-align: center;
  line-height: 20px;
  margin-left: 0.5rem;
  cursor: pointer;
}
.active-circel {
  color: #134bea;
  border: 1px solid #134bea;
}
.Image {
  width: 193px;
  height: 150px;
}
/* 设置网格布局相关的样式 */
.grid {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  margin-top: 50px;
}

.grid > .col {
  box-sizing: border-box;
  // padding: 10px;
}

/* 设置fixed2样式 */
.main-middle {
  width: 160px;
  height: 160px;
  background: #fff url("~@/assets/image/instruct/network_slices.png") no-repeat
    center;
  background-size: 160px;
  position: relative;
  font-size: 12px;
  .text-overflow {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
    cursor: pointer;
  }
  .ied_struct_manufacturer {
    line-height: 2rem;
    transform: rotate(-33deg);
    top: 65%;
    position: absolute;
    left: 62%;
    border: 0px solid #cccccc1c;
    font-style: italic;
    font-size: 1rem;
    width: 6rem;
    text-align: center;
  }
  .ied_struct_manufacturer1 {
    top: 54%;
    left: 59%;
  }
  .ied_struct_desc {
    line-height: 2rem;
    position: absolute;
    transform: rotate(31deg);
    top: 15%;
    left: 32%;
    width: 59%;
    word-break: break-word;
    color: #134bea;
    font-weight: bold;
    font-style: italic;
    text-align: center;
  }
  .ied_struct_type {
    position: absolute;
    transform: rotate(31deg);
    top: 26%;
    left: 17%;
    color: #15010152;
    font-size: 1rem;
    font-style: italic;
    width: 60%;
    line-height: 1.5rem;
    text-align: center;
  }
}

/* 设置fluid样式 */
.fluid {
  flex-grow: 1;
}
.transp {
  border: none;
}
.main-bottom {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 40px;
}
.dialog-nav-title {
  color: #09162c;
  font-size: 16px;
}
</style>