<template>
  <div class="draught-fan-list">
    <div class="form-wrapper">
      <div class="search mg-b-8">
        <div class="search-items">
          <div class="search-item">
            <div class="lable">电站：</div>
            <div class="search-content">
              <el-select
                v-model="station"
                clearable
                size="mini"
                placeholder="请选择"
                popper-class="select"
                @change="
                  (station) => {
                    getWt(station, true);
                  }
                "
              >
                <el-option
                  v-for="item in wpArray"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">设备：</div>
            <div class="search-content">
              <el-select
                v-model="inverters"
                clearable
                :multiple="isMultiple"
                collapse-tags
                collapse-tags-tooltip
                size="mini"
                placeholder="请选择"
                popper-class="select"
              >
                <el-checkbox
                  v-if="isMultiple"
                  v-model="checked"
                  :indeterminate="indeterminate"
                  @change="selectAll"
                  >全选</el-checkbox
                >
                <el-option
                  v-for="item in wtArray"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">开始时间：</div>
            <div class="search-content">
              <el-date-picker
                v-model="startdate"
                type="datetime"
                size="mini"
                :disabled-date="disabledDate"
                placeholder="选择日期时间"
                popper-class="date-select"
              >
              </el-date-picker>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">结束时间：</div>
            <div class="search-content">
              <el-date-picker
                v-model="enddate"
                type="datetime"
                :disabled-date="disabledDate2"
                size="mini"
                placeholder="选择日期时间"
                popper-class="date-select"
              >
              </el-date-picker>
            </div>
          </div>
          <div class="search-item custom">
            <div class="lable">等间隔：</div>
            <div class="search-content" style="width: 530px">
              <el-radio-group v-model="interval">
                <el-radio
                  v-for="item in radioList"
                  :key="item.code"
                  size="mini"
                  :label="item.code"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </div>
          </div>
        </div>
        <div class="search-actions">
          <el-button size="mini" class="btn-search" @click="search"
            >曲线拟合</el-button
          >
          <!-- <el-button
            size="mini"
            :class="{ 'btn-active': isChartArea }"
            :disabled="!seriesData?.length"
            @click="funChartArea"
            >区域划分</el-button
          > -->
        </div>
      </div>
      <div class="search mg-b-8">
        <div class="search-items">
          <div class="search-item">
            <div class="lable">最大辐照强度：</div>
            <div class="search-content">
              <el-input-number
                v-model="maxs"
                size="mini"
                clearable
                :min="mins + 1"
                :max="5000"
                placeholder="请选择"
                popper-class="select"
              >
              </el-input-number>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">最小辐照强度：</div>
            <div class="search-content">
              <el-input-number
                v-model="mins"
                size="mini"
                clearable
                :min="0"
                :max="maxs - 1"
                placeholder="请选择"
                popper-class="select"
              >
              </el-input-number>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">最大功率：</div>
            <div class="search-content">
              <el-input-number
                v-model="maxpower"
                size="mini"
                clearable
                :min="minpower + 1"
                placeholder="请选择"
                popper-class="select"
              >
              </el-input-number>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">最小功率：</div>
            <div class="search-content">
              <el-input-number
                v-model="minpower"
                size="mini"
                :min="0"
                clearable
                placeholder="请选择"
                popper-class="select"
              >
              </el-input-number>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">多项式：</div>
            <div class="search-content">
              <el-select v-model="dimension" size="mini">
                <el-option
                  v-for="item in 10"
                  :key="item"
                  :value="item"
                  :label="item"
                />
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">拟合方式：</div>
            <div class="search-content">
              <el-select v-model="mode" size="mini">
                <el-option
                  v-for="item in selectList"
                  :key="item.code"
                  size="mini"
                  :value="item.code"
                  :label="item.name"
                />
              </el-select>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="height: calc(100% - 40px); padding-bottom: 10px">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="图表展示" name="2"> </el-tab-pane>
        <div style="height: 100%">
          <CurrentScatterChart
            ref="chartRef"
            width="100%"
            height="100%"
            :chartTitle="''"
            :xAxisData="xAxisData"
            :yAxisData="{ splitLine: { show: false } }"
            :seriesData="seriesData"
            :showLegend="true"
            :brushSelected="isChartArea"
            :dataSet="dataSet"
            @getSelected="funChartSelect"
            @closeBrush="
              (val) => {
                isChartArea = val;
              }
            "
          />
        </div>
      </el-tabs>
    </div>
    <el-dialog v-model="wtDialog" width="60%" top="120px" draggable>
      <template #title>
        <div class="dialog-title">
          <div class="title">设备功率点位</div>
        </div>
      </template>
      <el-tabs v-model="wtTab">
        <el-tab-pane label="数据" name="table">
          <el-table :data="wtData" row-key="id" :max-height="550">
            <el-table-column property="inverter" align="center" label="设备" />
            <el-table-column
              property="datetime"
              sortable
              width="200"
              align="center"
              label="时间"
            />
            <el-table-column
              property="S"
              sortable
              width="140"
              align="center"
              label="光照(W/m²)"
            />
            <el-table-column
              property="actualP"
              sortable
              width="140"
              align="center"
              label="功率(kW)"
            />
            <el-table-column
              property="T"
              sortable
              width="140"
              align="center"
              label="温度(℃)"
            />
            <el-table-column
              property="filter"
              sortable
              width="140"
              align="center"
              label="是否有用点"
            />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="故障" name="problem" disabled> </el-tab-pane>
        <el-tab-pane label="预警" name="warning" disabled> </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
