<template>
  <div
    class="dataAnalysisAngleAna"
    :class="!theme ? 'themeDark' : 'themeLight'"
  >
    <div class="dataAnalysisAngleAnaMain">
      <div class="main_top">
        <p class="topPsty">浆距角分析</p>
      </div>
      <div class="main">
        <div class="treeDataMain">
          <tree-cop
            :data="treeData"
            :height="treeHeight"
            :currentNodeKey="currentNodeKey"
            @currentChange="funCurrentChange"
            @refresh="funGetTree"
          >
          </tree-cop>
        </div>
        <div class="excelDataMain">
          <excel-cop
            :data="excelList"
            :height="excelHeight"
            :theme="theme"
            @excelChange="funExcelChange"
          >
          </excel-cop>
        </div>
        <div class="tableDataMain">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="图表展示" name="1"> </el-tab-pane>
            <el-tab-pane label="桨距角风速曲线" name="2" v-if="false">
            </el-tab-pane>
            <el-tab-pane label="表格数据" name="3"> </el-tab-pane>
            <el-tab-pane
              :label="`异常测点 (${abnormalPoint.length}个)`"
              name="4"
            >
            </el-tab-pane>
            <div v-if="activeTab === '3'" :style="{ height: tableHeight }">
              <table-cop
                class=""
                :data="tableData"
                :column="tableColumn"
                :theme="theme"
                :height="tableHeight"
                :tableId="tableShowId"
                :tableName="tableName"
                :rowstyle="true"
              ></table-cop>
            </div>
            <div v-show="activeTab === '1'" :style="{ height: tableHeight }">
              <!-- :height="`calc( ${tableHeight})`" -->
              <p :style="!theme ? 'color: #fff' : 'color: #000'" style="width: 100%;text-align: center">变桨角度偏差率:{{angleData*100}}%</p>
              <CurrentScatterChart
                ref="chartRef"
                width="100%"
                height="75vh"
                :chartTitle="''"
                style="margin-top: 3vh"
                :xAxisData="xAxisData"
                :yAxisData="{ splitLine: { show: false } }"
                :seriesData="seriesData"
                :seriesAllData="seriesAllData"
                :showLegend="true"
                :brushSelected="false"
                :dataSet="dataSet"
                :theme="theme"
                :echartsTheme="echartsTheme"
                @getSelected="funChartSelect"
              />
            </div>
            <div
              v-if="false && activeTab === '2'"
              :style="{ height: tableHeight }"
            >
              <!-- <div id="speedLine" style="width:100%;height:100%"></div> -->
              <bar-chart-cop
                width="100%"
                height="100%"
                :theme="theme"
                :echartsTheme="echartsTheme"
                :xAxis="linexAxis"
                :yAxis="lineyAxis"
                :series="lineSeries"
              ></bar-chart-cop>
            </div>
            <div v-if="activeTab === '4'" :style="{ height: tableHeight }">
              <el-table
                :data="abnormalPoint"
                style="width: 100%"
                :max-height="tableHeight"
              >
                <el-table-column
                  prop="date"
                  label="异常时间 (点击定位至图表位置)"
                  width="400"
                  align="center"
                >
                  <template #default="scoped">
                    <p style="cursor: pointer" @click="createMark(scoped.row)">
                      <span>{{ scoped.row.date }}</span>
                    </p>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="yp1"
                  label="叶片1"
                  width="180"
                  align="center"
                />
                <el-table-column
                  prop="yp2"
                  label="叶片2"
                  width="180"
                  align="center"
                />
                <el-table-column
                  prop="yp3"
                  label="叶片3"
                  width="180"
                  align="center"
                />
              </el-table>
            </div>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup name="prepare">
import excelCop from "@/components/generatingCapacityComponent/excel.vue";
import treeCop from "@/components/generatingCapacityComponent/tree.vue";
import tableCop from "@/components/generatingCapacityComponent/table.vue";
import barChartCop from "../spaceAnalysis/components/barChart.vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { onMounted, ref, reactive, onActivated, watch } from "vue";
import { useStore } from "vuex";
import CurrentScatterChart from "./components/current-scatter-chart.vue";
import httpRequest from "@/utils/request.js";
/**配置参数 */
const tableHeight = ref(window.innerHeight - 170 + "px");
const treeHeight = ref(window.innerHeight - 120 + "px"); //tree高度
const excelHeight = ref(window.innerHeight - 120 + "px"); //excel高度
/**excel 开始 */
const excelList = ref([]);
const speedParams = ref({});
const currentNodeKey = ref("");

