<template>
  <div>
    <div class="bigBox" :class="{ bigBoxUp: isUPdate == 'update' }">
      <div>
        <div class="titles">
          <img
            style="width: 20px; height: 20px"
            src="../../../assets/icon/HardDrives.png"
            alt=""
          />
          <div>装置列表</div>
        </div>
      </div>
      <div class="tagBox">
        <div
          class="cont-line tagP"
          :class="{ clicktag: tagChoose == index }"
          v-for="(item, index) in tagList"
          :key="index"
          @click="tagClick(item, index)"
        >
          <span v-if="!OpensclTrue">{{
            `(${item.ied_name})${item.desc}`
          }}</span>
          <span v-else>{{ `(${item.ied_name})${item.ied_desc}` }}</span>
        </div>
      </div>
      <div class="setting">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="label" :class="{ 'tree-label': node.expanded }">{{
              node.label
            }}</span
            ><span
              :class="{ 'tree-label': clickItemcode == data.itemcode }"
              style="position: absolute; right: 10px"
              ><span v-if="OpensclTrue">{{ data.num }}</span
              ><span v-else>{{ data.num }}</span></span
            >
          </template>
        </el-tree>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, toRefs, watch } from "vue";
import cid from "@/api/cid/cid";
import scdCheck from "@/api/scdCheck/scdCheck";
import { compIedstatType } from "@/api/scdCheck/scdCheck2";
import { useRoute } from "vue-router";
const route = useRoute();
const props = defineProps({
  OpensclTrue: {
    type: Boolean,
    default: false,
  },
  iedRelation: {
    type: Object,
    default: () => {},
  },
  UPdate: {
    //判断是否是点击更改 进入的界面
    type: String,
    default: "",
  },
  clickRowDatas: {
    type: Object,
    default: () => {},
  },
  allCidStart: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["treeBack", "clickCode", "treeBackDefalut"]);
let tagList = ref(props.iedRelation);
const loading = ref(true);
let tagChoose = ref("");
let treeData = ref([
  {
    label: "装置信息",
    itemcode: "ied",
    num: 0,
    children: [
      {
        label: "基本信息",
        itemcode: "scd.ied",
        num: 0,
      },
    ],
  },
  {
    label: "通信参数",
    itemcode: "Communication",
    num: 0,
    children: [
      {
        label: "通信接入点",
        itemcode: "scd.ied.Communication",
        num: 0,
      },
      {
        label: "站控层通信参数",
        itemcode: "scd.ied.Communication.S1",
        num: 0,
      },
      {
        label: "GOOSE 通信参数",
        itemcode: "scd.ied.Communication.GSE",
        num: 0,
      },
      { label: "SV 通信参数", itemcode: "scd.ied.Communication.SMV", num: 0 },
    ],
  },
  {
    label: "测点信息",
    itemcode: "Point",
    num: 0,
    children: [
      {
        label: "遥信",
        itemcode: "scd.ied.YX",
        num: 0,
      },
      {
        label: "遥控",
        itemcode: "scd.ied.YK",
        num: 0,
      },
      {
        label: "遥测",
        itemcode: "scd.ied.YC",
        num: 0,
      },
      {
        label: "遥脉",
        num: 0,
        itemcode: "scd.ied.YM",
      },
      {
        label: "定值",
        itemcode: "scd.ied.DZ",
        num: 0,
      },
    ],
  },
  {
    label: "回路配置",
    itemcode: "config",
    num: 0,
    children: [
      {
        label: "发布虚端子",
        itemcode: "scd.ied.FCDA",
        num: 0,
      },
      {
        label: "定阅虚端子",
        itemcode: "scd.ied.ExtRef",
        num: 0,
      },
      {
        label: "虚回路信息",
        itemcode: "scd.ied.Relation",
        num: 0,
      },
    ],
  },
  {
    label: "建模信息",
    itemcode: "model",
    num: 0,
    children: [
      {
        label: "数据集",
        itemcode: "scd.ied.DatSet",
        num: 0,
      },
      {
        label: "数据集成员",
        itemcode: "scd.ied.DatSetMeber",
        num: 0,
      },
      {
        label: "GOOSE控制块",
        itemcode: "scd.ied.GSEControl",
        num: 0,
      },
      {
        label: "SV控制块",
        itemcode: "scd.ied.SampledValueControl",
        num: 0,
      },
      {
        label: "报告控制块",
        itemcode: "scd.ied.ReportControl",
        num: 0,
      },
      {
        label: "日志控制块",
        itemcode: "scd.ied.LogControl",
        num: 0,
      },
    ],
  },
]);

let needName = ref("");
//得到差异项code的数字数据
const codeStatic = async () => {
  const ids = clickRow.value ? clickRow.value.id : "";
  const names = clickTage.value ? clickTage.value.ied_name : "";
  const res = await compIedstatType({
    comp_id: ids,
    ied_name: names,
    comptype: "u",
  });
  updateNum(treeData.value, res.data);
};
const updateNum = (treeNode, data) => {
  for (let node of treeNode) {
    node.num = 0;
    // 检查当前节点的 itemcode 是否在 data 中
    if (data && data.hasOwnProperty(node.itemcode)) {
      node.num = parseInt(data[node.itemcode]);
    }
    if (data && node.itemcode == "scd.ied.Relation"&&data["scd.ied.ExtRef"]) {
      node.num = parseInt(data["scd.ied.ExtRef"]);
    }
    // 如果当前节点有子节点，递归处理子节点
    if (node.children) {
      updateNum(node.children, data);
      // 计算父级节点的num是子节点num的和
      node.num = node.children
        .filter((child) => child.itemcode !== "scd.ied.Relation")
        .reduce((total, child) => total + child.num, 0);
    }
  }
  loading.value = false
};
let defaultProps = ref({
  label: "label",
  children: "children",
  num: "num",
});
const isUPdate = ref(props.UPdate);
watch(
  () => props.UPdate,
  (newValue) => {
    isUPdate.value = newValue;
  }
);
watch(
  () => props.iedRelation, //点击SCD文件一致性校核，点击查看，点击修改进如的装置列表
  (newValue) => {
    if (newValue) {
      tagList.value = newValue;
    }
  }
);
const allCidStartProps = ref(null);
watch(
  //CID一致性校验左侧的数据处理
  () => props.allCidStart,
  (newValue) => {
    if (newValue && newValue.length) {
      allCidStartProps.value = newValue;
      treeData.value.forEach((node) => {
        addChildItems(node, newValue);
      });
    }
  }
);

//Cid使用递归
const addChildItems = (node, data) => {
  if (!node.childItemCid) {
    node.childItemCid = [];
  }
  data.forEach((item) => {
    if (node.itemcode === item.diff_object_type) {
      let text;
      text = item.diff_desc.replace(/[\r|\n|\t]/g, ""); //处理返回的数据中换行等，整理好规整数据
      item.diff_desc = JSON.parse(text);
      node.childItemCid.push(item);
    }
  });
  if (node.children) {
    node.children.forEach((childNode) => {
      addChildItems(childNode, data);
    });
    // 计算并设置 num 值
    let childrenNum = 0;
    node.children.forEach((childNode) => {
      childrenNum += childNode.childItemCid.length;
    });
    node.num = childrenNum;
  } else {
    node.num = node.childItemCid.length;
  }
};
const reload = () => {
  if (!props.OpensclTrue) {
    //网络结构体点击CID一致性校核打开获取的装置列表
    cid.getAll({ scd_id: route.query.id, ied_name: "" }).then((res) => {
      tagList.value = res.data;
      tagChoose.value = res.data ? Object.keys(res.data)[0] : "";
      clickTage.value = res.data ? Object.values(res.data)[0] : "";
      emit("treeBack", clickTage.value)
    });
  }
};
const clickTage = ref(null);
const tagClick = (row, num) => {
  loading.value = true;
  treeData.value.forEach(item=>{
    item.num = 0;
    item.childItemCid = [];
    if(item.children){
      item.children.forEach(key=>{
        key.num=0;
        key.childItemCid = [];
      })
    }
  })
  tagChoose.value = num;
  clickTage.value = row;
  // cid
  //   .findFile({
  //     scd_id: route.query.id,
  //     ied_name: row.desc,
  //     pageno: 1,
  //     pagesize: 10,
  //     station_id: route.query.stationId,
  //   })
  //   .then((res) => {});
  // scdCheck
  //   .lookCheck({
  //     pageindex: 1,
  //     pagesize: 10,
  //     station_id: route.query.stationId,
  //     scd_id: route.query.id,
  //     is_checkin: 2,
  //     ied_name: row.ied_name,
  //   })
  //   .then((res) => {
  //     let fileInfo;
  //     if (res.data) {
  //       fileInfo = res.data.filter((item) => item.scd_id == route.query.id);
  //       if (fileInfo.length > 0) {
  //         emit("treeBack", row, fileInfo[0]);
  //       }
  //     }
      //   let a = res.data.filter((item) => item.type_name == "CID");
      //   if (a.length > 0) {
      //     needName.value = a[0].file_name;
      //     emit("treeBack", needName.value, a[0].id);
      //   }
    // });
  if (props.OpensclTrue) {
    codeStatic();
  }
};
const clickRow = ref(props.clickRowDatas);
//对比文件：头部对比的单个数据
watch(
  () => props.clickRowDatas,
  (newValue) => {
    if (newValue) {
      clickRow.value = newValue;
    }
  }
);
const clickItemcode = ref("");
const handleNodeClick = (e) => {
  clickItemcode.value = e.itemcode;
  emit("clickCode", e.itemcode, e);
};
onMounted(() => {
  tagChoose.value = props.iedRelation ? Object.keys(props.iedRelation)[0] : "";
  clickTage.value = props.iedRelation
    ? Object.values(props.iedRelation)[0]
    : "";
  emit("treeBackDefalut", clickTage.value);
  reload();
  if (props.OpensclTrue) {
    codeStatic();
  }
});
</script>

<style scoped lang="scss">
p,
h3 {
  margin: 0;
  padding: 0;
}

.bigBox {
  width: 100%;
  height: calc(100vh - 280px);
  margin-top: 20px;
  border: 1px solid #a3ade0;
  border-radius: 2px;
  cursor: pointer;
  background: #f7f8fb;
  & > div:first-child {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #1a2447;
    margin: 16px 0 0 16px;
  }
}
.bigBoxUp {
  height: calc(100vh - 230px) !important;
}
:deep(.el-tree) {
  --el-fill-color-blank: #f7f8fb;
}
.tagBox {
  width: 92%;
  height: 45%;
  overflow-y: auto;
  margin: 8px 16px 0px 16px;
}

.tagP {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 8px;
  font-size: 16px;
}
.setting {
  width: 92%;
  height: 45%;
  overflow-y: auto;
  border-top: 1px solid #a3ade0;
  margin: 2px auto;
  .label {
    padding: 5px 8px;
  }
  :deep(.el-tree--highlight-current .el-tree-node) {
    margin: 5px 0;
    color: #1a2447;
  }
  :deep(
      .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content
    ) {
    background: transparent;
  }
  :deep(
      .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content
        .label
    ) {
    color: #134bea;
    border: 1px solid #255ce7;
    background: #f6f9ff;
  }
}
.titles {
  display: flex;
  align-items: center;
  & > div {
    font-size: 16px;
    margin-left: 8px;
    vertical-align: middle;
    font-weight: bold;
  }
}
.cont-line,
:deep(.el-tree-node__label) {
  color: #1a2447;
  font-size: 14px;
}
.clicktag {
  color: #255ce7;
}
.tree-label {
  color: #134bea;
}
</style>