<template>
  <el-scrollbar height="92vh">
    <div class="query mg-b-8">
      <div class="query-items">
        <div class="query-item" style="width: 230px">
          <div class="lable">场站：</div>
          <div class="search-input">
            <el-select
              v-model="station"
              placeholder="请选择"
              popper-class="select"
              @change="stationChange"
            >
              <el-option
                v-for="item in ChangZhan"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="query-item" style="width: 230px">
          <div class="lable">故障类型：</div>
          <div class="search-input">
            <el-select
              v-model="widget"
              multiple
              collapse-tags
              clearable
              placeholder="请选择"
              popper-class="select"
            >
              <el-option @click="checkAll" :class="active ? 'green' : ''">
                全选
              </el-option>
              <el-option
                v-for="item in widgetArr"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="query-item" style="width: 230px">
          <div class="lable">风机型号：</div>
          <div class="search-input">
            <el-select
              v-model="model"
              multiple
              collapse-tags
              clearable
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in fjxh"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="query-item" style="width: 230px">
          <div class="lable">样本类型：</div>
          <div class="search-input">
            <el-select
              v-model="category"
              collapse-tags
              clearable
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in categorys"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">时间：</div>
          <div class="search-input">
            <el-date-picker
              v-model="time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="query-actions" style="margin-left: 10px">
          <button class="btn" @click="list">查询</button>
          <button class="btn" style="margin-left: 6px" @click="add">
            新增
          </button>
          <el-upload
            style="display: inline; margin-left: 6px"
            :show-file-list="false"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="beforeUpload"
            action="http://192.168.1.18:9002/case/upload/file"
            accept=".xls,.xlsx"
          >
            <button class="btn" @click="importFile">
              {{ btnText }}
            </button>
          </el-upload>
          <button class="btn" style="margin-left: 6px" @click="exportData()">
            导出
          </button>
          <button
            class="btn"
            style="margin-left: 6px"
            @click="downloadTemplate"
          >
            下载模板
          </button>
        </div>
      </div>
    </div>
    <el-row :type="'flex'" class="content">
      <ComTable
        :data="tableData"
        :pageSize="pageSize"
        @onPagging="onChangePage"
        height="84vh"
        v-loading="tableLoading"
        element-loading-text="拼命加载中"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        v-if="category == '0'"
      ></ComTable>
      <ComTable
        :data="tableData2"
        :pageSize="pageSize"
        @onPagging="onChangePage"
        height="84vh"
        v-loading="tableLoading"
        element-loading-text="拼命加载中"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        v-else
      ></ComTable>
    </el-row>
    <el-dialog
      title="原始数据对比"
      v-model="gzCgd"
      width="80%"
      top="5vh"
      custom-class="modal"
      :close-on-click-modal="false"
      :before-close="onClickDialogClose"
      class="isvisiable"
      @closed="
        () => {
          markLineData = [];
        }
      "
    >
      <Point :data="gzCgdData" :st="st" :markLineData="markLineData" v-if="gzCgd" />
    </el-dialog>
    <el-dialog
      :title="'故障样本库' + addDialogTitle"
      v-model="addDialogShow"
      width="60%"
      custom-class="modal currentAddDialog"
      :close-on-click-modal="false"
      class="isvisiable"
      @closed="
        (res) => {
          addDialogTitle = '';
          addDialogShow = false;
          list();
        }
      "
    >
      <el-form
        ref="addDialogRef"
        :model="addDialogForm"
        :rules="addDialogRules"
        label-width="120px"
      >
        <div class="inlineItem">
          <el-form-item label="场站：" prop="stationen">
            <el-select
              v-model="addDialogForm.stationen"
              placeholder="请选择"
              popper-class="select"
              @change="addDialogStationChange"
            >
              <el-option
                v-for="item in ChangZhan"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="风机：" prop="windturbineid">
            <el-select
              v-model="addDialogForm.windturbineid"
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in fengjiArray"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="inlineItem">
          <el-form-item label="故障类型：" prop="faulttype">
            <el-select
              v-model="addDialogForm.faulttype"
              placeholder="请选择"
              popper-class="select"
              @change="addDialogFaulttypeChange"
            >
              <el-option
                v-for="item in widgetArr"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="风机型号：" prop="model">
            <el-select
              v-model="addDialogForm.model"
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in addDialogFjxh"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="inlineItem">
          <el-form-item label="故障时间：" prop="time">
            <el-date-picker
              v-model="addDialogForm.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD hh:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="风机厂商：" prop="manufacturer">
            <el-select
              v-model="addDialogForm.manufacturer"
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in manufacturerArray"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="inlineItem">
          <el-form-item style="width: 100%" label="故障现象：" prop="symptom">
            <el-input
              type="textarea"
              v-model="addDialogForm.symptom"
              placeholder="请输入"
              clearable
              resize="none"
              :maxlength="200"
              :autosize="{ minRows: 2, maxRows: 6 }"
              :rows="2"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            class="btn red"
            type="danger"
            @click="cancelAdd('addDialogRef')"
          >
            取消
          </el-button>
          <el-button
            class="btn green"
            type="success"
            style="margin-left: 12px"
            @click="submitForm('addDialogRef')"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-scrollbar>