import jsonData from "./components/data.json";
const funExcelChange = async (obj) => {
  chartRef.value.setMarkItem({});
  //点击excel项时
  funSubmit({
    ids: obj.id,
  });
  tableShowId.value = obj.id
  tableName.value = obj.name.substring(0, obj.name.indexOf('_'));
  getSpeedLine({
    ids: obj.id,
  });
  speedParams.value = {
    ids: obj.id,
  };
};

const createMark = (markInfo) => {
  activeTab.value = "1";
  chartRef.value.initChart(markInfo);
};

/**tree 开始 */
const treeData = ref([]);
const actTreeNode = ref(null); //当前激活的treeNode
const funRepeatMap = (arr, type) => {
  return arr.map((o) => {
    if (o.children) {
      const findIndex = o.children.findIndex((p) => !!p.type);
      if (findIndex !== -1) {
        o.childs = o.children;
        o.children = [];
        if (!actTreeNode.value && type === "prepare") {
          //判断当且仅有process获取tree时 赋值
          actTreeNode.value = o;
        }
      }
    }
    return {
      ...o,
      children: o.children.length ? funRepeatMap(o.children, type) : [],
    };
  });
};

const funGetTree = async () => {
//   const res = await httpRequest.get("/power/prepare/treepitch");
  const res = await httpRequest.get("/power/process/tree");
  treeData.value = funRepeatMap(res.data, "process");
  excelList.value = [];
  if (actTreeNode.value) {
    funCurrentChange({
      current: actTreeNode.value,
      currentNode: null,
    });
    const child = actTreeNode.value.childs[0];
    const obj = {
      id: child.id,
      interval: child.interval,
      path: child.path,
      prepareid: child.prepareid,
      station: child.station,
      time: child.time,
      type: child.type,
      windturbine: child.windturbine,
      name: child.path.substring(
        child.path.indexOf(child.station + "_") + (child.station + "_").length
      ),
    };
    currentNodeKey.value = actTreeNode.value?.id || "";
    funExcelChange(obj);
  }
};
const funCurrentChange = ({ current, currentNode }) => {
  if (current.childs) {
    excelList.value = current.childs.map((o) => {
      return {
        id: o.id,
        interval: o.interval,
        path: o.path,
        prepareid: o.prepareid,
        station: o.station,
        time: o.time,
        type: o.type,
        windturbine: o.windturbine,
        name: o.path.substring(
          o.path.indexOf(o.station + "_") + (o.station + "_").length
        ),
      };
    });
    if (excelList.value.length > 0) {
      funExcelChange(excelList.value[0]);
    }
  } else {
    excelList.value = [];
  }
};
/**table 开始 */
const tableShowId = ref("");
const tableName = ref("");
const tableColumn = ref([
  {
    prop: "time",
    label: "时间",
  },
  {
    prop: "yp1",
    label: "叶片一",
  },
  {
    prop: "yp2",
    label: "叶片二",
  },
  {
    prop: "yp3",
    label: "叶片三",
  },
]);
const tableLoading = ref(false);
const tableData = ref([]);
/**tab  */
const activeTab = ref("1");
/**chart Data */
const xAxisData = ref([]);
const chartRef = ref(); //chart 的ref
const seriesData = ref([]);
const seriesAllData = ref([]);
const dataSet = ref("");
const angleData = ref("");
const funChartSelect = async (batch) => {
  return false;
};
/**submit */
const funSubmit = async (params) => {
  const res = await httpRequest.get("/blade/angle", {
    params: params,
  });
  if (res.code !== 200) {
    return false;
  }

  angleData.value = res.data.angle

  let exTime = [];
  let yp1 = [],
    yp2 = [],
    yp3 = [],
    speed = [];
  res.data.bw.forEach((it) => {
    exTime.push(it.time);
    yp1.push(it.yp1);
    yp2.push(it.yp2);
    yp3.push(it.yp3);
    speed.push(it.speed);
  });
  tableData.value = res.data.bw;
  seriesAllData.value = res.data.bw;
  // res.data.bw.forEach(it => {
  //     yp2.push(it.yp2)
  // })
  xAxisData.value = exTime;

  seriesData.value = [
    // {
    //     name: "并网(绿)/停机(红)",
    //     type: "line",
    //     symbol: "line", //设定为实心点
    //     symbolSize: 0, //设定实心点的大小
    //     smooth: false, //这个是把线变成曲线
    //     data: yp1,
    //     xAxisIndex: 0,
    // },
    {
      name: "叶片1",
      type: "line",
      symbol: "line", //设定为实心点
      symbolSize: 0, //设定实心点的大小
      smooth: false, //这个是把线变成曲线
      data: yp1,
      xAxisIndex: 0,
    },
    {
      name: "叶片2",
      type: "line",
      symbol: "line", //设定为实心点
      symbolSize: 0, //设定实心点的大小
      smooth: false, //这个是把线变成曲线
      data: yp2,
      xAxisIndex: 0,
    },
    {
      name: "叶片3",
      type: "line",
      symbol: "line", //设定为实心点
      symbolSize: 0, //设定实心点的大小
      smooth: false, //这个是把线变成曲线
      data: yp3,
      xAxisIndex: 0,
    },
    {
      name: "风速",
      type: "line",
      yAxisIndex: 1,
      symbol: "line", //设定为实心点
      symbolSize: 0, //设定实心点的大小
      smooth: false, //这个是把线变成曲线
      data: speed,
      xAxisIndex: 0,
    },
  ];

  const exPoint = [];
  seriesData.value?.[0]?.data?.forEach((ele, index) => {
    const numEqual = [
      ele,
      seriesData.value[1].data[index],
      seriesData.value[2].data[index],
    ];
    if (areNumbersDistinct(numEqual)) {
      exPoint.push({
        date: exTime[index],
        yp1: numEqual[0],
        yp2: numEqual[1],
        yp3: numEqual[2],
        dataIndex: index,
      });
    }
  });

  abnormalPoint.value = exPoint;
};
const linexAxis = reactive({
  type: "category",
  name: "风速",
  data: [],
});
const lineyAxis = reactive({
  type: "value",
  name: "度",
  splitLine: {
    show: false,
  },
  axisTick: {
    show: true,
  },
  axisLine: {
    onZero: false,
  },
});
const lineSeries = reactive([
  {
    name: "桨距角风速曲线",
    type: "line",
    data: [],
    symbol: "line", //设定为实心点
    symbolSize: 0, //设定实心点的大小
  },
]);
const getSpeedLine = async (params) => {
  const speedRes = await httpRequest.get("/blade/curve", {
    params: params,
  });
  if (speedRes.code === 200) {
    if (speedRes.data) {
      let xAsis = [];
      let series = [];
      for (const item in speedRes.data) {
        xAsis.push(item);
        series.push(speedRes.data[item]);
      }
      linexAxis.data = xAsis;
      lineSeries[0].data = series;
    }
  }
};
/**created */
// funGetTree()
const theme = ref(null);
const echartsTheme = ref("");
const store = useStore();
watch(
  () => store.state.theme,
  (newVal, oldVal) => {
    theme.value = newVal;
    echartsTheme.value = !newVal ? "dark" : "";
    funGetTree();
  },
  {
    deep: true,
  }
);

