<template>
  <div class="datasearch">
    <el-card class="box-card cardleft">
      <div class="cardleft_top">
        <el-select
          v-if="!isStation"
          v-model="state.stationId"
          clearable
          style="width: 140px; margin-right: 20px"
          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
          style="flex: 1"
          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 style="height: calc(100% - 54px)">
        <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>
    </el-card>
    <el-card class="box-card cardmid">
      <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"
      />
    </el-card>
    <el-card class="box-card cardright">
      <el-table :data="filterAIList" style="width: 100%" height="77vh">
        <el-table-column prop="uniformCode" label="点名" width="120" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="value" label="值" width="80">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.value }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="时间" width="180" align="center">
          <template #default="scope">
            <el-tag>{{
              dayjs(scope.row.time).format("YYYY-MM-DD HH:mm:ss")
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="单位" width="180" align="center">
          <template #default="scope">
            {{ scope.row.unitName }}
            {{ scope.row.unitNameCn ? `(${scope.row.unitNameCn})` : "" }}
          </template>
        </el-table-column>
        <el-table-column width="100">
          <template #default="scope">
            <el-button size="small" @click="handleSearch(scope.row)"
              >历史数据</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          hide-on-single-page
          :current-page="query.page"
          :page-size="query.limit"
          :total="query.pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      width="80%"
      :before-close="dialogClose"
      :title="`${state.activeWT}_${state.activeAI}_${
        state.handleSearch?.name || ''
      }历史数据`"
    >
      <div class="pickerFifter">
        <el-date-picker
          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
          v-model="state.selectTimeVal"
          style="width: 200px"
          v-show="state.selectDataVal !== 1"
          placeholder="时间间隔"
        >
          <template #append>分钟</template>
        </el-input>
        <el-button
          size="small"
          type="primary"
          style="margin: 0 10px"
          @click="pickerSearch"
          >查询</el-button
        >
        <el-button size="small" type="primary" @click="export2Excel"
          >导出</el-button
        >
      </div>
      <div class="dChart" style="height: 500px; width: 100%" :id="eChart"></div>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  ref,
  onMounted,
  watch,
  reactive,
  computed,
  onUnmounted,
  nextTick,
} from "vue";
import {
  fetchWindturbineList,
  tree,
  fetchAIDIPointList,
  getAdapterLatest,
  getAdapterHistory,
  getAdapterHistorysnap,
  AdapterHistoryExport,
  getStationinfo,
  fetchModel,
} from "/@/api/api.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 "/@/utils/exportExcel"; //引入文件
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();
});
onUnmounted(() => {
  state.echarts?.clear(); //销毁
  clearInterval(state.Interval);
  state.Interval = null;
});
const dialogClose = (done) => {
  state.echarts?.clear(); //销毁
  done();
};
const query = reactive({
  page: 1,
  limit: 14,
  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];
  }
});
//get 风机机组
const getWindturbineList = async () => {
  const { data } = await fetchWindturbineList(state.stationId);
  state.windturbineList = 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))
  )
);

// 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);
  }
  state.Interval = setInterval(getLatest, 1000, 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="scss" scoped>
.datasearch {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  .el-card__body {
    height: calc(100% - 40px);
  }
  .cardleft {
    width: 18vw;

    .cardleft_top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
    }

    .active {
      background: #afd5ff;
    }
  }

  .cardmid {
    width: 10vw;
    margin: 0 10px;

    .active {
      background: #afd5ff;
    }
  }

  .cardright {
    flex: 1;
  }
}

.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: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}
</style>
<style lang="scss">
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #bbdbff !important;
}

.deviceModelClass {
  .el-table__header tr,
  .el-table__header th {
    padding: 0;
    height: 40px;
  }

  .el-table__body tr,
  .el-table__body td {
    padding: 0;
    height: 40px;
  }
}
</style>
