<template>
  <div class="data-search">
    <div class="leftContent">
      <span>{{ pageTitle }}</span>
    </div>
    <div class="data-content">
      <div class="card-left">
        <div class="cardleft">
          <div class="cardleft-search">
            <div class="cardleft_top">
              <el-select
                v-model="state.stationId"
                clearable
                size="mini"
                placeholder="全部场站"
                popper-class="select"
                @change="getWindturbineList()"
              >
                <el-option
                  v-for="item in stationList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
              <el-select
                v-model="state.modeId"
                clearable
                size="mini"
                placeholder="全部机型"
                popper-class="select"
              >
                <el-option
                  v-for="item in modelList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.aname"
                ></el-option>
              </el-select>
            </div>
            <el-input
              v-model="state.input"
              size="mini"
              placeholder="设备检索"
              clearable
            />
          </div>
          <div style="height: calc(100% - 74px)">
            <el-scrollbar height="100%">
              <div
                v-for="item in filterWTList"
                :key="item"
                :class="[
                  'scrollbar-demo-item',
                  item.id == state.activeWT ? 'active' : '',
                ]"
                @click="clickWT(item)"
              >
                {{ item.aname }}
              </div>
            </el-scrollbar>
          </div>
        </div>
        <div class="cardright">
          <el-input
            v-model="state.inputAI"
            style="margin-bottom: 10px"
            size="mini"
            placeholder="点名检索"
            clearable
          />
          <el-tree
            :data="state.treedata"
            :props="state.defaultProps"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="card-right">
        <el-table
          :data="filterAIList"
          style="width: 100%"
          height="calc(100% - 40px)"
        >
          <el-table-column
            prop="uniformCode"
            label="点名"
            align="center"
            width="120"
          />
          <el-table-column prop="name" label="名称" align="left" />
          <el-table-column prop="value" label="值" width="120" align="right">
            <template #default="scope">
              <el-tag
                size="small"
                color="#133122"
                style="border-color: #67c23a"
                type="success"
              >
                {{ scope.row.value }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="时间" width="180" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.time).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="100" align="center">
            <template #default="scope">
              {{ scope.row.unitName }}
              {{ scope.row.unitNameCn ? `(${scope.row.unitNameCn})` : "--" }}
            </template>
          </el-table-column>
          <el-table-column width="100" align="center">
            <template #default="scope">
              <el-button
                type="text"
                style="color: #05bb4c"
                size="mini"
                @click="handleSearch(scope.row)"
                >历史数据</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            layout="total,sizes, prev, pager, next"
            :current-page="query.page"
            :page-size="query.limit"
            :page-sizes="[23, 50, 100, 500]"
            :total="query.pageTotal"
            @current-change="handlePageChange"
            @size-change="
              (value) => {
                query.page = 1;
                query.limit = value;
                getFetchAIPointListt();
              }
            "
          ></el-pagination>
        </div>
      </div>

      <el-dialog
        v-model="dialogVisible"
        width="80%"
        :before-close="dialogClose"
      >
        <template #title>
          <div class="dialog-title">
            <div class="title">
              {{
                `${state.handleSearch?.name || ""}_${state.activeAI}历史数据`
              }}
            </div>
          </div>
        </template>
        <div class="pickerFifter">
          <el-date-picker
            size="mini"
            v-model="state.pickerVal"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
          <el-select
            v-model="state.selectDataVal"
            placeholder="数据源"
            style="margin: 0 10px"
          >
            <el-option
              v-for="item in state.selectData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-select
          v-model="state.selectTimeVal"
          v-show="state.selectDataVal !== 1"
          placeholder="时间间隔"
        >
          <el-option
            v-for="item in state.selectTime"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
          <el-input
            size="mini"
            class="selectTimeVal"
            v-model="state.selectTimeVal"
            style="width: 200px"
            v-show="state.selectDataVal !== 1"
            placeholder="时间间隔"
          >
            <template #append>分钟</template>
          </el-input>
          <el-button size="mini" class="buttons" round @click="pickerSearch"
            >查询</el-button
          >
          <el-button size="mini" class="buttons" round @click="export2Excel"
            >导出</el-button
          >
        </div>
        <div
          class="dChart"
          style="height: 500px; width: 100%"
          :id="eChart"
        ></div>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { getApiequipmentListByWp } from "@/api/monthlyPerformanceAnalysis.js";
