<template>
  <div class="page-container collectorList all-select-btn" data-testid="about-view-container">
    <div class="content-box" data-testid="content-box">
      <div class="search" data-testid="search-area">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" data-testid="search-form">
          <el-form-item label="事件名称">
            <el-input
              v-model="formInline.eventName"
              placeholder="请输入事件名称"
              style="width: 200px"
              clearable
              data-testid="event-name-input"
            />
          </el-form-item>
          <el-form-item label="发生位置">
            <el-input
              v-model="formInline.name"
              placeholder="请输入发生位置"
              style="width: 200px"
              clearable
              data-testid="location-input"
            />
          </el-form-item>
          <el-form-item label="除尘器名称">
            <el-input
              v-model="formInline.dusterName"
              placeholder="请输入除尘器名称"
              style="width: 200px"
              clearable
              data-testid="duster-name-input"
            />
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="formInline.deviceType" style="width: 200px" data-testid="device-type-select">
              <el-option
                v-for="(i, index) in typeList.list"
                :key="i"
                :label="`${i.desc}`"
                :value="i.code"
                :id="`device-type-option-${index}`"
              />
            </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"
              data-testid="alarm-date-picker"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="default" class="reset-btn-balck-theme" @click="onReset" data-testid="reset-button"
              >重置</el-button
            >
            <el-button type="default" class="search-btn-balck-theme" @click="onSubmit" data-testid="search-button"
              >查询</el-button
            >
            <el-button
              type="default"
              style="width: 140px"
              class="export-btn-balck-theme"
              @click="openRound()"
              data-testid="suspend-device-button"
              >挂起设备</el-button
            >
          </el-form-item>
          <br />
          <el-form-item>
            <el-radio-group v-model="formInline.suspendFlag" @change="onSubmit" data-testid="suspend-flag-radio-group">
              <el-radio value="1" data-testid="suspend-flag-radio-during">挂起期间告警</el-radio>
              <el-radio value="0" data-testid="suspend-flag-radio-normal">非挂起期间告警</el-radio>
              <el-radio value="2" data-testid="suspend-flag-radio-all">全部告警</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-box" data-testid="table-container">
        <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: '跳至',
          }"
          data-testid="alarm-table"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #operate="{ row }">
            <span class="health-score green-color" @click="openDialog(row)" data-testid="suspend-action-link">暂挂起</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"
      data-testid="suspend-dialog"
    >
      <div class="equd_body" data-testid="dialog-body">
        <el-form
          ref="ruleFormRef"
          :model="equSubmitInfo"
          :rules="rules"
          class="equd_form"
          data-testid="suspend-form"
        >
          <span
            >是否要对<span class="bold">{{ clickItem.name }}</span
            >不再告警：</span
          >
          <el-form-item>
            <el-radio-group v-model="equSubmitInfo.noAlarm" @change="onSubmit" data-testid="no-alarm-radio-group">
              <el-radio value="1" data-testid="no-alarm-radio-yes">是</el-radio>
              <el-radio value="0" data-testid="no-alarm-radio-no">否</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"
              data-testid="start-time-picker"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="equSubmitInfo.endTime"
              type="datetime"
              placeholder="选择结束时间"
              popper-class="date-picker-popper"
              data-testid="end-time-picker"
            />
          </el-form-item>
          <el-form-item label="原因分类" prop="reasonCategory">
            <el-select v-model="equSubmitInfo.reasonCategory" style="width: 220px;" data-testid="reason-category-select">
              <el-option v-for="(item, index) in reasonCategoryList" :key="item.key" :value="item.key" :label="item.value" :id="`reason-category-option-${index}`"></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;" data-testid="reason-description-textarea"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer " data-testid="dialog-footer">
          <el-button type="default" class="cancel-btn-balck-theme" @click="equDialog = false" data-testid="cancel-button">取消</el-button>
          <el-button type="default" class="search-btn-balck-theme" @click="equPending(ruleFormRef)" data-testid="confirm-button">
            确认
          </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>
