<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="wtIds"
                clearable
                size="mini"
                :multiple="isMultiple"
                collapse-tags
                placeholder="请选择"
                popper-class="select"
              >
                <el-option
                  v-for="item in wtArray"
                  :key="item.id"
                  :value="item.id"
                  :label="item.nemCode"
                />
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <div class="lable">开始时间：</div>
            <div class="search-content">
              <el-date-picker
                v-model="st"
                type="date"
                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="et"
                type="date"
                :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>
      <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="25"
                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="3"
                :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="maxp"
                size="mini"
                clearable
                :min="minp + 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="minp"
                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 class="search mg-b-8">
        <div class="search-items">
          <div class="search-item custom">
            <div class="lable">筛选条件：</div>
            <div class="search-content">
              <el-checkbox-group v-model="checkedList" :min="1">
                <el-checkbox
                  v-for="item in checkList"
                  :key="item.code"
                  :label="item.code"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-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>
    <div style="height: calc(100% - 125px); padding-bottom: 10px">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="表格数据" name="1"> </el-tab-pane>
        <el-tab-pane label="图表展示" name="2"> </el-tab-pane>
        <table-cop
          v-show="activeTab === '1'"
          :data="tableData"
          :loading="tableLoading"
          :column="tableColumn"
          height="calc(100% - 20px)"
          :tableId="tableShowId"
          :tableName="tableName"
        ></table-cop>
        <div v-show="activeTab === '2'" style="height: 100%">
          <CurrentScatterChart
            ref="chartRef"
            width="100%"
            height="100%"
            :chartTitle="
              avgObj.title +
              '&nbsp;&nbsp;' +
              '平均Cp值：' +
              avgObj.cpavg +
              '； 静风频率：' +
              avgObj.frequency +
              '%； 曲线偏差率：' +
              avgObj.pcratio +
              '%'
            "
            :xAxisData="xAxisData"
            :yAxisData="{ splitLine: { show: false } }"
            :seriesData="seriesData"
            :brushSelected="!isChartArea"
            :showLegend="true"
            :dataSet="dataSet"
            @getSelected="funChartSelect"
          />
        </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="wtId" align="center" label="风机" />
            <el-table-column
              property="time"
              sortable
              width="200"
              align="center"
              label="时间"
            />
            <el-table-column
              property="speed"
              sortable
              width="140"
              align="center"
              label="风速(m/s)"
            />
            <el-table-column
              property="power"
              sortable
              width="140"
              align="center"
              label="功率(kW)"
            />
            <el-table-column
              property="rr"
              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 {
  getPowerFittingId,
  getPowerFittingChart,
  getPowerFittingTable,
  getPowerFittingSelectedChart,
} from "@/api/powerAnalyse.js";
export default {
  // 名称
  name: "healthPowerCurve",

  // 使用组件
  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: "",
      wtIds: "",
      st: dayjs().add(-1, "month").startOf("day").format("YYYY-MM-DD HH:mm:ss"),
      et: dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
      interval: 600,
      maxs: 25,
      mins: 3,
      maxp: 2500,
      minp: 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: false,
      tableShowId: "",
      tableColumn: [],
      tableLoading: false,
      tableName: "",
      tableData: [],
      wtTab: "table",
      wtDialog: false,
      wtData: [],
    };
  },

  // 函数
  methods: {
    // 时间选择器第一个禁用
    disabledDate(time) {
      if (this.et) {
        return time.getTime() > Date.parse(this.et);
      } else {
        return null;
      }
    },
    // 时间选择器第二个禁用
    disabledDate2(time) {
      if (this.st) {
        return time.getTime() < Date.parse(this.st);
      } else {
        return null;
      }
    },
    // 获取风场
    getWp(reGetWp) {
      api1
        .getWpList({
          type: "-1",
        })
        .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) {
        api1
          .getWtList({
            wpId: wpid,
          })
          .then((res) => {
            if (res.code === 200) {
              this.wtArray = res.data;
              this.wtIds = this.isMultiple ? [res.data[0].id] : res.data[0].id;
              if (!reGetWp) {
                this.search();
              }
            }
          });
      }
    },
    //获取拟合id
    getChartId() {
      this.BASE.showLoading();
      let obj = {
        isfbw: false,
        isfhl: false,
        isbw: false,
        istj: false,
        isglpc: false,
      };
      this.checkedList.length &&
        this.checkedList.forEach((i) => {
          for (let key in obj) {
            if (key == i) {
              obj[key] = true;
            }
          }
        });
      let params = {
        station: this.station,
        wtIds: this.isMultiple ? this.wtIds.join(",") : this.wtIds,
        st: dayjs(this.st).valueOf(),
        et: dayjs(this.et).valueOf(),
        interval: this.interval,
        maxs: this.maxs,
        mins: this.mins,
        maxp: this.maxp,
        minp: this.minp,
        ...obj,
        dimension: this.dimension,
        mode: this.mode,
      };
      getPowerFittingId(params).then((res) => {
        if (res.code == 200) {
          this.fittingId = res.data.id;
          this.getChartData();
          this.getTableData();
        } else {
          this.BASE.closeLoading();
          this.$message.error(res.msg);
          this.clear();
        }
      });
    },
    //清空数据
    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() {
      getPowerFittingChart({
        id: this.fittingId,
      }).then((res) => {
        if (res.code == 200) {
          let chartRes = {
            scatterhs: [[]],
            scatterls: [[]],
            sjgl: [[]],
            llgl: [[]],
            cpz: [[]],
          };
          chartRes = res.data;
          this.markDot.pcl5 = chartRes.obj.pc5ratio;
          this.markDot.pcl10 = chartRes.obj.pc10ratio;
          this.markDot.pcl12 = chartRes.obj.pc12ratio;
          this.markDot.pcl25 = chartRes.obj.pc25ratio;
          this.avgObj.title =
            this.mode == 0
              ? chartRes.obj.code
              : chartRes.obj.path
                  .substring(
                    chartRes.obj.path.indexOf(chartRes.obj.station + "_") +
                      (chartRes.obj.station + "_").length
                  )
                  .split("_")[0];
          this.avgObj.cpavg = Number(chartRes.obj.cpavg).toFixed(2);
          this.avgObj.frequency = Number(chartRes.obj.frequency).toFixed(2);
          this.avgObj.pcratio = Number(chartRes.obj.pcratio).toFixed(2);
          this.dataSet = JSON.stringify([
            {
              source: chartRes.wyd,
            },
            {
              source: chartRes.yyd,
            },
          ]);
          this.seriesData = [
            {
              name: "拟合功率",
              type: "line",
              symbol: "line", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: chartRes.sjgl,
              xAxisIndex: 0,
            },
            {
              name: "保证功率",
              type: "line",
              symbol: "line", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: chartRes.llgl,
              xAxisIndex: 0,
            },
            {
              type: "effectScatter",
              showEffectOn: "emphasis",
              rippleEffect: {
                scale: 1,
              },
              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,
              },
              name: "有用点",
              symbolSize: (data) => {
                return data.s ? (data.s > 10 ? 10 : data.s) : 4;
              },
              datasetIndex: 1,
              encode: {
                x: "x",
                y: "y",
              },
              xAxisIndex: 0,
              yAxisIndex: 0,
            },
            {
              name: "Cp值",
              type: "line",
              symbol: "line", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: chartRes.cpz,
              xAxisIndex: 0,
              yAxisIndex: 1,
            },
          ];
          this.$message.success(res.msg);
        }
        this.BASE.closeLoading();
      });
    },
    //拟合按钮
    search() {
      this.isChartArea = false;
      if (!this.station || !this.wtIds || !this.wtIds.length) {
        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[2].dataIndex;
        scatterhs = batch[0].selected[3].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 scatterIndex of scatterhs) {
              yDataArr.push(dataSetObj[1].source[scatterIndex].k);
            }
          }
          const wtRes = await getPowerFittingSelectedChart({
            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;
              });
            }
          }
        }
      }
    },
  },

  created() {
    this.getWp();
  },

  watch: {
    mode(val) {
      if (val == 0) {
        this.isMultiple = false;
        this.wtIds =
          typeof this.wtIds == "string"
            ? this.wtIds
            : this.wtIds.length
            ? this.wtIds[0]
            : [];
      } else {
        this.isMultiple = true;
        this.wtIds = [this.wtIds];
      }
    },
  },

  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,
    .el-select {
      width: 100%;
    }
    .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: 65px;
            white-space: nowrap;
          }
          .search-content {
            flex: 1;
          }
          &:nth-last-child(1) {
            margin-right: 0;
          }
        }
        .custom {
          width: auto;
        }
      }
      .search-actions {
        .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>