import {
  ref,
  onMounted,
  watch,
  reactive,
  computed,
  onUnmounted,
  nextTick,
} from "vue";
import {
  fetchWindturbineList,
  tree,
  fetchAIDIPointList,
  getAdapterLatest,
  getAdapterHistory,
  getAdapterHistorysnap,
  AdapterHistoryExport,
  getStationinfo,
  fetchModel,
} from "@/api/zhbj/index.js";
import dayjs from "dayjs";
import * as echarts from "echarts";
import { useStore } from "vuex";
import axios from "axios";
import { ElMessage } from "element-plus";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
const pageTitle = "数据查询";
const store = useStore();
const isStation = computed(() => store.getters.isStation);
const stationList = computed(() => store.state.stationListAll);
const eChart = ref("eChart" + Date.now() + Math.random());
watch(
  () => stationList,
  (val, old) => {
    val.value[0] &&
      nextTick(async () => {
        state.stationId = stationList.value[0]?.id;
        await getWindturbineList();
        getTreeData();
      });
  },
  {
    deep: true,
    immediate: true,
  }
);

onMounted(async () => {
  getequipmentmodel_list();
  getTreeData();
});
onUnmounted(() => {
  state.echarts?.clear(); //销毁
  clearInterval(state.Interval);
  state.Interval = null;
});
const dialogClose = (done) => {
  state.echarts?.clear(); //销毁
  done();
};
const query = reactive({
  page: 1,
  limit: 23,
  pageTotal: null,
});
const dialogVisible = ref(null);
const state = reactive({
  handleSearch: null,
  input: "",
  inputAI: "",
  stationId: "",
  windturbineList: [],
  modelListAll: [],
  modeId: "",
  AIList: [],
  activeWT: "",
  activeAI: "",
  Interval: null,
  pickerVal: [new Date(new Date() - 1 * 60 * 60 * 1000), new Date()],
  echarts: null,
  treedata: [],
  defaultProps: {
    children: "children",
    label: (a) => {
      return a.node.name;
    },
  },
  structcode: "",
  selectDataVal: 1,
  selectData: [
    {
      label: "原始数据",
      value: 1,
    },
    {
      label: "数据快照",
      value: 2,
    },
  ],
  selectTimeVal: 1,
  downData: null,
});
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await fetchModel();
  state.modelListAll = data;
};
const modelList = computed(() => {
  //   if (state.stationId == "") {
  //     return [];
  //   } else {
  //     return state.modelListAll[state.stationId];
  //   }
  return [
    {
      id: "SEC-W02B-1250kW",
      nemCode: "SEC-W02B-1250kW",
      name: "SEC-W02B-1250kW",
      aname: "SEC-W02B-1250kW",
      description: "DI",
      powerProduction: 1250,
      windturbineManufacturerId: "SHDQ_MF",
      photo: null,
      unit: null,
      cutinwindSpeed: 3,
      ratedwindSpeed: 11,
      cutoutwindSpeed: "25",
      sweptArea: 5800,
      equipmentCategory: "F",
    },
  ];
});
//get 风机机组
const getWindturbineList = async () => {
  const { data } = await getApiequipmentListByWp({ wpid: state.stationId });
  state.windturbineList = data.data;
  state.activeWT = state.windturbineList[0]?.id;
  state.modeId = "";
  //   await getequipmentmodel_list();
  await getFetchAIPointListt();
};
// 风机搜 索
const filterWTList = computed(() =>
  state.windturbineList?.filter(
    (data) =>
      data.aname.includes(state.input) && data.modelId.includes(state.modeId)
  )
);
//AI点检索
const filterAIList = computed(() =>
  //   state.AIList?.filter(
  //     (data) => !state.inputAI || data.name.includes(state.inputAI)
  //     //   !state.inputAI ||
  //     //   (data.uniformCode.toUpperCase().includes(state.inputAI.toUpperCase()) ||
  //     //   data.name.indexOf(state.inputAI))
  //   )
  // );
  new Array(5).fill({
    unitNameCn: "",
    englishName: null,
    unitName: "",
    modelId: "SEC-W02B-1250kW",
    name: "01号风机风向",
    valueUnit: null,
    model: "SEC-W02B-1250kW",
    typeId: "F",
    id: "e222918e1e6a4feeba41007be3c85bf7",
    uniformCode: "AI067",
    value: "344.00",
    time: 1718176440000,
  })
);

