<template>
  <div class="statisticalReport">
    <div class="searchMain">
      <div class="searchBox" ref="searchref">
        <el-form :inline="true" :model="formdata" class="demo-form-inline">
          <el-form-item label="电压等级" class="dyClass">
            <el-select v-model="formdata.dyid" @change="getSearchxl">
              <el-option
                v-for="item in dyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                {{ item.name }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="线路名称">
            <el-select v-model="formdata.lineid" filterable>
              <el-option
                v-for="item in xlOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="活动"
            class="activitybox"
            v-if="
              roleName === 'superadmin' ||
              roleName === 'Matthew' ||
              roleName === 'SCB'
            "
          >
            <el-select
              @keyup.enter.native="onSubmit()"
              v-model="formdata.activityId"
              filterable
              @change="changeActive"
            >
              <el-option
                v-for="item in activityOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="formdata.starttime"
              type="datetime"
              placeholder="开始日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
              default-time="00:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="formdata.endtime"
              type="datetime"
              default-time="23:59:59"
              placeholder="结束日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
              class="ml10"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="formdata.search"
              placeholder="请输入装置编号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="采样周期" class="intervalClass">
            <el-input
              v-model="formdata.interval"
              placeholder="请输入采样周期"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :disabled="searchFlag"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div class="pictureBox">
        <div class="deviceTable">
          <el-table
            ref="multipleTable"
            border
            :data="lastDataArray"
            tooltip-effect="dark"
            stripe
            style="width: 100%"
            height="calc(120%)"
            v-loading="loading"
            highlight-current-row
          >
            <template slot="empty">
              <el-empty :image-size="160" description="暂无数据"></el-empty>
            </template>
            <el-table-column prop="cmdid" label="装置"></el-table-column>

            <el-table-column label="图片数据" prop="photoTimePoint">
              <template slot-scope="scope">
                <span class="pre-format">{{ scope.row.photoTimePoint }}</span>
              </template>
            </el-table-column>
            <el-table-column label="覆冰数据" prop="pullPoint">
              <template slot-scope="scope">
                <span class="pre-format">{{ scope.row.pullPoint }}</span>
              </template>
            </el-table-column>
            <el-table-column label="天气数据" prop="weatherPoint">
              <template slot-scope="scope">
                <span class="pre-format">{{ scope.row.weatherPoint }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSearchInfo, getReportApi } from "@/utils/api/index";