// import ScatterLineChart from "@com/chart/combination/scatter-line-chart.vue";
import tableCop from "./components/table.vue";
import CurrentScatterChart from "./components/current-scatter-chart.vue";
import api1 from "@api/economic/index.js";
// import api from "@api/wisdomOverhaul/energy/index.js";
import dayjs from "dayjs";
import {
  getIntervers,
  getPowerFittingGF,
  getPowerHotChartGF,
  getPowerFittingChart,
  getPowerFittingTable,
  getPowerFittingSelectedChartGF,
} from "@/api/powerAnalyse.js";
export default {
  // 名称
  name: "powerHotAnalyse",

  // 使用组件
  components: {
    // ScatterLineChart,
    CurrentScatterChart,
    tableCop,
  },

  // 数据
  data() {
    return {
      activeTab: "2",
      checkList: [
        { name: "非并网", code: "isfbw" },
        { name: "非合理值", code: "isfhl" },
        { name: "并网后十分钟", code: "isbw" },
        { name: "停机前十分钟", code: "istj" },
        { name: "功率曲线偏差", code: "isglpc" },
      ],
      selectList: [
        { name: "单台拟合", code: 0 },
        { name: "合并拟合", code: 1 },
        // { name: "同名拟合", code: 2 },
      ],
      radioList: [
        { name: "一秒钟", code: 1 },
        { name: "一分钟", code: 60 },
        { name: "十分钟", code: 600 },
        { name: "十五分钟", code: 900 },
      ],
      isAsc: "asc",
      wpArray: [],
      wtArray: [],
      station: "",
      inverters: "",
      startdate: dayjs()
        // .add(-1, "month")
        .startOf("month")
        .format("YYYY-MM-DD HH:mm:ss"),
      enddate: dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
      interval: 600,
      maxs: 5000,
      mins: 0,
      maxpower: 2500,
      minpower: 0,
      checkedList: ["isfbw", "isfhl", "isbw", "istj", "isglpc"],
      dimension: 10,
      mode: 0,
      fittingId: "",
      seriesData: [],
      avgObj: {
        //平均cpz等
        title: "",
        cpavg: "",
        frequency: "",
        pcratio: "",
      },
      markDot: {
        //3-5 point点等
        pcl5: null,
        pcl10: null,
        pcl12: null,
        pcl25: null,
      },
      xAxisData: [],
      dataSet: "",
      isChartArea: true,
      tableShowId: "",
      tableColumn: [],
      tableLoading: false,
      tableName: "",
      tableData: [],
      wtTab: "table",
      wtDialog: false,
      wtData: [],
      isMultiple: false,
      checked: false,
      indeterminate: false,
    };
  },
  created() {
    this.getWp();
  },
  watch: {
    mode(val) {
      if (val == 0) {
        this.isMultiple = false;
        this.inverters =
          typeof this.inverters == "string"
            ? this.inverters
            : this.inverters.length
            ? this.inverters[0]
            : [];
      } else {
        this.isMultiple = true;
        this.inverters =
          typeof this.inverters == "string"
            ? [this.inverters]
            : [...this.inverters];
      }
    },
    inverters: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          if (this.isMultiple) {
            this.inverters = newVal;
            if (this.wtArray.length && this.inverters) {
              if (this.inverters.length === this.wtArray.length) {
                this.checked = true;
                this.indeterminate = false;
              } else if (this.inverters.length < this.wtArray.length) {
                this.checked = false;
                if (this.inverters.length != 0) {
                  this.indeterminate = true;
                }
                if (newVal.length == 0) {
                  this.$message.error("必须至少选择一项");
                  this.inverters = oldVal;
                }
              }
            }
          }
        });
      },
      immediate: true,
    },
  },
  // 函数
  methods: {
    selectAll() {
      if (this.checked) {
        this.wtArray.forEach((item) => {
          this.inverters.push(item.id);
        });
        this.inverters = [...new Set(this.inverters)];
        this.indeterminate = false;
      } else {
        this.inverters = [this.wtArray[0].id];
      }
    },
    // 时间选择器第一个禁用
    disabledDate(time) {
      if (this.enddate) {
        return time.getTime() > Date.parse(this.enddate);
      } else {
        return null;
      }
    },
    // 时间选择器第二个禁用
    disabledDate2(time) {
      if (this.startdate) {
        return time.getTime() < Date.parse(this.startdate);
      } else {
        return null;
      }
    },
    // 获取风场
    getWp(reGetWp) {
      api1
        .getWpList({
          type: "-2",
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.wpArray = res.data.data;
            this.station = res.data.data[0].id;
            this.getWt(this.station, reGetWp);
          }
        });
    },
    // 获取风机
    getWt(wpid, reGetWp) {
      if (wpid) {
        getIntervers({
          wpids: wpid,
        }).then(({ data: res }) => {
          if (res.code === 200) {
            this.wtArray = res.data;
            this.inverters = res.data.length
              ? this.isMultiple
                ? [res.data[0].id]
                : res.data[0].id
              : "";
            if (!reGetWp) {
              this.search();
            }
          }
        });
      }
    },
    //获取拟合id
    getChartId() {
      this.BASE.showLoading();
      this.activeTab = "2";
      let params = {
        station: this.station,
        inverters: this.isMultiple ? this.inverters.join(",") : this.inverters,
        startdate: dayjs(this.startdate).valueOf(),
        enddate: dayjs(this.enddate).valueOf(),
        interval: this.interval,
        maxs: this.maxs,
        mins: this.mins,
        maxpower: this.maxpower,
        minpower: this.minpower,
      };
      this.getChartData(params);
    },
    //清空数据
    clear() {
      this.fittingId = "";
      this.seriesData = [];
      this.avgObj = {
        //平均cpz等
        title: "",
        cpavg: "",
        frequency: "",
        pcratio: "",
      };
      this.markDot = {
        //3-5 point点等
        pcl5: null,
        pcl10: null,
        pcl12: null,
        pcl25: null,
      };
      this.xAxisData = [];
      this.dataSet = "";
    },
    //是否区域划分
    funChartArea() {
      this.BASE.showLoading();
      if (this.seriesData.length) {
        if (!this.isChartArea) {
          // 请求一下
          this.seriesData[0] = {
            ...this.seriesData[0],
            markLine: {
              symbol: "none",
              label: {
                show: false,
              },
              lineStyle: {
                color: "rgba(96,174,255, 1)",
              },
              data: [
                {
                  xAxis: 3,
                  valueIndex: 0,
                },
                {
                  xAxis: 5,
                  valueIndex: 0,
                },
                {
                  xAxis: 10,
                  valueIndex: 0,
                },
                {
                  xAxis: 12,
                  valueIndex: 0,
                },
                {
                  xAxis: 25,
                  valueIndex: 0,
                },
              ],
            },
            markArea: {
              label: {
                fontSize: 13,
                color: "#ccc",
                fontWeight: "normal",
                fontFamily: "Arial",
              },
              itemStyle: {
                color: "rgba(236,245,255, 0)",
              },
              emphasis: {
                itemStyle: {
                  color: "rgba(96,174,255, 0.5)",
                },
              },
              data: [
                [
                  {
                    name: `3~5m 偏差率: ${this.markDot.pcl5}%`,
                    xAxis: 3,
                  },
                  {
                    xAxis: 5,
                  },
                ],
                [
                  {
                    name: `5~10m 偏差率: ${this.markDot.pcl10}%`,
                    xAxis: 5,
                  },
                  {
                    xAxis: 10,
                  },
                ],
                [
                  {
                    name: `10~12m 偏差率: ${this.markDot.pcl12}%`,
                    xAxis: 10,
                  },
                  {
                    xAxis: 12,
                  },
                ],
                [
                  {
                    name: `12~25m 偏差率: ${this.markDot.pcl25}%`,
                    xAxis: 12,
                  },
                  {
                    xAxis: 25,
                  },
                ],
              ],
            },
          };
          this.isChartArea = true;
          this.BASE.closeLoading();
        } else {
          this.seriesData[0] = {
            ...this.seriesData[0],
            markLine: null,
            markArea: null,
          };
          this.isChartArea = false;
          this.BASE.closeLoading();
        }
      }
    },
    // // 获取表格数据
    // getTableData() {
    //   this.tableLoading = true;
    //   getPowerFittingTable({
    //     id: this.fittingId,
    //   }).then((res) => {
    //     if (res.code == 200) {
    //       this.tableColumn = res.data.title.map((o) => {
    //         return {
    //           prop: o.key,
    //           width: o.des === "时间" ? 100 : 80,
    //           label: o.des,
    //         };
    //       });
    //       this.tableData = res.data.data;
    //       this.$message.success(res.msg);
    //     }
    //     this.tableLoading = false;
    //   });
    // },
    // 获取图表数据
    getChartData(params) {
      getPowerHotChartGF(params).then((res) => {
        this.tableData = [];
        let chartRes = {};
        if (res.code == 200) {
          chartRes = res.data;
          this.dataSet = JSON.stringify([
            {
              source: chartRes.wyd,
            },
            {
              source: chartRes.yyd,
            },
          ]);
          this.seriesData = [
            {
              name: "拟合功率",
              type: "line",
              lineStyle: {
                width: 3,
                color: "#3d54be",
              },
              symbol: "line", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: chartRes.yydnh,
              xAxisIndex: 0,
            },

            {
              type: "effectScatter",
              showEffectOn: "emphasis",
              rippleEffect: {
                scale: 1,
              },
              itemStyle: {
                color: "#ccc",
              },
              name: "无用点",
              symbolSize: (data) => {
                return data.s ? (data.s > 10 ? 10 : data.s) : 4;
              },
              datasetIndex: 0,
              encode: {
                x: "x",
                y: "y",
              },
              xAxisIndex: 0,
              yAxisIndex: 0,
            },
            {
              type: "effectScatter",
              showEffectOn: "emphasis",
              rippleEffect: {
                scale: 1,
              },
              itemStyle: {
                color: [
                  {
                    type: "linear",
                    colorStops: [
                      { offset: 0, color: "#000" },
                      { offset: 0.2, color: "rgb(75,11,106)" },
                      { offset: 0.4, color: "rgb(210,70,69)" },
                      { offset: 0.6, color: "rgb(247,126,21)", },
                      { offset: 1, color: "rgb(249,252,156)" },
                    ],
                    globalCoord: false,
                  },
                ],
              },
              name: "有用点",
              symbolSize: (data) => {
                return data.s ? (data.s > 10 ? 10 : data.s) : 4;
              },
              datasetIndex: 1,
              encode: {
                x: "x",
                y: "y",
              },
              xAxisIndex: 0,
              yAxisIndex: 0,
            },
          ];
          this.$message.success(res.msg);
        } else {
          this.xAxisData = {};
          this.seriesData = {};
        }
        this.BASE.closeLoading();
      });
    },
    //拟合按钮
    search() {
      this.isChartArea = true;
      if (!this.station || !this.inverters) {
        this.BASE.showMsg({
          msg: "场站与风机为必选项",
        });
      } else {
        this.getChartId();
      }
    },
    async funChartSelect(batch) {
      const wDataArr = [];
      const yDataArr = [];
      let scatterls = [];
      let scatterhs = [];
      let dataSetObj = [];
      this.wtData = [];
      if (batch?.length && this.dataSet) {
        scatterls = batch[0].selected[1].dataIndex;
        scatterhs = batch[0].selected[2].dataIndex;
        if (scatterls?.length || scatterhs?.length) {
          dataSetObj = JSON.parse(this.dataSet);
          if (scatterls?.length) {
            for (const scatterIndex of scatterls) {
              wDataArr.push(dataSetObj[0].source[scatterIndex].k);
            }
          }
          if (scatterhs?.length) {
            for (const scatterIndex1 of scatterhs) {
              yDataArr.push(dataSetObj[1].source[scatterIndex1].k);
            }
          }
          const wtRes = await getPowerFittingSelectedChartGF({
            yk: yDataArr.join(","),
            wk: wDataArr.join(","),
          });
          if (wtRes.code === 200) {
            let id = 1;
            const tempArr = []; //用于以风机id 聚合dataArr
            if (wtRes.data?.length) {
              for (const data of wtRes.data) {
                if (tempArr.length) {
                  const findIndex = tempArr.findIndex(
                    (o) => o.wtId === data.wtId
                  );
                  if (findIndex !== -1) {
                    if (!tempArr[findIndex].children) {
                      tempArr[findIndex].children = [];
                    }
                    tempArr[findIndex].children.push({
                      ...data,
                      id: id,
                      filter: data.filter === 0 ? "是" : "否",
                    });
                    id++;
                  } else {
                    tempArr.push({
                      ...data,
                      id: id,
                      filter: data.filter === 0 ? "是" : "否",
                    });
                    id++;
                  }
                } else {
                  tempArr.push({
                    ...data,
                    id: id,
                    filter: data.filter === 0 ? "是" : "否",
                  });
                  id++;
                }
              }
              this.wtDialog = true;
              this.$nextTick(() => {
                this.wtTab = "table";
                this.wtData = tempArr;
              });
            }
          }
        }
      }
    },
  },

  unmounted() {},
};
</script>

