<template>
  <!-- 预警记录功能 -->
  <div class="app-container alarm-record">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      class="main-search-card"
      label-width="68px"
    >
      <el-form-item label="所属项目" prop="inProject">
        <el-select v-model="queryParams.inProject" clearable placeholder="请选择所属项目" size="small">
          <el-option
            v-for="(item, index) in inProjectList"
            :key="item.projectId"
            :label="item.projectName"
            :value="item.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预警时间" prop="alarmTime">
        <el-date-picker
          v-model="time"
          :default-time="['00:00:00', '23:59:59']"
          clearable
          end-placeholder="结束日期"
          range-separator="至"
          size="small"
          start-placeholder="开始日期"
          type="datetimerange"
          @change="queryTimeChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预警类型" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          clearable
          placeholder="请输入预警类型"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="main-content-card">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        :view-type="viewType"
        @changeViewType="changeViewType"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="viewType!='card'"
      v-loading="loading"
      :data="recordList"
      :default-sort="{ prop: 'alarmTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column
        :index="indexFormatter"
        align="center"
        label="序号"
        type="index"
        width="60"
      ></el-table-column>
      <el-table-column
        align="center"
        label="预警类型"
        prop="typeName"
      />
      <el-table-column
        align="center"
        label="设备名称"
        prop="deviceName"
      />
      <el-table-column align="center" label="所属项目" prop="inProjectName" />
      <el-table-column align="center" label="预警内容" prop="alarmContent" />
      <el-table-column
        align="center"
        label="预警时间"
        prop="alarmTime"
        sortable="custom"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.alarmTime, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="处理状态"
        prop="processStatus"
        width="100"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.processStatus === '1'" >{{ stateFormatter(scope.row) }}</el-tag>
          <el-tag v-else-if="scope.row.processStatus === '0'" type="danger" >{{ stateFormatter(scope.row) }}</el-tag>
          <el-tag v-else-if="scope.row.processStatus === '2'" type="warning" >{{ stateFormatter(scope.row) }}</el-tag>
          <el-tag v-else type="info" >{{ stateFormatter(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="处理结果" prop="processResult" />
      <el-table-column
        align="center"
        label="处理时间"
        prop="processTime"
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.processTime, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.processStatus === '0'"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >处理</el-button
          >
          <el-button
            icon="el-icon-document-add"
            size="mini"
            type="text"
            @click="handleWork(scope.row)"
            >创建工单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div v-else class="card-list-box">
      <el-row :gutter="20">
        <el-col v-for="(item, index) in recordList" :key="index" :lg="8" :md="12" :sm="12" :xs="24" class="card-item-col">
          <div class="card-item">
            <div class="card-header">
              <div class="card-header-top">
                <div class="device-img-box">
                  <el-image
                    :src="'http://static.drgyen.com/pc/smart-power-ui/alarm/device.png'"
                    style="width: 100%; height: 100%">
                  </el-image>
                </div>
                <div class="card-item-name">{{ item.typeName }}</div>
              </div>
              <div :class="'card-status'+item.processStatus" class="card-status">
                {{ stateFormatter(item) }}
              </div>
            </div>
            <div class="card-content">
              <div class="info-item">
                <span class="label">预警设备：</span>
                <el-tooltip :content="item.deviceName" effect="dark" placement="top">
                  <span class="value">{{ item.deviceName }}</span>
                </el-tooltip>
              </div>
              <div class="info-item">
                <span class="label">所属项目：</span>
                <el-tooltip :content="item.inProjectName" effect="dark" placement="top">
                  <span class="value">{{ item.inProjectName }}</span>
                </el-tooltip>
              </div>
              <div class="info-item">
                <span class="label">预警内容：</span>
                <el-tooltip :content="item.alarmContent" effect="dark" placement="top">
                  <span class="value">{{ item.alarmContent }}</span>
                </el-tooltip>
              </div>
              <div class="info-item">
                <span class="label">预警时间：</span>
                <el-tooltip :content="item.alarmTime" effect="dark" placement="top">
                  <span class="value">{{parseTime(item.alarmTime, "{y}-{m}-{d} {h}:{i}:{s}")}}</span>
                </el-tooltip>
              </div>
              <div class="info-item">
                <span class="label">处理结果：</span>
                <el-tooltip :content="item.processResult" effect="dark" placement="top">
                  <span class="value">{{ item.processResult }}</span>
                </el-tooltip>
              </div>
              <div class="info-item">
                <span class="label">处理时间：</span>
                <el-tooltip :content="item.processTime" effect="dark" placement="top">
                  <span class="value">{{parseTime(item.processTime, "{y}-{m}-{d} {h}:{i}:{s}")}}</span>
                </el-tooltip>
              </div>
            </div>
            <div class="card-footer">
              <el-button
                :disabled="item.processStatus !== '0'"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(item)"
              >处理</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button
                icon="el-icon-document-add"
                size="mini"
                type="text"
                @click="handleWork(item)"
              >创建工单</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-empty v-if="total === 0"></el-empty>
    </div>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[12, 24, 36, 60]"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      class="eldialog-wrap"
      width="600px"
    >
      <el-form
        ref="dialogForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="处理结果:" prop="processResult">
          <el-input
            v-model="form.processResult"
            :rows="2"
            placeholder="请输入处理结果"
            type="textarea"
          />
        </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";
import { handlerRecord } from "@/api/alarm/record";
import { listProject } from "@/api/tenant/project";

export default {
  name: "Warning",
  components: {
    Editor,
  },
  data() {
    return {
      // 视图类型
      viewType: "card",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预警记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        typeName: null,
        typeCode: null,
        inProject: null,
        beginTime: null,
        endTime: null,
        alarmDivide: "WARNING",
        isAsc: 'desc',
        orderByColumn: 'alarmTime'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      time: [],
      // 弹出层标题
      inProjectList:[],
    };
  },
  created() {
    this.getList();
    this.getInProjectList();
  },
  methods: {
    changeViewType(type) {
      this.viewType=type;
    },
    // 查询所属项目列表
    getInProjectList() {
      listProject({
        pageNum: 1,
        pageSize: 100,
        orderByColumn: 'createTime',
        isAsc: 'desc'
      }).then(response => {
        this.inProjectList = response.rows;
      });
    },
    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();
          });
        }
      });
    },
    // 处理告警
    handleUpdate(row) {
      const recordId = row.recordId || this.ids;
      this.$confirm("是否设置此预警为已处理状态?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return handlerRecord({ recordIds: recordId.split(",") });
        })
        .then(() => {
          this.getList();
          this.msgSuccess("处理成功");
        });
    },
    // 转工单处理
    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");
        });
    },
    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>

<style lang="scss" scoped>
@import "~@/assets/styles/alarm-card.scss";
</style>