const abnormalPoint = ref([]);
const initPageData = () => {
  treeData.value = funRepeatMap(
    JSON.parse(JSON.stringify(jsonData.treeData)),
    "prepare"
  );
  excelList.value = [];
  if (actTreeNode.value) {
    if (actTreeNode.value.childs) {
      excelList.value = actTreeNode.value.childs.map((o) => {
        return {
          id: o.id,
          interval: o.interval,
          path: o.path,
          prepareid: o.prepareid,
          station: o.station,
          time: o.time,
          type: o.type,
          windturbine: o.windturbine,
          isCheck: false,
          name: o.path.substring(
            o.path.indexOf(o.station + "_") + (o.station + "_").length
          ),
        };
      });
    } else {
      excelList.value = [];
    }
    const child = actTreeNode.value.childs[0];
    const obj = {
      id: child.id,
      interval: child.interval,
      path: child.path,
      prepareid: child.prepareid,
      station: child.station,
      time: child.time,
      type: child.type,
      windturbine: child.windturbine,
      name: child.path.substring(
        child.path.indexOf(child.station + "_") + (child.station + "_").length
      ),
    };
    currentNodeKey.value = actTreeNode.value?.id || "";

    let exTime = [];
    let yp1 = [],
      yp2 = [],
      yp3 = [],
      speed = [];
    jsonData.angelData.bw.forEach((it) => {
      exTime.push(it.time);
      yp1.push(it.yp1);
      yp2.push(it.yp2);
      yp3.push(it.yp3);
      speed.push(it.speed);
    });
    tableData.value = jsonData.angelData.bw;
    seriesAllData.value = jsonData.angelData.bw;
    xAxisData.value = exTime;

    seriesData.value = [
      {
        name: "叶片1",
        type: "line",
        symbol: "line", //设定为实心点
        symbolSize: 0, //设定实心点的大小
        smooth: false, //这个是把线变成曲线
        data: yp1,
        xAxisIndex: 0,
      },
      {
        name: "叶片2",
        type: "line",
        symbol: "line", //设定为实心点
        symbolSize: 0, //设定实心点的大小
        smooth: false, //这个是把线变成曲线
        data: yp2,
        xAxisIndex: 0,
      },
      {
        name: "叶片3",
        type: "line",
        symbol: "line", //设定为实心点
        symbolSize: 0, //设定实心点的大小
        smooth: false, //这个是把线变成曲线
        data: yp3,
        xAxisIndex: 0,
      },
      {
        name: "风速",
        type: "line",
        yAxisIndex: 1,
        symbol: "line", //设定为实心点
        symbolSize: 0, //设定实心点的大小
        smooth: false, //这个是把线变成曲线
        data: speed,
        xAxisIndex: 0,
      },
    ];

    tableShowId.value = obj.id
    tableName.value = obj.name.substring(0, obj.name.indexOf('_'));

    let xAsis = [];
    let series = [];
    for (const item in jsonData.curveData) {
      xAsis.push(item);
      series.push(jsonData.curveData[item]);
    }
    linexAxis.data = xAsis;
    lineSeries[0].data = series;

    speedParams.value = {
      ids: obj.id,
    };

    const exPoint = [];
    seriesData.value?.[0]?.data?.forEach((ele, index) => {
      const numEqual = [
        ele,
        seriesData.value[1].data[index],
        seriesData.value[2].data[index],
      ];
      if (areNumbersDistinct(numEqual)) {
        exPoint.push({
          date: exTime[index],
          yp1: numEqual[0],
          yp2: numEqual[1],
          yp3: numEqual[2],
          dataIndex: index,
        });
      }
    });

    abnormalPoint.value = exPoint;
  }
};