<style lang="less" scoped>
.draught-fan-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  .form-wrapper ::v-deep {
    .el-checkbox__input {
      display: block;
    }
    .el-input-number {
      width: 100%;
      .el-input-number__decrease,
      .el-input-number__increase {
        background: rgba(67, 81, 107, 0.2) !important;

        position: absolute;
        z-index: 10;
        border: 0;
        // height: 33px;
        // line-height: 33px;
        &:hover {
          color: #05be4c;
        }
      }
    }
    .el-date-editor {
      width: 100%;
    }
    .el-select {
      width: 100%;
      .el-select__tags {
        max-width: 140px !important;
        .el-select__tags-text {
          max-width: 62px !important;
        }
      }
    }
    .el-radio-group {
      width: 100%;
      display: flex;
      .el-radio {
        flex: 1;
      }
    }
    .search {
      display: flex;
      align-items: center;
      .search-items {
        display: flex;
        align-items: center;
        .search-item {
          width: 296px;
          display: flex;
          align-items: center;
          margin-right: 10px;
          .lable {
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #b3b3b3;
            margin-right: 5px;
            width: 84px;
            text-align: right;
            white-space: nowrap;
          }
          .search-content {
            flex: 1;
          }
          &:nth-last-child(1) {
            margin-right: 0;
          }
        }
        .custom {
          width: auto;
        }
      }
      .search-actions {
        top: 152px;
        right: 75px;
        position: absolute;
        z-index: 88;
        .el-button {
          background-color: rgba(5, 187, 76, 0.3);
          border: 1px solid #3b6c53;
          color: #b3b3b3;
          font-size: 14px;
          border: none;
          width: 108px;
          min-height: 25px !important;

          &.btn-search:hover {
            background-color: rgba(5, 187, 76, 0.6);
            color: #ffffff;
          }
        }
        .btn-active {
          background-color: rgba(5, 187, 76, 0.6);
          color: #ffffff;
        }
      }
      &:nth-last-child(1) {
        justify-content: space-between;
      }
    }
  }
  .el-tabs ::v-deep {
    height: 100%;
    .el-tabs__item {
      color: #b3b3b3;
    }
    .el-tabs__nav-wrap::after {
      background-color: #14221f;
    }
    .el-tabs__active-bar {
      background-color: #05bb4c;
    }
    .el-tabs__item.is-active,
    .el-tabs__item:hover {
      color: #05bb4c;
    }
    .el-tabs__content {
      height: calc(100% - 40px);
    }
  }
}
</style>
