<template>
  <div class="page-container collectorList all-select-btn">
    <div class="content-box">
      <div class="search">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="事件名称">
            <el-input
              v-model="formInline.eventName"
              placeholder="请输入事件名称"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          <el-form-item label="发生位置">
            <el-input
              v-model="formInline.name"
              placeholder="请输入发生位置"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          <el-form-item label="除尘器名称">
            <el-input
              v-model="formInline.dusterName"
              placeholder="请输入除尘器名称"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="formInline.deviceType" style="width: 200px">
              <el-option
                v-for="i in typeList.list"
                :key="i"
                :label="`${i.desc}`"
                :value="i.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="告警时间">
            <el-date-picker
              v-model="formInline.date"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              popper-class="date-picker-popper"
              :teleported="false"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="default" class="reset-btn-balck-theme" @click="onReset"
              >重置</el-button
            >
            <el-button type="default" class="search-btn-balck-theme" @click="onSubmit"
              >查询</el-button
            >
            <el-button
              type="default"
              style="width: 140px"
              class="export-btn-balck-theme"
              @click="openRound()"
              >挂起设备</el-button
            >
          </el-form-item>
          <br />
          <el-form-item>
            <el-radio-group v-model="formInline.suspendFlag" @change="onSubmit">
              <el-radio value="1">挂起期间告警</el-radio>
              <el-radio value="0">非挂起期间告警</el-radio>
              <el-radio value="2">全部告警</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-box">
        <common-table
          ref="pageRef"
          :data="tableData.list"
          :columns="tableColumns"
          :total="total"
          :default-page-size="20"
          @pagination-change="handlePaginationChange"
          :pagination-texts="{
            total: '共',
            sizeChange: '条/页',
            prev: '前一页',
            next: '后一页',
            jumper: '跳至',
          }"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #operate="{ row }">
            <span class="health-score green-color" @click="openDialog(row)">暂挂起</span>
          </template>
        </common-table>
      </div>
    </div>
    <!-- 设备挂起 -->
    <el-dialog
      class="equWarnDialog"
      v-model="equDialog"
      title=""
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="equd_body">
        <el-form
          ref="ruleFormRef"
          :model="equSubmitInfo"
          :rules="rules"
          class="equd_form"
        >
          <span
            >是否要对<span class="bold">{{ clickItem.name }}</span
            >不再告警：</span
          >
          <el-form-item>
            <el-radio-group v-model="equSubmitInfo.noAlarm" @change="onSubmit">
              <el-radio value="1">是</el-radio>
              <el-radio value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="equSubmitInfo.startTime"
              type="datetime"
              placeholder="选择开始时间"
              popper-class="date-picker-popper"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="equSubmitInfo.endTime"
              type="datetime"
              placeholder="选择结束时间"
              popper-class="date-picker-popper"
            />
          </el-form-item>
          <el-form-item label="原因分类" prop="reasonCategory">
            <el-select v-model="equSubmitInfo.reasonCategory" style="width: 220px;">
              <el-option v-for="item in reasonCategoryList" :key="item.key" :value="item.key" :label="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="原因描述" prop="reasonDescription" style="padding-left: 10px;">
            <el-input v-model="equSubmitInfo.reasonDescription" type="textarea" style="width: 220px;"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer ">
          <el-button type="default" class="cancel-btn-balck-theme" @click="equDialog = false">取消</el-button>
          <el-button type="default" class="search-btn-balck-theme" @click="equPending(ruleFormRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, reactive } from "vue";
import CommonTable from "@/components/commonTable/index.vue";
import { useRoute, useRouter } from "vue-router";
import { getDataFun, postDataJSON } from "@/request/method.js";
import moment from "moment";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