</template>

<script>
import ComTable from "@/components/coms/table/table.vue";
import Point from "./point.vue";
import { ElMessageBox } from "element-plus";
export default {
  components: {
    ComTable,
    Point,
  },
  data() {
    const that = this;
    return {
      markLineData: [],
      btnText: "导入",
      addDialogTitle: "",
      addDialogShow: false,
      addDialogForm: {
        tag: 0,
        category: 0,
        stationcn: "",
        stationen: "",
        windturbineid: "",
        faulttype: "",
        faultcode: "",
        time: [],
        symptom: "",
        manufacturer: "",
      },
      addDialogRules: {
        stationen: [
          {
            required: true,
            message: "场站不可为空",
            trigger: "change",
          },
        ],
        windturbineid: [
          {
            required: true,
            message: "风机不可为空",
            trigger: "change",
          },
        ],
        faulttype: [
          {
            required: true,
            message: "故障类型不可为空",
            trigger: "change",
          },
        ],
        model: [
          {
            required: true,
            message: "风机型号不可为空",
            trigger: "change",
          },
        ],
        time: [
          {
            required: true,
            message: "故障时间区间不可为空",
            trigger: "blur",
          },
        ],
        manufacturer: [
          {
            required: true,
            message: "风机厂商不可为空",
            trigger: "change",
          },
        ],
        symptom: [
          {
            required: true,
            message: "故障现象不可为空",
            trigger: "change",
          },
        ],
      },
      fengjiArray: [],
      addDialogFjxh: [],
      manufacturerArray: [
        { label: "联合动力", value: "联合动力" },
        { label: "华创", value: "华创" },
      ],
      sourceTableData: [],
      active: true,
      selectAll: true,
      pageIndex: 1,
      pageSize: 20,
      gzCgd: false, //传感点组件隐藏或显示
      gzCgdData: [], //传感点参数
      category: "0", //模型分类
      categorys: [
        { label: "故障样本", value: "0" },
        { label: "DBSCAN样本", value: "3" },
      ],
      st: "",
      widgetArr: [],
      ChangZhan: [],
      fjxh: [],
      fjxhArr: [],
      widget: [],
      model: [],
      time: [],
      station: "",
      tableData: {
        column: [
          {
            name: "序号",
            field: "index",
            is_light: false,
            width: "50px",
          },
          {
            name: "风机编号",
            field: "wtId",
            is_light: false,
            width: "150px",
          },
          {
            name: "故障类型",
            field: "tableTag",
            is_light: false,
            width: "150px",
          },
          {
            name: "故障现象",
            field: "symptom",
            is_light: false,
            width: "300px",
          },
          {
            name: "时间",
            field: "tableTime",
            is_light: false,
            width: "350px",
          },
          {
            name: "风机型号",
            field: "tableModel",
            is_light: false,
            width: "150px",
          },
          {
            name: "厂商",
            field: "tableManufacturer",
            is_light: false,
            width: "150px",
          },
          {
            name: "操作",
            field: "cz",
            is_light: false,
            width: "200px",
            template: () => {
              return "<el-button type='text' style='cursor: pointer;' value='config' data-callback='onClickOption'>传感点</el-button><el-button type='text' style='cursor: pointer;margin:0 10px;' value='config' data-callback='edit'>编辑</el-button><el-button type='text' style='cursor: pointer;' value='config' data-callback='delete'>删除</el-button>";
            },
            click(e, row) {
              const fnName = e.target.getAttribute("data-callback");
              fnName && that[fnName](e, row);
            },
          },
        ],
        data: [],
      },
      tableData2: {
        column: [
          {
            name: "序号",
            field: "index",
            is_light: false,
            width: "50px",
          },
          {
            name: "风机编号",
            field: "wtId",
            is_light: false,
            width: "200px",
          },
          {
            name: "故障类型",
            field: "faulttype",
            is_light: false,
            width: "200px",
          },
          {
            name: "故障时间",
            field: "faultTime",
            is_light: false,
            width: "200px",
          },
          {
            name: "风机型号",
            field: "modelId",
            is_light: false,
            width: "200px",
          },
          {
            name: "操作",
            field: "cz",
            is_light: false,
            width: "200px",
            template: () => {
              return "<el-button type='text' style='cursor: pointer;' value='config' data-callback='onClickOption'>传感点</el-button><el-button type='text' style='margin:0 10px;cursor: pointer;' value='config' data-callback='delete'>删除</el-button>";
            },
            click(e, row) {
              const fnName = e.target.getAttribute("data-callback");
              fnName && that[fnName](e, row);
            },
          },
        ],
        data: [],
      },
    };
  },
  methods: {
    stationChange() {
      let fjxh = [];
      this.fjxhArr.forEach((ele) => {
        if (ele.id == this.station) {
          ele.value.forEach((ele2) => {
            fjxh.push({
              label: ele2,
              value: ele2,
            });
          });
          this.model = ele.value;
        }
      });
      this.fjxh = fjxh;
    },

    checkAll() {
      this.selectAll = !this.selectAll;
      if (this.selectAll) {
        let widget = [];
        this.widgetArr.forEach((ele) => {
          widget.push(ele.value);
        });
        this.widget = widget;
        this.active = true;
      } else {
        this.active = false;
        this.widget = [];
      }
    },

    onChangePage(params) {
      this.pageIndex = params.pageIndex;
      this.pageSize = params.pageSize;
      this.list();
    },

    async startAjax() {
      var that = this;
      that.time = [
        new Date(new Date() - 3600 * 1000 * 24 * 360).formatDate(
          "yyyy-MM-dd hh:mm:ss"
        ),
        new Date().formatDate("yyyy-MM-dd hh:mm:ss"),
      ];

      await that.API.requestData({
        method: "GET",
        subUrl: "/know/fault/type/all",
        success(res) {
          let widgetArr = [],
            widget = [];
          res.data.forEach((ele, index) => {
            widgetArr.push({
              label: ele.name,
              value: ele.code,
            });
            widget.push(ele.code);
          });
          that.widget = widget;
          that.widgetArr = widgetArr;
        },
      });

      await that.API.requestData({
        method: "GET",
        subUrl: "basic/station/all",
        success(res) {
          that.ChangZhan = res.data;
          that.station = res.data[1].name;
          let fjxhArr = [];
          let model = [],
            fjxh = [];
          res.data.forEach((ele) => {
            fjxhArr.push({
              id: ele.id,
              value: ele.model.split("/"),
            });
            if (ele.id == "NSS_FDC") {
              model = ["UP82"];
              fjxh.push({
                label: "UP82",
                value: "UP82",
              });
            }
          });
          that.fjxhArr = fjxhArr;
          that.model = model;
          that.fjxh = fjxh;
        },
      });
      that.list();
    },

    onClickOption(e, row) {
      // 操作按钮
      let that = this;
      if ("config" == e.target.getAttribute("value")) {
        //传感点
        that.API.requestData({
          method: "GET",
          subUrl: "point/list",
          data: {
            wtId: row.wtId,
            widget: row.widget,
          },
          success(res) {
            if (res.data.length) {
              that.markLineData = [
                {
                  xAxis: new Date(row.tableTime.split(" - ")[0]).formatDate(
                    "yyyy-MM-dd hh:mm"
                  ),
                },
              ];
              that.gzCgdData = res.data;
              if (that.category == "0") {
                that.st = Date.parse(new Date(row.tableTime.split(" - ")[0]));
              } else {
                that.st = Date.parse(new Date(row.faultTime));
              }
              that.gzCgd = true;
            } else {
              that.BASE.showMsg({
                msg: "暂无数据",
              });
            }
          },
        });
      }
    },

    onClickDialogClose() {
      // 弹窗右上角关闭按钮
      this.gzCgd = false;
    },

    formatDate(dates) {
      var date = new Date(dates);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },

    list() {
      var that = this;
      let station = "",
        widget = "";
      if (typeof that.time[0].valueOf() != "string") {
        that.time[0] = that.formatDate(that.time[0].valueOf());
      }
      if (typeof that.time[1].valueOf() != "string") {
        that.time[1] = that.formatDate(that.time[1].valueOf());
      }
      if (typeof that.station.valueOf() == "string") {
        that.ChangZhan.forEach((ele) => {
          if (ele.name == that.station) {
            station = ele.id;
          }
        });
      }
      if (typeof that.widget.valueOf() == "string") {
        that.widgetArr.forEach((ele) => {
          if (ele.label == that.widget) {
            widget = ele.value;
          }
        });
      }
      if (that.model.length == 0) {
        that.BASE.showMsg({
          type: "warning",
          msg: "请选择风机型号",
        });
        return;
      }
      if (that.widget.length == 0) {
        that.BASE.showMsg({
          type: "warning",
          msg: "请选择部件",
        });
        return;
      }
      that.tableData.data = [];
      that.tableData2.data = [];
      that.API.requestData({
        showLoading: true,
        method: "GET",
        subUrl: "case/fault/list",
        data: {
          widget: widget ? widget : that.widget,
          station: station ? station : that.station,
          model: that.model,
          category: that.category,
          st: that.time[0].valueOf(),
          et: that.time[1].valueOf(),
        },
        success(res) {
          if (res.code === 200 && res.data.length) {
            let data = res.data;
            that.sourceTableData = res.data;
            if (that.category == "0") {
              let k = 0;
              for (var i = 0; i < data.length; i++) {
                k++;
                let obj = {
                  index: k,
                  dataIndex: i,
                  tableTag: data[i].faulttype,
                  symptom: data[i].symptom,
                  tableModel: data[i].model,
                  tableTime: data[i].starttime + " - " + data[i].endtime,
                  tableManufacturer: data[i].manufacturer,
                  wtId: data[i].windturbineid,
                  widget: data[i].faultcode,
                  id: data[i].id,
                };
                that.tableData.data.push(obj);
              }
            } else {
              that.tableData2.data = [];
              let k = 0;
              for (var j = 0; j < data.length; j++) {
                k++;
                let obj = {
                  index: k,
                  dataIndex: i,
                  wtId: data[j].windturbineid,
                  faulttype: data[j].faulttype,
                  modelId: data[j].model,
                  faultTime: data[j].starttime,
                  widget: data[j].faultcode,
                };
                that.tableData2.data.push(obj);
              }
            }
          }
        },
      });
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },

    exportData() {
      let that = this;
      const { export_json_to_excel } = require("@tools/excel/Export2Excel.js"); // 注意这个Export2Excel路径
      let tHeader = []; // 上面设置Excel的表格第一行的标题
      let filterVal = []; // 上面的index、nickName、name是tableData里对象的属性key值

      that.tableData.column.forEach((ele) => {
        if (ele.field != "cz") {
          tHeader.push(ele.name);
          filterVal.push(ele.field);
        }
      });
      const data = that.formatJson(filterVal, that.tableData.data);
      export_json_to_excel(tHeader, data, "故障样本库"); // 最后一个是表名字
    },

    delete(e, row) {
      const that = this;
      ElMessageBox.alert("确定删除该条数据？此操作不可逆", "", {
        showCancelButton: true,
        showConfirmButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "我再想想",
        callback(action) {
          if (action === "confirm") {
            that.API.requestData({
              method: "GET",
              subUrl: "case/fault/delete",
              data: {
                id: row.id,
              },
              success() {
                that.BASE.showMsg({
                  type: "success",
                  msg: "删除成功",
                });
                that.list();
              },
            });
          }
        },
      });
    },

    add() {
      this.addDialogTitle = "新增";
      this.addDialogForm.stationen = this.ChangZhan[0]?.id;
      this.addDialogStationChange(this.ChangZhan[0]?.id);
      this.addDialogShow = true;
    },

    addDialogStationChange(res, fjId) {
      let fjxh = [];
      this.fjxhArr.forEach((ele) => {
        if (ele.id === res) {
          ele.value.forEach((ele2) => {
            fjxh.push({
              label: ele2,
              value: ele2,
            });
          });
        }
      });
      this.addDialogFjxh = fjxh;
      this.addDialogForm.model = fjxh[0].value;
      this.addDialogForm.stationcn = this.ChangZhan.find((ele) => {
        return ele.id === res;
      })?.name;
      this.getFengji(fjId);
    },

    getFengji(fjId) {
      const that = this;
      that.API.requestData({
        method: "GET",
        subUrl: "basic/windturbine/all",
        data: {
          station: that.addDialogForm.stationen,
        },
        success(res) {
          that.fengjiArray = res.data;
          that.addDialogForm.windturbineid = fjId || res.data[0].id;
        },
      });
    },

    addDialogFaulttypeChange(res) {
      this.addDialogForm.faultcode = this.widgetArr.find((ele) => {
        return ele.value === res;
      })?.value;
    },

    cancelAdd(ref) {
      const that = this;
      ElMessageBox.alert(
        `确定取消${that.addDialogTitle}吗？之前所做的操作将不被保存`,
        "",
        {
          showCancelButton: true,
          showConfirmButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          callback(action) {
            if (action === "confirm") {
              that.addDialogShow = false;
              that.resetForm(ref);
            }
          },
        }
      );
    },

    resetForm(ref) {
      this.addDialogForm = {
        tag: 0,
        category: 0,
        stationcn: "",
        stationen: "",
        windturbineid: "",
        faulttype: "",
        faultcode: "",
        time: [],
        symptom: "",
        manufacturer: "",
      };
      this.$refs[ref].resetFields();
    },

    submitForm(ref) {
      const that = this;
      that.$refs[ref].validate((valid, fields) => {
        if (valid) {
          let data = that.BASE.deepCopy(that.addDialogForm);
          data.starttime = data.time[0];
          data.endtime = data.time[1];
          data.faulttype = that.widgetArr.find((ele) => {
            return ele.value === data.faulttype;
          })?.label;
          data.time && delete data.time;
          that.API.request({
            method: "post",
            subUrl: `case/fault/${
              that.addDialogTitle === "新增" ? "insert" : "edit"
            }`,
            data: that.addDialogTitle === "新增" ? [data] : data,
          }).then((res) => {
            if (res.data.code === 200) {
              that.BASE.showMsg({
                type: "success",
                msg: `${that.addDialogTitle}成功`,
              });
              that.addDialogShow = false;
              that.resetForm();
            }
          })
        }
      });
    },
    edit(e, row) {
      const that = this;
      const editItem = that.sourceTableData[row.dataIndex];
      for (let key in that.addDialogForm) {
        if (key === "time") {
          that.addDialogForm[key] = [editItem.starttime, editItem.endtime];
        } else if (key === "faulttype") {
          that.addDialogForm[key] = editItem.faultcode;
        } else {
          that.addDialogForm[key] = editItem[key];
        }
      }
      that.addDialogForm.id = editItem.id;
      that.addDialogStationChange(editItem.stationen, editItem.windturbineid);
      that.addDialogTitle = "编辑";
      that.addDialogShow = true;
    },

    onSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.BASE.showMsg({
          type: "success",
          msg: `文件上传成功`,
        });
      } else {
        this.BASE.showMsg({
          msg: response.msg,
        });
      }

      this.BASE.closeLoading();
      this.btnText = "导入";
    },
    onError(err, file, fileList) {
      this.btnText = "导入";
    },
    beforeUpload(file) {
      this.BASE.showLoading();
      this.btnText = "正在导入";
      return file.type.indexOf(".sheet") !== -1;
    },
    downloadTemplate() {
      window.open(
        "http://192.168.1.18:9002/case/download/template?template=fault"
      );
    },
  },
  created() {
    this.startAjax();
  },
};
</script>

<style lang="less" scoped>
.mb10 {
  margin-bottom: 10px;
}

.el-select.w {
  width: 100%;
}

// .el-range-editor.w{width: 100%;}
</style>

<style lang="less">
.currentAddDialog {
  .el-form {
    display: flex;
    justify-content: start;
    align-items: center;
    flex-wrap: wrap;
    .inlineItem {
      width: 100%;
      display: flex;
      justify-content: start;
      align-items: center;
      .el-form-item {
        width: 100%;
        margin-bottom: 40px;

        .el-input__count {
          background: rgba(83, 98, 104, 0.2);
          color: #b3bdc0;
        }
      }
    }
  }
}
</style>