import { getActivityApi } from "@/utils/api/reportApi";
export default {
  name: "statisticalReport",
  data() {
    return {
      searchFlag: true,
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > Date.now(); // 禁用大于今天的日期
        },
      },
      dyOptions: [{ id: -1, name: "全部" }], //电压数据
      xlOptions: [{ id: -1, name: "全部" }], //线路数据
      activityOptions: [{ id: -1, name: "全部" }], //活动
      formdata: {
        dyid: -1,
        lineid: -1,
        towerid: -1,
        channelid: -1,
        interval: 10,
        search: "",
        activityId: -1,
      },
      dataArray: [],
      lastDataArray: [],
      page: 1, // 当前页数
      pageSize: 20, // 每页数量
      tdTermid: "",
      loading: false,
    };
  },
  created() {
    var that = this;
    this.roleName = localStorage.getItem("userName");
    document.onkeydown = function (e) {
      var key = window.event.keyCode;
      if (key === 13) {
        that.onSubmit(); // 触发事件
      }
    };
  },
  mounted() {
    this.getactiveList();
    this.$set(this.formdata, "endtime", new Date().getTime());
    this.$set(
      this.formdata,
      "starttime",
      new Date(new Date().toLocaleDateString()).getTime()
    );
  },
  methods: {
    //获取电压信息
    getSearchdy() {
      getSearchInfo({ type: 1 })
        .then((res) => {
          this.dyOptions = this.dyOptions.concat(res.data.list);
          console.log(this.dyOptions);
          if (JSON.stringify(this.$route.query) === "{}") {
            this.formdata.dyid = this.dyOptions[0].id;
          } else {
            this.formdata.dyid = Number(this.$route.query.dyId);
          }
          this.getSearchxl();
        })
        .catch((err) => {});
    },
    //获取线路数据
    getSearchxl() {
      getSearchInfo({ type: 2, id: this.formdata.dyid })
        .then((res) => {
          this.xlOptions = [{ id: -1, name: "全部" }];
          this.xlOptions = this.xlOptions.concat(res.data.list);

          if (JSON.stringify(this.$route.query) === "{}") {
            this.formdata.lineid = this.xlOptions[0].id;
          } else {
            this.formdata.lineid = Number(this.$route.query.lineId);
          }
        })
        .catch((err) => {});
    },
    //获取活动列表
    getactiveList() {
      getActivityApi()
        .then((res) => {
          // this.activityOptions = this.activityOptions.concat(res.data.list);
          let activeArr = res.data.map((item) => ({
            id: item.id,
            name: item.title,
          }));
          this.activityOptions = this.activityOptions.concat(activeArr);
          console.log(this.activityOptions);
          this.formdata.activityId = this.activityOptions[1].id;
          this.searchFlag = false;
        })
        .catch((err) => {});
    },
    changeActive(val) {
      this.formdata.activityId = val;
    },
    getSearchtdAlone() {
      getSearchInfo({ type: 5, id: this.tdTermid })
        .then((res) => {
          this.tdOptions = [{ id: -1, name: "全部", alias: null }];
          this.tdOptions = this.tdOptions.concat(res.data.list);
        })
        .catch((err) => {});
    },
    //获取图片列表
    getPicData() {
      this.loading = true;
      console.log(this.formdata);
      this.$set(this.formdata, "pageindex", this.page);
      this.$set(this.formdata, "pagesize", this.pageSize);
      getReportApi(this.formdata)
        .then((res) => {
          console.log(res.data);
          this.dataArray = res.data;
          this.loading = false;
          this.lastDataArray = this.processSnapshotData(this.dataArray);
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    processSnapshotData(data) {
      return data.map((item) => {
        const channelStatus = [];
        console.log(item);
        //图片数据
        item.channels.forEach((channel) => {
          const channelStatusParts = []; // 通道级别的状态片段
          channel.presets.forEach((preset) => {
            const missingTimes = [];
            const moreTimes = [];
            preset.scheduleList.forEach((schedule) => {
              if (schedule.wrong && schedule.timeList.length === 0) {
                const time = `${schedule.hour
                  .toString()
                  .padStart(2, "0")}:${schedule.minute
                  .toString()
                  .padStart(2, "0")}`;
                missingTimes.push(time);
              }
              if (schedule.wrong && schedule.timeList.length > 1) {
                const time = `${schedule.hour
                  .toString()
                  .padStart(2, "0")}:${schedule.minute
                  .toString()
                  .padStart(2, "0")}`;
                moreTimes.push(time);
              }
            });

            // 生成当前预置位的状态片段
            const presetStatusParts = [];
            if (missingTimes.length > 0) {
              presetStatusParts.push(
                `少图（${[...new Set(missingTimes)].join("、")}）`
              );
            }
            if (moreTimes.length > 0) {
              presetStatusParts.push(
                `多图（${[...new Set(moreTimes)].join("、")}）`
              );
            }

            // 若当前预置位有问题，则添加到通道状态
            if (presetStatusParts.length > 0) {
              channelStatusParts.push(
                `预置位${preset.presetId}：${presetStatusParts.join("，")}`
              );
            }
          });

          // 构建通道的最终状态描述
          const status =
            channelStatusParts.length > 0
              ? `通道${channel.channelId}：${channelStatusParts.join("；")}`
              : `通道${channel.channelId}图片正常`;
          channelStatus.push(status);
        });
        //覆冰数据
        const pullStatusParts = [];
        const pullmissingTimes = [];
        const pullmoreTimes = [];
        item.pullScheduleList.forEach((pull) => {
          if (pull.wrong && pull.timeList.length === 0) {
            const time = `${pull.hour.toString().padStart(2, "0")}:${pull.minute
              .toString()
              .padStart(2, "0")}`;
            pullmissingTimes.push(time);
          }
          if (pull.wrong && pull.timeList.length > 1) {
            const time = `${pull.hour.toString().padStart(2, "0")}:${pull.minute
              .toString()
              .padStart(2, "0")}`;
            pullmoreTimes.push(time);
          }
        });
        console.log(pullmissingTimes);
        console.log(pullmoreTimes);
        // 生成当前预置位的状态片段
        const pullParts = [];
        if (pullmissingTimes.length > 0) {
          pullParts.push(
            `少${pullmissingTimes.length}条数据（${[
              ...new Set(pullmissingTimes),
            ].join("、")}）`
          );
        }
        if (pullmoreTimes.length > 0) {
          pullParts.push(
            `多${pullmoreTimes.length}条数据（${[
              ...new Set(pullmoreTimes),
            ].join("、")}）`
          );
        }
        // 构建通道的最终状态描述
        const pullstatus =
          pullParts.length > 0 ? `${pullParts.join("；")}` : `数据正常`;
        pullStatusParts.push(pullstatus);

        //覆冰拉力结束

        //天气数据遍历开始
        //覆冰数据
        const weatherStatusParts = [];
        const weathermissingTimes = [];
        const weathermoreTimes = [];
        item.weatherScheduleList.forEach((weather) => {
          if (weather.wrong && weather.timeList.length === 0) {
            const time = `${weather.hour
              .toString()
              .padStart(2, "0")}:${weather.minute.toString().padStart(2, "0")}`;
            weathermissingTimes.push(time);
          }
          if (weather.wrong && weather.timeList.length > 1) {
            const time = `${weather.hour
              .toString()
              .padStart(2, "0")}:${weather.minute.toString().padStart(2, "0")}`;
            weathermoreTimes.push(time);
          }
        });
        console.log(weathermissingTimes);
        console.log(weathermoreTimes);
        // 生成当前预置位的状态片段
        const weatherParts = [];
        if (weathermissingTimes.length > 0) {
          weatherParts.push(
            `少${weathermissingTimes.length}条数据（${[
              ...new Set(weathermissingTimes),
            ].join("、")}）`
          );
        }
        if (weathermoreTimes.length > 0) {
          weatherParts.push(
            `多${weathermoreTimes.length}条数据（${[
              ...new Set(weathermoreTimes),
            ].join("、")}）`
          );
        }
        // 构建通道的最终状态描述
        const weatherstatus =
          weatherParts.length > 0 ? `${weatherParts.join("；")}` : `数据正常`;
        weatherStatusParts.push(weatherstatus);
        //天气数据遍历结束

        //最终返回数据
        return {
          cmdid: item.cmdid,
          photoTimePoint: channelStatus.join("\n"),
          pullPoint: pullStatusParts.join("\n"),
          weatherPoint: weatherStatusParts.join("\n"),
        };
      });
    },

    //查询
    onSubmit() {
      if (this.formdata.starttime > this.formdata.endtime) {
        return this.$message({
          duration: 1500,
          showClose: true,
          message: "开始日期不能大于结束日期",
          type: "warning",
        });
      }

      this.getPicData();
    },
  },
};
</script>
<style lang="less">
.statisticalReport {
  width: calc(100% - 24px);
  height: calc(100% - 24px);
  padding: 12px 12px;
  background: #fff;

  .deviceTable {
    height: calc(100% - 94px);
    //background: #fcc;
  }

  .searchMain {
    border: 1px solid #dddddd;
    height: calc(100% - 22px);
    padding: 12px;
    border-radius: 4px;

    .ml10 {
      margin-left: 10px;
    }
    .dyClass {
      .el-select {
        width: 150px;
      }
    }
    .intervalClass {
      .el-input {
        width: 80px;
      }
    }
  }
  .pictureBox {
    height: calc(100% - 135px);
    border: 1px solid #eee;
    .pre-format {
      white-space: pre-line; /* 保留换行符 */
      line-height: 1.8; /* 增加行间距 */
    }
  }
}
</style>
