<template>
  <div class="app-container">
    <div class="btn-condition">
      <div class="condition-left" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="报警类型" prop="alarmType">
            <el-select
              v-model="queryParams.alarmType"
              placeholder="选择报警类型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.alarm_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="事件类型" prop="eventType">
            <el-select
              v-model="queryParams.eventType"
              placeholder="选择事件类型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.alarm_event_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="报警等级" prop="alarmLevel">
            <el-select
              v-model="queryParams.alarmLevel"
              placeholder="选择报警等级"
              clearable
            >
              <el-option
                v-for="dict in dict.type.alarm_level"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="primary-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
        </div>
        <div class="cancel-btn">
          <el-button
            type="cancel"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div class="primary-btn" v-hasPermi="['alarm:ar:add']">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="success-btn" v-hasPermi="['alarm:ar:edit']">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            >修改</el-button
          >
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="delete-btn" v-hasPermi="['alarm:ar:remove']">
          <el-button
            type="delete"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </div>
      </el-col>
      <!-- <el-col :span="1.5">
        <div class="warning-btn" v-hasPermi="['system:post:export']">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </div>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报警类型" align="center" prop="alarmType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.alarm_type"
            :value="scope.row.alarmType"
          />
        </template>
      </el-table-column>
      <el-table-column label="事件类型" align="center" prop="eventType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.alarm_event_type"
            :value="scope.row.eventType"
          />
        </template>
      </el-table-column>
      <el-table-column label="报警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.alarm_level"
            :value="scope.row.alarmLevel"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="采集点位" align="center" prop="cpmName">
      </el-table-column>
      <el-table-column
        label="报警延时时间"
        align="center"
        prop="delayTimes"
        width="110"
      />
      <el-table-column label="时段设置" align="center" prop="timePeriodSet">
        <template slot-scope="scope">
          <span v-if="scope.row.timePeriodSet === 0">全时段</span>
          <span v-if="scope.row.timePeriodSet === 1">自定义时段</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时段" align="center" prop="beginTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时段" align="center" prop="endTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="触发事件" align="center" prop="triggerEvent">
        <template slot-scope="scope">
          <span v-if="scope.row.triggerEvent === 0">开</span>
          <span v-if="scope.row.triggerEvent === 1">关</span>
        </template>
      </el-table-column>
      <el-table-column label="条件1" align="center" prop="condition1" />
      <el-table-column label="阈值1" align="center" prop="threshold1" />
      <el-table-column label="条件2" align="center" prop="condition2" />
      <el-table-column label="阈值2" align="center" prop="threshold2" />
      <!-- <el-table-column label="能源节点" align="center" prop="energyNode" />
      <el-table-column label="能源类型" align="center" prop="energyType" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span
            :class="getStatusClass(scope.row.status)"
            v-if="scope.row.status === 0"
            >已启用</span
          >
          <span
            :class="getStatusClass(scope.row.status)"
            v-if="scope.row.status === 1"
            >未启用</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['alarm:ar:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['alarm:ar:remove']"
            >删除</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 :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="ledgerId">
              <el-select
                v-model="form.ledgerId"
                placeholder="请选择设备类型"
                clearable
                @change="handleDevice"
              >
                <el-option
                  v-for="item in devices"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采集点位" prop="cpmId">
              <el-select
                v-model="form.cpmId"
                placeholder="请选择设备类型"
                clearable
                @change="handleMeter"
              >
                <el-option
                  v-for="item in cpmList"
                  :key="item.id"
                  :label="item.otherName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="报警类型" prop="alarmType">
              <el-select
                v-model="form.alarmType"
                placeholder="请选择报警类型"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.alarm_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警延时时间" prop="delayTimes">
              <el-input
                clearable
                v-model="form.delayTimes"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="事件类型" prop="eventType">
              <el-select
                v-model="form.eventType"
                placeholder="请选择事件类型"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.alarm_event_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="报警等级" prop="alarmLevel">
              <el-select
                v-model="form.alarmLevel"
                placeholder="请选择报警等级"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.alarm_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="触发事件" prop="triggerEvent">
              <el-select
                v-model="form.triggerEvent"
                placeholder="请选择"
                clearable
              >
                <el-option label="开" value="0" />
                <el-option label="关" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时段设置" prop="timePeriodSet">
              <el-select
                v-model="form.timePeriodSet"
                placeholder="请选择"
                clearable
              >
                <el-option label="全时段" value="0" />
                <el-option label="自定义时段" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" v-if="form.timePeriodSet === '1'">
          <el-col :span="12">
            <el-form-item label="开始时段" prop="beginTime">
              <el-date-picker
                v-model="form.beginTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时段" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="条件1" prop="condition1">
              <el-input
                clearable
                v-model="form.condition1"
                placeholder="请输入条件"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阈值1" prop="threshold1">
              <el-input
                clearable
                v-model="form.threshold1"
                placeholder="请输入阈值"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="条件2" prop="condition2">
              <el-input
                clearable
                v-model="form.condition2"
                placeholder="请输入条件"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阈值2" prop="threshold2">
              <el-input
                clearable
                v-model="form.threshold2"
                placeholder="请输入阈值"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="flex-start">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable>
                <el-option label="已启用" value="0" />
                <el-option label="未启用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  alarmRuleList,
  getAlarmRule,
  delAlarmRule,
  addAlarmRule,
  updateAlarmRule,
} from "@/api/alarm/alarmRule";
import { cpmList } from "@/api/device/gather";
import { ledgerList } from "@/api/device/ledger";
export default {
  name: "alarmRule",
  dicts: ["alarm_type", "alarm_event_type", "alarm_level", "sys_mt_type"],
  data() {
    // 自定义校验规则
    const validateBeginTime = (rule, value, callback) => {
      if (this.form.timePeriodSet === "1") {
        if (!value) {
          callback(new Error("请选择开始时段"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateEndTime = (rule, value, callback) => {
      if (this.form.timePeriodSet === "1") {
        if (!value) {
          callback(new Error("请选择结束时段"));
        } else if (new Date(value) <= new Date(this.form.beginTime)) {
          callback(new Error("结束时间必须大于开始时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateAtLeastOnePair = (rule, value, callback) => {
      const { condition1, threshold1, condition2, threshold2 } = this.form;
      if ((condition1 && threshold1) || (condition2 && threshold2)) {
        callback();
      } else {
        callback(new Error("至少要有一组条件和阈值不能为空"));
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网关表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmType: "",
        eventType: "",
        alarmLevel: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ledgerId: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        cpmId: [
          { required: true, message: "仪表名称不能为空", trigger: "blur" },
        ],
        eventType: [
          { required: true, message: "请选择事件类型", trigger: "blur" },
        ],
        alarmLevel: [
          { required: true, message: "请选择报警等级", trigger: "blur" },
        ],
        alarmType: [
          { required: true, message: "请选择报警事件", trigger: "blur" },
        ],
        delayTimes: [
          { required: true, message: "消息内容不能为空", trigger: "blur" },
        ],
        timePeriodSet: [
          { required: true, message: "请选择一个时段设置", trigger: "blur" },
        ],
        beginTime: [
          {
            validator: validateBeginTime,
            trigger: "change",
          },
        ],
        endTime: [
          {
            validator: validateEndTime,
            trigger: "change",
          },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        condition1: [{ validator: validateAtLeastOnePair, trigger: "blur" }],
        threshold1: [{ validator: validateAtLeastOnePair, trigger: "blur" }],
        condition2: [{ validator: validateAtLeastOnePair, trigger: "blur" }],
        threshold2: [{ validator: validateAtLeastOnePair, trigger: "blur" }],
      },
      devices: [], //设备列表
      cpmList: [], //采集点位列表
    };
  },
  created() {
    this.getDeviceList();
    this.getList();
  },
  methods: {
    // 表格动态类名
    getStatusClass(status) {
      switch (status) {
        case 0:
          return "status-green";
        case 1:
          return "status-red";
        default:
          return "";
      }
    },
    // 查询设备列表
    getDeviceList() {
      let data = {
        pageNum: 1,
        pageSize: 100000,
      };
      ledgerList(data).then((response) => {
        this.devices = response.rows;
      });
    },
    /** 查询报警编码列表 */
    getList() {
      this.loading = true;
      alarmRuleList(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.form.id = "";
    },
    // 表单重置
    reset() {
      this.form = {
        eventType: "",
        alarmLevel: "",
        alarmType: "",
        ledgerId: "",
        deviceName: "",
        cpmId: "",
        cpmName: "",
        delayTimes: "",
        timePeriodSet: "",
        beginTime: "",
        endTime: "",
        triggerEvent: "",
        condition1: "",
        threshold1: "",
        condition2: "",
        threshold2: "",
        energyNode: "",
        energyType: "",
        status: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 弹框选择设备名称
    handleDevice(selectedValue) {
      // 通过选中的 value 找到对应的 label
      const selectedItem = this.devices.find(
        (item) => item.id === selectedValue
      );
      if (selectedItem) {
        const selectedLabel = selectedItem.deviceName;
        console.log("选中的 value:", selectedValue);
        console.log("选中的 label:", selectedLabel);
        // 在这里可以进行其他操作，比如发送请求等
        this.form.ledgerId = selectedValue;
        this.form.deviceName = selectedLabel;
        // 请求采集位点
        this.getCpmIdList(this.form.ledgerId);
      }
      //清除采集位点
      this.form.cpmId = "";
    },
    //采集参数列表
    getCpmIdList(id) {
      let data = {
        pageNum: 1,
        pageSize: 10000,
        beginTime: "",
        endTime: "",
        mtType: "",
        mtNum: "",
        deviceLedgerId: id,
        systemType: "",
        paramType: "",
      };
      cpmList(data).then((response) => {
        this.cpmList = response.rows;
        console.log("this.cpmList", this.cpmList);
      });
    },
    // 弹框选择采集类型
    handleMeter(selectedValue) {
      // 通过选中的 value 找到对应的 label
      const selectedItem = this.cpmList.find(
        (item) => item.id === selectedValue
      );
      if (selectedItem) {
        const selectedLabel = selectedItem.otherName;
        console.log("选中的 value:", selectedValue);
        console.log("选中的 label:", selectedLabel);
        // 在这里可以进行其他操作，比如发送请求等
        this.form.cpmId = selectedValue;
        this.form.cpmName = selectedLabel;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报警规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.id = "";
      const arId = row.id || this.ids;
      console.log("");
      getAlarmRule(arId).then((response) => {
        // this.form = response.data;
        this.form = {
          id: response.data.id,
          eventType:
            response.data.eventType !== null
              ? response.data.eventType.toString()
              : null,
          alarmLevel:
            response.data.alarmLevel !== null
              ? response.data.alarmLevel.toString()
              : null,
          alarmType:
            response.data.alarmType !== null
              ? response.data.alarmType.toString()
              : null,
          ledgerId: response.data.ledgerId,
          deviceName: response.data.deviceName,
          cpmId: response.data.cpmId,
          cpmName: response.data.cpmName,
          delayTimes: response.data.delayTimes,
          timePeriodSet:
            response.data.timePeriodSet !== null
              ? response.data.timePeriodSet.toString()
              : null,
          beginTime: response.data.beginTime,
          endTime: response.data.endTime,
          triggerEvent:
            response.data.triggerEvent !== null
              ? response.data.triggerEvent.toString()
              : null,
          condition1: response.data.condition1,
          threshold1: response.data.threshold1,
          condition2: response.data.condition2,
          threshold2: response.data.threshold2,
          energyNode: "",
          energyType: "",
          status:
            response.data.status !== null
              ? response.data.status.toString()
              : null,
        };
        this.open = true;
        this.title = "修改报警规则";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAlarmRule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log("新增参数", this.form);
            addAlarmRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报警规则编号为"' + Ids + '"的数据项？')
        .then(function () {
          return delAlarmRule(Ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/gateway/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.status-green {
  color: rgb(7, 214, 110);
}
.status-red {
  color: red;
}
</style>
<style scoped lang="scss">
/* 媒体查询，适配大于2000px分辨率的大屏样式 - element样式 */
@media (max-width: 2000px) {
  ::v-deep .el-dialog {
    width: 700px !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 150px !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
@media (min-width: 2000px) {
  ::v-deep .el-dialog {
    width: 7.5rem !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 1.5rem !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
</style>
