<template>
  <div>
    <el-card style="margin-bottom: 10px">
      <el-space wrap :size="30">
        <div class="search-input">
          <span class="lable">场站：</span>
          <template v-if="state.stationListCount % 2">
            <el-select
              v-model="state.stationId"
              clearable
              placeholder="请选择"
              popper-class="select"
              @change="getWindturbineList(1)"
            >
              <el-option
                v-for="item in stationList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-select
              v-model="state.stationId"
              clearable
              placeholder="请选择"
              popper-class="select"
              @change="getWindturbineList(1)"
            >
              <el-option
                v-for="item in stationList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </template>
        </div>
        <div class="search-input">
          <span class="lable">机组：</span>
          <el-select
            v-model="state.windturbineId"
            clearable
            style="width: 150px"
            placeholder="全部"
            popper-class="select"
          >
            <el-option
              v-for="item in state.windturbineList"
              :key="item.id"
              :value="item.id"
              :label="item.windturbineCode"
            ></el-option>
          </el-select>
        </div>
        <div class="search-input">
          <span class="lable">开始日期：</span>

          <el-date-picker
            v-model="state.startDate"
            type="date"
            placeholder="开始日期"
            popper-class="date-select"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </div>
        <div class="search-input">
          <span class="lable">结束日期：</span>

          <el-date-picker
            v-model="state.endDate"
            type="date"
            placeholder="开始日期"
            popper-class="date-select"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </div>
        <el-button class="btn green" type="primary" @click="getTable()"
          >查询</el-button
        >
      </el-space>
      <el-row :gutter="24" class="btnFilterRow">
        <el-button
          class="btnFilter"
          v-for="(item, index) in state.ruleList"
          :key="index"
          @click="btnFilter(item.code)"
        >
          {{ item.name }}
        </el-button>
      </el-row>
    </el-card>
    <el-card>
      <div class="table-box">
        <div class="custom-report-items" v-if="state.tableData?.length">
          <div
            class="title"
            v-for="(item, index) in state.tableData"
            :key="index"
            @click="alertDetail(item)"
          >
            <div class="alarmName">{{ item.alarmtext }}</div>
            <div class="alarmContent">
              <div class="alarmTime">
                时长：{{ fiexdTime(item.times) }}(分钟)
              </div>
              <div class="alarmSum">次数：{{ item.sum }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-dialog
        :title="state.stationName + '_' + state.alarmtext"
        v-model="dialogShow"
        width="80%"
        top="10vh"
        custom-class="modal dBody"
        :close-on-click-modal="true"
        :before-close="dialogClose"
        :destroy-on-close="true"
      >
        <div class="dGrid" height="100%">
          <el-table
            :data="state.dGridData"
            height="66vh"
            style="width: 100%"
            stripe
          >
            <el-table-column prop="windturbineCode" label="风机" />
            <el-table-column prop="sum" label="次数" />
            <el-table-column prop="times" label="时间(分钟)">
              <template #default="scope">
                {{ fiexdTime(scope.row.times) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="dChart" height="100%" id="dChart"></div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import dayjs from "dayjs";
import { ref, onMounted, watch, reactive, computed, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  fetchWindturbineList,
  statistics_querymap,
  statistics_querybyname,
  statistics_lineandproject,
  alertrule2_list,
} from "/@/api/api.js";
import { useStore } from "vuex";
const store = useStore();
const endtime = new Date(new Date() - 1 * 24 * 60 * 60 * 1000);
const starttime = new Date(endtime - 1 * 24 * 60 * 60 * 1000);
const stationList = computed(() => store.state.stationList);
const isStation = computed(() => store.getters.isStation);
watch(
  () => stationList,
  (val, old) => {
    val.value[0] &&
      nextTick(async () => {
        state.stationId = val.value[0]?.id;
        state.stationName = val.value[0]?.name;
        state.startDate = formatTime(starttime);
        state.endDate = formatTime(endtime);
        await getWindturbineList();
        await getAlertrule2list();
        await getTable();
      });
  },
  {
    deep: true,
    immediate: true,
  }
);

onMounted(async () => {});
const state = reactive({
  stationId: "",
  stationName: "",
  windturbineList: [],
  windturbineId: "",
  startDate: null,
  endDate: null,
  tableData: [],
  tableDataList: [],
  dGridData: [],
  dChartData: [],
  firstRuleList: [],
  ruleList: [],
  chart: null,
  alarmtext: "",
  stationListCount: 0,
});
let dialogShow = ref(false);

const btnFilter = (item) => {
  if (item === "") {
    state.tableData = JSON.parse(
      JSON.stringify(state.tableDataList?.length ? state.tableDataList : [])
    );
  } else {
    let tableData = [];
    state.tableDataList.forEach((e) => {
      if (e.datadictionary?.code == item) {
        tableData.push(e);
      }
    });
    state.tableData = tableData;
  }
};
//get 风机
const getWindturbineList = async (flg = false) => {
  const res = await fetchWindturbineList(state.stationId);
  state.stationName = res?.[0]?.name;
  state.windturbineList = res;
  flg && await getTable();
};
//get 规则
const getAlertrule2list = async () => {
  const res = await alertrule2_list();
  state.firstRuleList = res;
  let arr = [];
  res.forEach((e) => {
    arr.push(e.datadictionary);
  });
  var obj = {};
  state.ruleList = arr.reduce(function (a, b) {
    b && (obj[b.name] ? "" : (obj[b.name] = true && a.push(b)));
    return a;
  }, []);
  state.ruleList.unshift({ code: "", name: "全部" });
  state.ruleList.push({ code: "other", name: "其他" });
};

const getTable = async () => {
  state.tableData = [];
  state.tableDataList = [];
  const res = await statistics_querymap({
    stationid: state.stationId,
    windturbineid: state.windturbineId,
    datebegin: state.startDate,
    dateend: state.endDate,
  });

  let tmpArr = [];
  for (var key in res.data) {
    let item = res.data[key];
    item["key"] = key;
    tmpArr.push(item);
  }
  tmpArr.sort(function (a, b) {
    return b["sum"] - a["sum"];
  });
  tmpArr.forEach((e) => {
    e["datadictionary"] = { code: "other" };
    state.firstRuleList.find((k) => {
      if (e.alarmtext == k.name) {
        e["datadictionary"] = k.datadictionary;
      }
    });
  });
  state.tableDataList = tmpArr;
  btnFilter("");
};

//弹出
const alertDetail = async (item) => {
  state.alarmtext = item.alarmtext;
  state.dGridData = [];
  dialogShow.value = true;

  const resData = await statistics_querybyname({
    stationid: state.stationId,
    datebegin: state.startDate,
    dateend: state.endDate,
    snapid: item["key"],
  });
  const dGridData = Object.values(resData.data);
  dGridData.sort(function (a, b) {
    return b.sum - a.sum;
  });
  state.dGridData = dGridData;
  await alertDetailChart(item);
};
const alertDetailChart = async (item) => {
  document.getElementById("dChart").removeAttribute("_echarts_instance_");
  state.chart = echarts.init(document.getElementById("dChart"));
  const { data } = await statistics_lineandproject({
    stationid: state.stationId,
    datebegin: state.startDate,
    dateend: state.endDate,
    snapid: item["key"],
  });
  let dataX = [],
    data1 = [],
    data2 = [];
  for (let item of data) {
    dataX.push(item["linenum"]);
    data1.push(item["happendsum"]);
    data2.push(item["sum"]);
  }

  let option = {
    color: ["#05bb4c", "#4b55ae", "#fa8c16"],
    title: {
      text: "报警统计柱状图",
      left: "5%",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["总数", "发生数量"],
      textStyle: {
        color: "#000",
      },
    },
    grid: {
      left: "5%",
      right: "6%",
      bottom: "6%",
      containLabel: true,
    },
    xAxis: {
      name: "线路",
      type: "category",
      data: dataX,
      axisLabel: {
        interval: 0, //强制文字产生间隔
        rotate: 45, //文字逆时针旋转45°
      },
    },
    yAxis: { name: "数量", type: "value" },
    series: [
      {
        name: "总数",
        type: "bar",
        barWidth: 40,
        barGap: "-100%",
        label: { normal: { show: true, position: "top" } },
        data: data2,
      },
      {
        name: "发生数量",
        type: "bar",
        barGap: "-100%",
        barWidth: 40,
        label: { normal: { show: true, position: "inside" } },
        data: data1,
      },
    ],
  };
  state.chart.setOption(option);
};
const dialogClose = (done) => {
  state.chart?.dispose();
  done();
  state.stationListCount++;
};
// 时间格式化
const formatTime = (val) => {
  return dayjs(val).format("YYYY-MM-DD");
};
// 保留两位小数格式化

const fiexdTime = (val) => {
  return val.toFixed(2);
};
</script>
<style lang="scss" scoped>
.btnFilterRow {
  padding-top: 15px !important;
  margin-top: 10px;
  border-top: 1px solid #eee;
}

.dGrid {
  height: 70vh;
  width: 30%;
  display: inline-block;
}

.dChart {
  height: 70vh;
  width: 70%;
  display: inline-block;
  vertical-align: top;
}

.dBody {
  height: 80vh;
  overflow-x: hidden;
}

.custom-report-items {
  display: flex;
  flex-wrap: wrap;

  .title {
    height: 120px;
    width: 17.6vw;
    background: rgba(#606769, 0.1);
    color: #606769;
    border-radius: 6px;
    padding: 3px;
    font-size: 1.85vh;
    margin: 6px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    cursor: pointer;

    .alarmName {
      width: 100%;
      font-size: 18px;
      text-align: center;
    }

    .alarmContent {
      font-size: 16px;
      width: 100%;
      display: flex;
      justify-content: space-around;
    }
  }
}
</style>