const formInline = ref({
  eventName: "",
  name: "",
  dusterName: "",
  deviceType: route.query.deviceType ? Number(route.query.deviceType) : "",
  suspendFlag: "0",
  date: route.query.startTime
    ? [
        moment(new Date(route.query.startTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        moment(new Date(route.query.endTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
      ]
    : [],
});

const currentPage = ref(1);
const pageSize = ref(20);
const equDialog = ref(false);

const tableColumns = ref([
  {
    prop: "index",
    label: "序号",
    width: "4%",
  },
  {
    prop: "eventName",
    label: "事件名称",
    width: "9%",
  },
  {
    prop: "name",
    label: "发生位置",
    width: "15%",
  },
  {
    prop: "deviceType",
    label: "设备类型",
    width: "7%",
  },
  {
    prop: "alarmIndicators",
    label: "告警指标",
    width: "7%",
  },
  {
    prop: "value",
    label: "监测值",
    width: "5%",
  },
  {
    prop: "eventTime",
    label: "告警时间",
    width: "9%",
  },
  {
    prop: "isSuspendAlarm",
    label: "是否挂起期间告警",
    width: "8%",
  },
  {
    prop: "operate",
    label: "操作",
    width: "10%",
  },
]);

const ruleFormRef = ref(null);
const rules = {
  startTime: [{ required: true, message: "请填写开始时间", trigger: "blur" }],
  endTime: [
    {
      required: true,
      message: "请填写结束时间",
    },
  ],
  reasonCategory: [{ required: true, message: "请选择原因分类", trigger: "blur" }],
};

const tableData = reactive({
  list: [],
});

const typeList = reactive({
  list: [],
});
const getTypeList = () => {
  const url = "/alarm/getDeviceType";
  return getDataFun(url, "").then((res) => {
    if (res && res.data) {
      typeList.list = res.data || [];
    }
  });
};

const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

const handlePaginationChange = (pagination) => {
  currentPage.value = pagination.currentPage;
  pageSize.value = pagination.pageSize;
  getAlarmList();
};

const onSubmit = () => {
  currentPage.value = 1;
  pageRef.value.setCurrentPage(currentPage.value);
  getAlarmList();
};

const pageRef = ref(null);
const onReset = () => {
  formInline.value = {
    eventName: "",
    name: "",
    dusterName: "",
    deviceType: "",
    suspendFlag: "0",
    date: [],
  };
  currentPage.value = 1;
  pageSize.value = 20;
  pageRef.value.setCurrentPage(currentPage.value);
  getAlarmList();
};

const openRound = () => {
  router.push({ path: "/management/suspend-management" });
};

const clickItem = ref({});
const openDialog = (item) => {
  clickItem.value = item;

  equDialog.value = true;
};

const total = ref(0);
const getAlarmList = () => {
  const url = "/alarm/getAlarmListPage";
  const params = {
    eventName: formInline.value.eventName,
    name: formInline.value.name,
    dusterName: formInline.value.dusterName,
    deviceType: formInline.value.deviceType,
    suspendFlag: formInline.value.suspendFlag,
    startTime: formInline.value.date[0]
      ? moment(new Date(formInline.value.date[0]).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    endTime: formInline.value.date[1]
      ? moment(new Date(formInline.value.date[1]).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    pageNo: currentPage.value,
    pageSize: pageSize.value,
  };
  return getDataFun(url, params).then((res) => {
    if (res && res.data) {
      tableData.list = res.data.list || [];
      total.value = res.data.total;
    } else {
      return [];
    }
  });
};

const equSubmitInfo = ref({
  noAlarm: "0",
  startTime: "",
  endTime: "",
  reasonCategory: "", // 原因分类
  reasonDescription: "", // 原因描述
});

const equPending = async (formEl) => {
  if (!formEl) return;
  const url = "/alarm/suspendDevice";
  const params = {
    id: clickItem.value.id,
    noAlarm: equSubmitInfo.value.noAlarm,
    startTime: equSubmitInfo.value.startTime
      ? moment(new Date(equSubmitInfo.value.startTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    endTime: equSubmitInfo.value.endTime
      ? moment(new Date(equSubmitInfo.value.endTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    reasonCategory: equSubmitInfo.value.reasonCategory, // 原因分类
    reasonDescription: equSubmitInfo.value.reasonDescription, // 原因描述
  };
  await formEl.validate((valid, fields) => {
    if (valid) {
      return getDataFun(url, params).then((res) => {
        if (res && res.code == 1) {
          equDialog.value = false;
          getAlarmList();
        }
        ElMessage.success(res && res.data);
      }).catch((err) => {
        ElMessage.error(res && res.data);
      })
      ;
    } else {
    }
  });
};

// 原因分类
const reasonCategoryList = ref([])
const getReasonCategoryList = () => {
  const url = '/alarm/reasonCategoryEnumList'
  const params = {}
  getDataFun(url, params).then(res => {
    if (res && res.code == 1) {
      reasonCategoryList.value = res.data
    }
  }).catch(err => {
    
  })
}

onMounted(async () => {
  if (route.query) {
    const { deviceName, suspendStartTime, suspendEndTime, suspendFlag } =
      route.query;
    if (deviceName) {
      formInline.value.name = deviceName;
    }
    if (suspendStartTime) {
      formInline.value.date[0] = suspendStartTime;
    }
    if (suspendEndTime) {
      formInline.value.date[1] = suspendEndTime;
    }
    if (suspendFlag) {
      formInline.value.suspendFlag = suspendFlag;
    }
  }

  getTypeList();
  getAlarmList();
  getReasonCategoryList();
});

onBeforeUnmount(() => {});
</script>

<style lang="scss" scoped>
.collectorList {
  width: 100%;
  height: calc(100% - 14px);
  box-sizing: border-box;
  :deep(.el-input--small) {
    width: 100%;
  }
  .content-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    .search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }
    .table-box {
      flex: 1;
      width: 100%;
      height: calc(100vh - 600px);
    }
  }

  .default-btn {
    width: 85px;
  }
  .search-btn {
    width: 85px;
    background-color: var(--bg-primary);
    border: 1px solid var(--success);
  }
  .add-btn {
    width: 85px;
  }

  .health-score {
    color: var(--success);
    cursor: pointer;
    display: block;
    width: 100%;
  }

  .status-matrix {
    width: fit-content;
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #ffffff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    .matrix-row {
      display: flex;
      gap: 6px;
      justify-content: flex-start;
    }

    .status-dot {
      width: 14px;
      height: 14px;
      border-radius: 50%;
      &:hover {
        cursor: pointer;
        transform: scale(1.2);
      }
    }

    .status-normal {
      background-color: #67c23a; // 绿色
    }

    .status-warning {
      background-color: #e6a23c; // 橙色
    }

    .status-error {
      background-color: #f56c6c; // 红色
    }
  }

  .view-btn {
    margin-right: 8px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 12px;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .distribution-table {
    margin-top: 20px;
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
  }

  .table-title {
    font-size: 14px;
    color: var(--success);
    margin-bottom: 16px;
    font-weight: 500;
  }

  :deep(.el-input-number.el-input-number--small) {
    width: 130px;
  }
  :deep(.distribution-table .el-table--border .el-table__cell) {
    border-right: 1px solid #ebeef5 !important;
  }

  .valve-setting {
    .setting-row {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 20px;

      .input-group {
        display: flex;
        align-items: center;
        gap: 8px;

        span {
          white-space: nowrap;
          color: #606266;
        }
      }
    }
  }

  .valve-distribution-grid {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;

    .valve-row {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .valve-cell {
      width: 41px;
      background: white;
      padding: 4px;
      border-radius: 4px;
      text-align: center;
      border: 1px solid #dcdfe6;

      .cell-index {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .cell-value {
        :deep(.el-input-number) {
          width: 100px;
        }
      }
    }
  }

  .readonly-value {
    font-size: 14px;
    color: #606266;
    line-height: 32px;
    padding: 0 12px;
  }

  .distribution-warning {
    display: inline-block;
    font-size: 13px;
    margin-left: 12px;
    padding: 2px 8px;
    border-radius: 4px;

    &.warning-more {
      color: #e6a23c;
      background-color: #fdf6ec;
    }

    &.warning-less {
      color: #f56c6c;
      background-color: #fef0f0;
    }
  }
  .equWarnDialog {
    .equd_body {
      .equd_form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #dce0e4;
      }
      .bold {
        font-weight: bold;
      }
    }
  }
}
</style>