const areNumbersDistinct = (arr) => {
  return arr[0] !== arr[1] || arr[0] !== arr[2] || arr[1] !== arr[2];
};

/**mounted */
onMounted(() => {
  initPageData();
  funGetTree();
  theme.value = store.state.theme;
  echartsTheme.value = !theme.value ? "dark" : "";
  tableHeight.value = window.innerHeight - 170 + "px";
  excelHeight.value = window.innerHeight - 120 + "px";
  treeHeight.value = window.innerHeight - 120 + "px";
  window.addEventListener("resize", () => {
    tableHeight.value = window.innerHeight - 170 + "px";
    excelHeight.value = window.innerHeight - 120 + "px";
    treeHeight.value = window.innerHeight - 120 + "px";
  });
});
/**activated */
onActivated(() => {
  // funGetTree()
  // funSubmit()
});
</script>
<style lang="less" scoped>
.dataAnalysisAngleAna {
  height: 100%;

  .dataAnalysisAngleAnaMain {
    height: 100%;

    .main_top {
      height: 40px;
      display: flex;
      align-items: center;

      .topPsty {
        position: relative;
        top: 5px;
        padding: 7px 20px;
        font-size: 12px;
        font-weight: 600;
        margin-left: 10px;
        border-radius: 3px;
      }
    }

    .main {
      display: flex;
      width: 100%;

      .treeDataMain,
      .excelDataMain,
      .tableDataMain {
        border-radius: 10px;
      }

      .treeDataMain {
        margin-right: 10px;
        padding: 10px 0 10px 10px;
        width: calc(19% - 20px);
      }

      .excelDataMain {
        margin-right: 10px;
        padding: 10px 0 10px 10px;
        width: calc(15% - 20px);
      }

      .tableDataMain {
        padding: 10px;
        width: calc(66% - 20px);
        position: relative;

        .butten_com {
          position: absolute;
          right: 20px;
          z-index: 111111;
        }
      }
    }
  }
}

.themeDark {
  .dataAnalysisAngleAnaMain {
    .main_top {
      .topPsty {
        color: #1c99ff;
        background: #1e2126;
      }
    }

    .main {
      background: #13171e;

      .treeDataMain {
        background: transparent;
      }

      .excelDataMain {
        background: #313233;
      }

      .tableDataMain {
        margin-top: 5px;
        background: #212223;
      }
    }
  }
}

.themeLight {
  padding: 0;

  .dataAnalysisAngleAnaMain {
    .main_top {
      .topPsty {
        color: #2778ff;
        background: #ffffff;
      }
    }

    .main {
      background: #e6e8f2;

      .treeDataMain {
        background: transparent;
      }

      .excelDataMain {
        background: #f4f6fb;
      }

      .tableDataMain {
        background: #fff;
        margin-top: 5px;
      }
    }
  }
}
</style>