<template>
  <div>
    <el-dialog
      class="dialogs"
      width="85%"
      top="120px"
      v-model="dialogCurveVisible"
      :show-close="true"
      @close="handleClose"
    >
      <template #title>
        <div class="dialog-title">
          <img class="dialog-title-img" src="@assets/imgs/dialog-title.png" />
          <div class="title">{{ chartName }}</div>
          <!--                    <i class="el-icon-full-screen"  @click="c"></i>-->
        </div>
      </template>
      <div class="dialog-body" style="height: 480px; width: 100%">
        <div style="margin-top: -8px; margin-bottom: 20px">
          <div
            style="
              height: 20px;
              line-height: 20px;
              flex-direction: row;
              align-items: center;
              display: flex;
            "
          >
            <div class="qushi-form">
              <div class="station">
                开始时间
                <div style="margin-left: 5px; margin-right: 10px">
                  <el-date-picker
                    v-model="starttime"
                    type="datetime"
                    placeholder="选择日期"
                    popper-class="date-select"
                    format="YYYY-MM-DD HH:mm:ss"
                  >
                  </el-date-picker>
                </div>
              </div>
              <div class="station">
                结束时间
                <div style="margin-left: 5px; margin-right: 10px">
                  <el-date-picker
                    v-model="endtime"
                    type="datetime"
                    popper-class="date-select"
                    placeholder="选择日期"
                    format="YYYY-MM-DD HH:mm:ss"
                  >
                  </el-date-picker>
                </div>
              </div>
              <div class="station">
                时间间隔（秒）
                <div>
                  <el-input-number
                    size="medium"
                    v-model="numgap"
                    :precision="0"
                  ></el-input-number>
                </div>
              </div>
              <el-button
                style="margin-left: 15px"
                round
                :disabled="timerFlag"
                size="mini"
                class="searchColor"
                @click="throttleSearch"
                >查询
              </el-button>
            </div>
            <div class="qushi-tools">
              <el-button
                class="customColor"
                round
                size="mini"
                type="primary"
                @click="showYsetDialog"
                icon="el-icon-edit"
                >自定义多坐标
              </el-button>

              <el-tooltip
                class="item"
                effect="dark"
                content="导出"
                placement="bottom"
              >
                <el-button
                  class="updownTit"
                  round
                  size="mini"
                  type="primary"
                  @click="exportDatas"
                >
                  <i class="svg-icon svg-icon-sm svg-icon-white">
                    <SvgIcon svgid="svg-dataout"></SvgIcon
                  ></i>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <img
          class="dialog-img"
          style="bottom: -166px"
          src="@assets/imgs/dialog.png"
        />
        <windChartCom
          ref="windChartCom"
          :height="chartHeight"
          :list="chartsData"
          :interval="intervalgap"
          :units="units"
          :unitDatas="unitDatas"
          :showLegend="false"
          :showXdata="false"
          :animate="false"
          :ratio="1000"
        />
      </div>
      <div class="economicTable1 mentues met" style="margin-top: 10px">
        <el-table
          :data="detailsValue"
          class="table-fixed tables"
          ref="multipleTable"
          :cell-style="tagCellStyle"
          height="230px"
          fit
          stripe
        >
          <el-table-column
            align="center"
            v-for="item in tableHeader"
            :key="item.code"
            :prop="item.code"
            :label="item.title"
            :width="item.width ? item.width : ''"
            show-overflow-tooltip
          >
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="name"
            label="指标名称"
            width="500"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="tagName"
            label="描述"
            width="400"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="dateTime"
            label="快照时间"
            width="200"
          >
          </el-table-column>
          <el-table-column align="center" prop="value" label="快照值">
          </el-table-column>
          <el-table-column align="center" prop="minvalue" label="最小值">
          </el-table-column>
          <el-table-column align="center" prop="maxvalue" label="最大值">
          </el-table-column>
          <el-table-column align="center" prop="avgvalue" label="平均值">
          </el-table-column> -->
          <el-table-column
            prop="showy"
            label="操作"
            align="center"
            width="110"
            style="cursor: pointer"
          >
            <template v-slot="scoped">
              <i
                style="cursor: pointer"
                class="svg-icon svg-icon-sm svg-icon-gray checkIcon"
              >
                <SvgIcon
                  :svgid="scoped.row.showy ? 'svg-show' : 'svg-hide'"
                ></SvgIcon
              ></i>
              <el-switch
                v-model="scoped.row.showy"
                @change="curveSwitchData(scoped.row)"
                inactive-color="rgba(0,0,0,0)"
                active-color="rgba(0,0,0,0)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog
      class="ysetDialog"
      width="43%"
      v-model="ysetDialogVisible"
      :show-close="true"
    >
      <template #title>
        <div class="dialog-title">
          <img class="dialog-title-img" src="@assets/imgs/dialog-title.png" />
          <div class="title">{{ ysetName }}</div>
        </div>
      </template>
      <div class="dialog-body mentuese metse" style="height: 320px">
        <el-table
          :data="tagDatas"
          class="table-fixed tables"
          ref="multipleTable"
          :cell-style="tagCellStyle2"
          height="100%"
          style="width: 100%"
          fit
          empty-text="暂无数据"
          stripe
        >
          <el-table-column
            prop="tagName"
            label="指标名称"
            align="center"
            fixed
            width="420"
          >
          </el-table-column>
          <el-table-column
            prop="minvalue"
            label="最小值"
            align="center"
            fixed
            width="180"
          >
            <template v-slot="scoped">
              <el-input-number
                size="small"
                v-model="scoped.row.min"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxvalue"
            label="最大值"
            align="center"
            fixed
            width="180"
          >
            <template v-slot="scoped">
              <el-input-number
                size="small"
                v-model="scoped.row.max"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <img
        class="dialog-img"
        style="position: absolute; bottom: 50px; right: 0"
        src="@assets/imgs/dialog.png"
      />
      <el-row
        class="footerButton changeButton"
        style="text-align: center; margin-top: 20px"
      >
        <el-button
          size="medium"
          style="width: 125px"
          round
          @click="cancelMultiys()"
          >取消多坐标</el-button
        >
        <el-button type="primary" size="medium" round @click="saveEditTagInfo()"
          >确定</el-button
        >
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  GetWtPoints,
  GetWpPoints,
  GetPointFitting,
  GetSubPoints,
  GetProPoints,
} from "@/api/points/index.js";
import SvgIcon from "@com/coms/icon/svg-icon.vue";
import dayjs from "dayjs";
import windChartCom from "./lineCharts.vue";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
export default {
  name: "changeCheck", //趋势对比
  components: {
    windChartCom,
    SvgIcon,
  },
  props: {
    data: {
      type: String,
      required: true,
    },
    chartName: {
      type: String,
      default: "对比曲线",
    },
    index: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      tableHeader: [
        { title: "指标名称", code: "name", width: 500 },
        { title: "描述", code: "tagName", width: 400 },
        { title: "快照时间", code: "dateTime", width: 200 },
        { title: "快照值", code: "value" },
        { title: "最大值", code: "maxvalue" },
        { title: "最小值", code: "minvalue" },
        { title: "平均值", code: "avgvalue" },
      ],
      value: true,
      dialogVisibles: false,
      stse: [],
      sts: [],
      statiomName: [],
      leng: "",
      x: 500,
      y: 250,
      starttime: new Date(),
      endtime: "",
      stationTit: null,
      dragging: false,
      currentX: 50,
      currentY: 0,
      initialX: 0,
      initialY: 0,
      tableShow: true,
      tmp: [],
      detailsValue: [],
      numgap: 900,
      intervalgap: 7,
      tmpData: "",
      units: [],
      color: [
        "#1985de",
        "#ff8300",
        "#06a746",
        "#3eede7",
        "#eb0f7c",
        "#dfdc0a",
        "#de0feb",
        "#cca4e3",
      ],
      unitDatas: [{ flag: false, min: 0, max: 0, codex: 0 }],
      tagDatas: [],
      handleSwitch: false,
      chartsData: [],
      chartsDataAll: [],
      dialogCurveVisible: false,
      ysetDialogVisible: false,
      ysetName: "自定义多坐标",
      visibles: "",
      cilent: "",
      dialogFull: false,
      chartHeight: "420px",
      tagNames: "",
      pointIds: "",
      searchFlag: false, //判断是否重置多坐标
      changeYset: false, //是否设置过多坐标
      ined: 1, //查询测点类型
      timerFlag: false,
    };
  },
  created() {
    this.starttime = new Date(new Date().setHours(0, 0, 0, 0));
    this.endtime = new Date();
  },
  methods: {
    // 防止按钮频繁点击
    throttleSearch() {
      this.timerFlag = true;
      setTimeout(() => {
        this.searchChartData();
        this.timerFlag = false;
      }, 2000);
    },
    // 指标样式
    tagCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row.showy) {
        return { color: "#525252", fontSize: "11px" };
      }
      if ((columnIndex == 0 || columnIndex == 1) && row.showy) {
        return { color: this.color[rowIndex], fontSize: "13px" };
      } else {
        return { padding: "6px 0px" };
      }
    },
    // 指标样式
    tagCellStyle2({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        return { color: this.color[rowIndex] + "!important", fontSize: "13px" };
      } else {
        return { padding: "6px 0px" };
      }
    },
    // 取消多坐标
    cancelMultiys() {
      this.searchFlag = false;
      this.units = [];
      this.unitDatas = [];
      this.tagDatas.forEach((value, index) => {
        if (index == 0) {
          this.units.push(this.chartsData[0].title);
          this.unitDatas.push({ flag: false, min: 0, max: 0, codex: 0 });
        }
      });
      this.chartsData.forEach((value2, index2) => {
        value2.yAxisIndex = 0;
      });
      this.ysetDialogVisible = false;
      this.changeYset = false;
    },
    // 展示多坐标弹窗
    showYsetDialog() {
      var maxy = this.$refs.windChartCom.childMethod(0);
      this.tagDatas.forEach((value, index) => {
        if (value.showy) {
          value.max = this.$refs.windChartCom.childMethod(index);
        } else {
          value.max = maxy;
        }
      });
      this.ysetDialogVisible = true;
      this.changeYset = true;
    },
    // 保存多坐标信息
    saveEditTagInfo() {
      if (this.changeYset) {
        this.units = [];
        this.unitDatas = [];
        this.chartsData.forEach((value, index) => {
          value.yAxisIndex = 0;
        });
        this.tagDatas.forEach((value, index) => {
          if (index == 0) {
            this.units.push(this.chartsData[0].title);
            this.unitDatas.push({
              flag: true,
              min: value.min,
              max: value.max,
              codex: 0,
            });
          }
          if (index > 0) {
            this.units.push(value.tagName);
            this.unitDatas.push({
              flag: true,
              min: value.min,
              max: value.max,
              codex: index,
            });
            this.chartsData.forEach((value2, index2) => {
              if (value2.title == value.tagName) {
                value2.yAxisIndex = index;
              }
            });
          }
        });

        this.changeYset = true;
      } else {
        this.changeYset = false;
      }
      this.ysetDialogVisible = false;
    },
    exportDatas() {
      let tableHeader = this.tableHeader.map((item) => item.title);
      let tableKey = this.tableHeader.map((item) => item.code);
      outExportExcel(
        tableHeader,
        tableKey,
        this.detailsValue,
        "对比曲线导出数据"
      );
    },
    c() {
      this.dialogFull ? (this.dialogFull = false) : (this.dialogFull = true);
    },
    curveSwitchData(e) {
      this.value = e.showy;

      var option = "{";
      this.detailsValue.forEach((value, index) => {
        option += "'" + value.tagName + "'" + ":" + value.showy + ",";
      });
      option = option.substring(0, option.length - 1);
      option += "}";
      var json = eval("(" + option + ")");
      this.$refs.windChartCom.changDateVisible(json);
    },
    // 弹窗首次加载对比曲线
    openCurvDatas(valse, ined, wtid) {
      this.ined = ined;
      this.searchFlag = false;
      this.changeYset = false;
      this.wtid = wtid;
      this.dialogCurveVisible = true;
      this.detailsValue = [];
      this.tagDatas = [];
      this.units = [];
      this.unitDatas = [];
      this.numgap = 900;
      this.intervalgap = 7;
      let tagNames = "";
      this.tmpData = valse;
      this.tmpData.forEach((value, index) => {
        tagNames += value.sts + ",";
      });
      this.tagNames = tagNames.substring(0, tagNames.length - 1);
      if (ined == 1) {
        this.getWpPoints(wtid);
      } else if (ined == 2) {
        this.getWtPoints(wtid);
      } else if (ined == 3) {
        this.getPoints(this.tagNames);
      } else if (ined == 4) {
        this.getSubPoints(wtid);
      } else if (ined == 5) {
        this.getProPoints(wtid);
      }
    },
    // 查询设备测点
    getWtPoints(wtid) {
      GetWtPoints({
        wtid,
        uniformcodes: this.tagNames,
      }).then((res) => {
        this.tmpData.forEach((item) => {
          res.data.data.forEach((i) => {
            if (item.sts == i.uniformCode) {
              item.sts = i.nemCode;
              item.statiomName = i.name;
            }
          });
          // if()
        });
        let pointIds = "";
        res.data.data.forEach((value) => {
          pointIds += value.nemCode + ",";
        });
        pointIds = pointIds.substring(0, pointIds.length - 1);
        this.getPoints(pointIds);
      });
    },
    // 查询场站测点
    getWpPoints(wpid) {
      GetWpPoints({
        wpid,
        uniformcodes: this.tagNames,
      }).then((res) => {
        let resData = res.data.data.map((item) => {
          if (item == null) {
            return {};
          } else {
            return { ...item };
          }
        });
        let pointIds = "";
        this.tmpData.forEach((item) => {
          resData.forEach((i) => {
            if (Object.keys(i).length) {
              if (item.sts == i.uniformCode) {
                item.sts = i.nemCode;
                item.statiomName = i.name;
              }
            } else {
              item.sts = "";
              item.statiomName = "";
            }
          });
        });

        resData.forEach((value) => {
          if (value == {}) {
            value.nemCode = "";
          }
          pointIds += value.nemCode + ",";
        });
        pointIds = pointIds.substring(0, pointIds.length - 1);
        this.getPoints(pointIds);
      });
    },
    // 查询调度场站测点
    getSubPoints(wpid) {
      GetSubPoints({
        wpid,
        uniformcodes: this.tagNames,
      }).then((res) => {
        this.tmpData.forEach((item) => {
          res.data.data.forEach((i) => {
            if (item.sts == i.uniformCode) {
              item.sts = i.nemCode;
              item.statiomName = i.name;
            }
          });
        });
        let pointIds = "";
        res.data.data.forEach((value) => {
          pointIds += value.nemCode + ",";
        });
        pointIds = pointIds.substring(0, pointIds.length - 1);
        this.getPoints(pointIds);
      });
    },
    // 查询场站期次测点
    getProPoints(wpid) {
      GetProPoints({
        wpid,
        uniformcodes: this.tagNames,
      }).then((res) => {
        this.tmpData.forEach((item) => {
          res.data.data.forEach((i) => {
            if (item.sts == i.uniformCode) {
              item.sts = i.nemCode;
              item.statiomName = i.name;
            }
          });
        });
        let pointIds = "";
        res.data.data.forEach((value) => {
          pointIds += value.nemCode + ",";
        });
        pointIds = pointIds.substring(0, pointIds.length - 1);
        this.getPoints(pointIds);
      });
    },
    // 查询测点
    getPoints(pointIds) {
      GetPointFitting({
        begin: dayjs(this.starttime).format("YYYY-MM-DD HH:mm:ss"),
        end: dayjs(this.endtime).format("YYYY-MM-DD HH:mm:ss"),
        interval: this.numgap,
        pointIds,
      }).then((res) => {
        if (res.data.data.length) {
          let powerLineChartData = [];
          let resData = res.data.data;
          resData.forEach((value, index) => {
            var option = {
              title:
                this.ined == 3
                  ? this.tmpData[index].stse + this.tmpData[index].statiomName
                  : this.tmpData[index].statiomName,
              tagName: this.tmpData[index].sts,
              yAxisIndex: 0,
              value: value
                ? value.map((item) => {
                    return {
                      dateTime: item.pointTime,
                      value: item.pointValueInDouble,
                    };
                  })
                : [],
              noRatio: true,
            };
            powerLineChartData.push(option);
          });
          this.chartsData = powerLineChartData;
          this.chartsDataAll = JSON.parse(JSON.stringify(this.chartsData));
          this.dialogCurveVisible = true;

          let tagDatas = [];
          resData.forEach((value, index) => {
            var option = {
              tagName:
                this.ined == 3
                  ? this.tmpData[index].stse + this.tmpData[index].statiomName
                  : this.tmpData[index].statiomName,
              min: 0,
              max: 0,
              showy: false,
            };
            tagDatas.push(option);
          });
          tagDatas[0].showy = true;
          if (!this.searchFlag) {
            this.units = [this.chartsData[0].title];
            this.unitDatas.push({ flag: false, min: 0, max: 0, codex: 0 });
            this.tagDatas = tagDatas;
          } else {
            this.saveEditTagInfo();
          }
          resData.forEach((value, index) => {
            var option;
            if (value != null && value.length > 0) {
              let dateTime = null;
              let dateValue = null;
              let vals = [];
              for (var i = value.length - 1; i >= 0; i--) {
                if (value[i].pointValueInDouble !== "") {
                  dateTime = dayjs(value[i].pointTime).format(
                    "YYYY-MM-DD HH:mm:ss"
                  );
                  dateValue = Number(value[i].pointValueInDouble).toFixed(2);
                  break;
                }
              }
              for (var j = value.length - 1; j >= 0; j--) {
                if (value[j].pointValueInDouble !== "") {
                  vals.push(value[j].pointValueInDouble);
                }
              }

              let maxValue = vals
                .sort((i, j) => i - j)
                .reverse()[0]
                .toFixed(2);
              let minValue = vals.sort((i, j) => i - j)[0].toFixed(2);
              let totalValue = 0;
              for (var k = 0; k < vals.length; k++) {
                totalValue += vals[k];
              }
              let avgValue = (totalValue / vals.length).toFixed(2);
              option = {
                name: this.tmpData[index].sts,
                tagName:
                  this.ined == 3
                    ? this.tmpData[index].stse + this.tmpData[index].statiomName
                    : this.tmpData[index].statiomName,
                showy: true,
                dateTime: dateTime,
                value: dateValue,
                maxvalue: maxValue,
                minvalue: minValue,
                avgvalue: avgValue,
              };
            } else {
              option = {
                name: this.tmpData[index].sts,
                tagName:
                  this.ined == 3
                    ? this.tmpData[index].stse + this.tmpData[index].statiomName
                    : this.tmpData[index].statiomName,
                showy: true,
                dateTime: "-",
                value: "-",
                maxvalue: "-",
                minvalue: "-",
                avgvalue: "-",
              };
            }
            this.detailsValue.push(option);
          });
        }
      });
    },
    sortFun(a, b) {
      console.log(a, b, Number.parseInt(a - b));
      return parseInt(a) - parseInt(b);
    },
    // 点击查询按钮查询对比曲线
    searchChartData() {
      this.searchFlag = true;
      this.chartsData = [];
      this.detailsValue = [];
      if (this.ined == 1) {
        this.getWpPoints(this.wtid);
      } else if (this.ined == 2) {
        this.getWtPoints(this.wtid);
      } else if (this.ined == 3) {
        this.getPoints(this.tagNames);
      } else if (this.ined == 4) {
        this.getSubPoints(this.wtid);
      } else if (this.ined == 5) {
        this.getProbPoints(this.wtid);
      }
    },
    // 关闭弹窗事件
    handleClose() {
      this.tmpData = [];
      this.tagNames = "";
      this.searchFlag = false;
      this.changeYset = false;
      this.tagDatas = [];
      this.chartsData = [];
      this.detailsValue = [];
      this.starttime = new Date(new Date().setHours(0, 0, 0, 0));
      this.endtime = new Date();
      this.numgap = 900;
    },
  },
  mounted() {},
  computed: {},
};
</script>
<style lang="less" scoped>
.footerButton {
  justify-content: right;

  .el-button:first-child {
    width: 108px;
    background-color: rgba(0, 70, 199, 0.2) !important;
    color: #b3b3b3;
    border-color: transparent;
  }

  .el-button:last-of-type {
    width: 108px;
    background: rgba(0, 70, 199, 0.4) !important;
  }
}
.checkIcon {
  position: absolute;
  left: 45px;
  top: 8px;
  font-size: 20px;
  color: #929396;
}