// get 实时data
const getLatest = async (stationId, AIlist) => {
  const data = await getAdapterLatest(stationId, AIlist, state.stationId);
  state.AIList?.forEach((e) => {
    if (e.uniformCode.indexOf("AI") !== -1) {
      e.value = Number(data[e.uniformCode]?.doubleValue).toFixed(2);
    }
    // else {
    //   e.value = data[e.uniformCode]?.booleanValue - 0;
    // }
    e["time"] = data[e.uniformCode]?.ts;
  });
};

// get 历史数据
const getHistory = async (stationId, AIpoint) => {
  let startTs = dayjs(state.pickerVal[0]).valueOf();
  let endTs = dayjs(state.pickerVal[1]).valueOf();
  const baseUrl = `http://10.81.3.162:801${
    /FDC/.test(state.stationId) ? "1" : "2"
  }/`;
  const data = await getAdapterHistory(
    stationId,
    AIpoint,
    startTs,
    endTs,
    baseUrl
  );
  state.downData = data;
  option.xAxis.data = [];
  option.series[0].data = [];
  let timeArr = [];
  data.forEach((e) => {
    option.series[0].data.push(e.doubleValue.toFixed(2));
    option.xAxis.data.push(dayjs(e.ts).format("YYYY-MM-DD HH:mm:ss"));
  });

  let chat = echarts.init(document.getElementById(eChart.value));
  state.echarts = await chat.setOption(option);
};

// get 数据快照
const getHistorysnap = async (stationId, AIpoint, interval) => {
  let startTs = dayjs(state.pickerVal[0]).valueOf();
  let endTs = dayjs(state.pickerVal[1]).valueOf();
  const baseUrl = `http://10.81.3.162:801${
    /FDC/.test(state.stationId) ? "1" : "2"
  }/`;
  const data = await getAdapterHistorysnap(
    stationId,
    AIpoint,
    startTs,
    endTs,
    interval,
    baseUrl
  );
  state.downData = data;
  option.xAxis.data = [];
  option.series[0].data = [];
  let timeArr = [];
  data.forEach((e) => {
    option.series[0].data.push(e.doubleValue.toFixed(2));
    option.xAxis.data.push(dayjs(e.ts).format("YYYY-MM-DD HH:mm:ss"));
  });
  let chat = echarts.init(document.getElementById(eChart.value));
  state.echarts = await chat.setOption(option);
};
const option = {
  tooltip: {
    trigger: "axis",
    position: function (pt) {
      return [pt[0], "10%"];
    },
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [],
  },
  yAxis: {
    type: "value",
    boundaryGap: [0, "100%"],
  },
  dataZoom: [
    {
      type: "inside",
      start: 0,
      end: 10,
    },
    {
      start: 0,
      end: 10,
    },
  ],
  series: [
    {
      data: [],
      type: "line",
      smooth: true,
    },
  ],
};

//get AI
const getFetchAIPointListt = async () => {
  const res = await fetchAIDIPointList(
    "windturbine",
    state.structcode,
    state.stationId,
    state.activeWT,
    query.page,
    query.limit
  );
  state.AIList = res?.records;
  query.pageTotal = res?.total;
  let AIlist = [];
  res.records?.forEach((e) => {
    AIlist.push(e.uniformCode);
  });
  if (state.Interval) {
    clearInterval(state.Interval);
  }
  getLatest(state.activeWT, AIlist);
  state.Interval = setInterval(getLatest, 5000, state.activeWT, AIlist);
};
// TREE
// tree click
const handleNodeClick = (data) => {
  state.structcode = data.node.code;
  getFetchAIPointListt();
};
// gettreeData
const getTreeData = async () => {
  // const res = await tree();
  // let data = res.children[1].children;

  let data = [];
  data.unshift({ node: { code: "", name: "全部" } });
  // data.unshift({ node: { code: "1010102", name: "全部" } });

  // data.forEach((e) => {
  //   delete e.children;
  // });
  state.treedata = data;
};
//
const handleSearch = (item) => {
  dialogVisible.value = true;
  state.handleSearch = item;
  state.activeAI = item.uniformCode;
  getHistory(state.activeWT, state.activeAI);
};
const clickWT = (item) => {
  state.activeWT = item.id;
  if (state.Interval) {
    clearInterval(state.Interval);
  }
  getFetchAIPointListt();
};

