<template>
  <!-- 预警记录功能 -->
  <div class="app-container alarm-record">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="预警时间" prop="alarmTime">
        <el-date-picker
          v-model="time"
          size="small"
          @change="queryTimeChange"
          clearable
          type="datetimerange"
          :default-time="['00:00:00', '23:59:59']"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预警类型" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入预警类型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tenant:record:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
      :default-sort="{ prop: 'alarmTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexFormatter"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="设备名称"
        align="left"
        width="200px"
        prop="deviceName"
      />
      <!-- <el-table-column label="设备当前值" align="left"  width="200px" prop="currentValue" /> -->
      <el-table-column label="推送内容" align="left" prop="alarmContent" />
      <el-table-column
        label="预警时间"
        align="center"
        prop="alarmTime"
        width="150"
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.alarmTime, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="处理状态"
        width="100px"
        align="center"
        prop="processStatus"
        :formatter="stateFormatter"
      />
      <el-table-column label="处理结果" align="left" prop="processResult" />
      <el-table-column
        label="处理时间"
        align="center"
        sortable="custom"
        prop="processTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.processTime, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="预警类型"
        align="left"
        width="200px"
        prop="typeName"
      />
      <el-table-column
        label="操作"
        width="200"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-show="scope.row.processStatus === '1'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:record:edit']"
          >处理</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleWork(scope.row)"
            v-hasPermi="['iot:maintenance:add']"
            >创建工单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      class="eldialog-wrap"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="600px"
    >
      <el-form
        ref="dialogForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="处理结果:" prop="processResult">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.processResult"
            placeholder="请输入处理结果"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  exportRecord,
  updateRecord,
  delRecord,
  addAlarmRecord,
} from "@/api/alarm/tenantAlarm";
import Editor from "@/components/Editor";

export default {
  name: "Warning",
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预警记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        typeCode: null,
        beginTime: null,
        endTime: null,
        alarmDivide: "WARNING",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      time: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    queryTimeChange(val) {
      if (val) {
        this.queryParams.beginTime = this.parseTime(
          val[0],
          "{y}-{m}-{d} {h}:{i}:{s}"
        );
        this.queryParams.endTime = this.parseTime(
          val[1],
          "{y}-{m}-{d} {h}:{i}:{s}"
        );
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordId = row.recordId;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delRecord(recordId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    submitForm() {
      this.$refs["dialogForm"].validate((v) => {
        if (v) {
          this.form.processTime = this.parseTime(
            new Date(),
            "{y}-{m}-{d} {h}:{i}:{s}"
          );
          this.form.processStatus = "2";
          updateRecord(this.form).then((response) => {
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 转工单处理
    handleWork(row) {
      console.log("addWork:", row);
      this.$confirm("是否创建预警工单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return addAlarmRecord({
            recordId: row.recordId, //告警记录id
            deviceId: row.deviceId,
            deviceName: row.deviceName,
            faultType: "4", //固定
            maintenanceStatus: "-1", //固定（工单已生成）
            tenantId: null,
            faultTypeName: "预警工单", //固定
          });
        })
        .then(() => {
          this.msgSuccess("创建成功！");
          this.$router.push("/power/maintenancet");
        });
    },
    // 处理预警
    handleUpdate(row) {
      this.resetFomr();
      getRecord(row.recordId).then((res) => {
        this.form = res.data;
        this.open = true;
        this.title = "预警处理";
      });
    },
    resetFomr() {
      this.form = {
        processResult: "",
        processStatus: "",
        processTime: "",
        recordId: "",
      };
    },
    stateFormatter(val) {
      console.log(val);
      switch (val.processStatus) {
        case "1":
          return "已处理";

        case "0":
          return "未处理";

        case "2":
          return "误报";

        default:
          return "未处理";
      }
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询预警记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 根据id获取记录详情
    getRecordInfo(id) {
      getRecord(id).then((res) => {
        this.form = res.data;
        this.open = true;
        this.title = `预警记录详情`;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.time = [];
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有预警记录数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportRecord(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