.searchColor {
  background: rgba(0, 70, 199, 0.4);
  color: #b3b3b3;
  font-size: 14px;
  border: none;
  width: 108px;
  min-height: 25px !important;

  &:hover {
    background-color: rgba(0, 70, 199, 0.5);
    color: #ffffff;
  }
}
.qushi-form {
  flex: 0 0 auto;
  display: flex;
  align-items: center;

  .station {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #b3b3b3;
    margin-left: 40px;

    /deep/ .el-input__suffix {
      right: -68px;
    }
    /deep/ .el-input__prefix {
      left: 0;
    }

    /deep/ .el-input__inner {
      width: 190px;
    }
    .el-input-number {
      width: 190px;

      /deep/ .el-input-number__decrease,
      /deep/ .el-input-number__increase {
        position: absolute;
        z-index: 10;
        border: 0;
        height: 25px;
        line-height: 25px;
        top: 5px;
      }
    }
  }
}
.qushi-tools {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  .customColor {
    border-radius: 0 !important;
    background: url("../../assets/imgs/buttonBack.png") no-repeat;
    background-position: 7px;
  }
  .updownTit {
    padding: 0 !important;
    width: 30px !important;
    min-height: 28px !important;
    border-radius: 4px;
    border: 1px solid rgba(225, 225, 225, 0.3) !important;
    border-top: 1px solid #ffffff !important;
    border-bottom: 0;
    box-shadow: 0 0 22px rgba(255, 255, 255, 0.2) inset !important;
    //border-image: linear-gradient(321deg, rgba(225, 225, 225,2 ),  rgba(5, 187, 76, 0.5)) 1 1 !important;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 0.5),
      rgba(0, 0, 0, 0.5),
      rgba(0, 0, 0, 1)
    );
  }
}
</style>