const pickerSearch = () => {
  if (state.selectDataVal == 1) {
    getHistory(state.activeWT, state.activeAI);
  } else {
    getHistorysnap(state.activeWT, state.activeAI, state.selectTimeVal * 60);
  }
};
// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getFetchAIPointListt();
};
// 批量导出
const export2Excel = async () => {
  let data = state.downData;
  data.forEach((e) => {
    e.doubleValue = e.doubleValue.toFixed(2);
    e.ts = dayjs(e.ts).format("YYYY-MM-DD HH:mm:ss");
  });
  ElMessage.success(`导出成功!`);
  const tableHeader = ["时间", "值"];
  const tableKey = ["ts", "doubleValue"];
  outExportExcel(
    tableHeader,
    tableKey,
    data,
    `${state.activeWT}_${state.activeAI}_${dayjs(state.pickerVal[0]).format(
      "YYYY-MM-DD HH:mm"
    )}-${dayjs(state.pickerVal[1]).format("YYYY-MM-DD HH:mm")}历史数据excel`
  );
};
</script>

<style lang="less" scoped>
.data-search {
  width: 100%;
  height: 100%;
  padding: 10px 20px;
  .leftContent {
    width: 242px;
    height: 41px;
    display: flex;
    align-items: center;
    // background: url("~@/assets/imgs/title_left_bg1.png") no-repeat;
    background: url("~@/assets/imgs/title_left_bg.png") no-repeat;

    span {
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #05bb4c;
      margin-left: 25px;
    }
  }
  .data-content {
    width: 100%;
    height: calc(100% - 40px);
    display: flex;
    justify-content: space-between;
    .card-left {
      width: 45%;
      height: 100%;
      display: flex;
      margin-right: 20px;

      .cardleft {
        width: 50%;
        height: 100%;
        margin-right: 20px;
        padding: 10px;
        background: #161f1e;
        .cardleft-search {
          padding-bottom: 10px;
          .cardleft_top {
            display: flex;
            padding-bottom: 10px;
            .el-select {
              flex: 1;
              &:nth-child(1) {
                margin-right: 10px;
              }
            }
          }
        }
      }
      .cardright {
        width: calc(50% - 20px);
        height: 100%;
        padding: 10px;
        background: #161f1e;
      }
    }
    .card-right {
      width: calc(55% - 20px);
      height: 100%;
      padding: 10px;
      background: #161f1e;
      .pagination {
        padding-top: 10px;
      }
    }
  }
}

.pickerFifter {
  width: 80%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  height: 30px;
  margin: 8px 0;
  text-align: center;
  border-radius: 4px;
  color: #b3b3b3;
  background-color: rgba(7, 122, 52, 0.2);
  border: 1px solid #3b6c53;
  &.active,
  &:hover {
    background-color: rgba(5, 187, 76, 0.5);
    color: #ffffff;
  }
  &:nth-child(1) {
    margin-top: 0;
  }
  &:nth-last-child(1) {
    margin-bottom: 0;
  }
}
.buttons {
  background-color: rgba(5, 187, 76, 0.2);
  border: 1px solid #3b6c53;
  color: #b3b3b3;
  font-size: 14px;

  &:hover {
    background-color: rgba(5, 187, 76, 0.5);
    color: #ffffff;
  }
}
.selectTimeVal ::v-deep {
  margin-right: 10px;
  .el-input__inner {
    text-align: right;
    border-radius: 12.5px 0px 0px 12.5px !important;
  }
  .el-input-group__append {
    background-color: #172422 !important;
    color: #fff !important;
    border: 0px !important;
    border-radius: 12.5px !important;
    border-top-left-radius: 0 !important;
    border-bottom-left-radius: 0 !important;
  }
}
</style>
