<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <bg-filter-group @search="changeSearch" v-model="filter.keyword" placeholder="请输入预警点/分类/指标">
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button type="primary" @click="batchPush">
              <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-edit"></bg-icon>
              批量推送
            </el-button>
            <el-button type="default" @click="batchClose">批量关闭</el-button>
            <span class="header_info"
              >已选择 <span style="color: #202531; font-weight: bold"> {{ state.selected.length }} </span> 项
            </span>
            <span class="header_info can_click_text" @click="clearSelected">清空</span>
          </div>
        </template>
        <template v-slot:filter_group>
          <div class="left-filter filter_list">
            <div class="filter_item">
              <span class="filter_title">风险等级</span>
              <el-select v-model="filter.risk_level" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(value, key, index) in riskLevels"
                  :key="'riskLevels' + index"
                  :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">状态</span>
              <el-select v-model="filter.status" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(value, key, index) in statusOptions"
                  :key="'stateOptions' + index"
                  :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">预警时间</span>
              <el-date-picker
                style="width: 400px"
                v-model="filter.time"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </div>
          </div>
          <div class="right-action apaas_button">
            <el-button type="primary" @click="filterAction"> 查询 </el-button>
            <el-button type="default" @click="filterClear"> 重置 </el-button>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <div class="table bg-scroll">
          <bg-table
            ref="dataTable"
            :headers="headers"
            :rows="tableRows"
            @selectAc="selectRows"
            :selectable="selectable"
            :isIndex="true"
            :select="true"
            :stripe="true">
            <template v-slot:alert_point="{ row }">
              <span class="can_click_text" @click="goDetail(row)">
                {{ row.alert_point }}
              </span>
            </template>
            <template v-slot:risk_level="{ row }">
              {{ riskLevels[row.risk_level] }}
            </template>
            <template v-slot:current_value="{ row }">
              {{ row.current_value }}{{ ruleTypeOptions[row.alert_rule_type]?.unit || "" }}
            </template>
            <template v-slot:warn_threshold="{ row }">
              {{ row.alert_condition.thresholds_min }}{{ ruleTypeOptions[row.alert_rule_type]?.unit || "" }}
              -
              {{ row.alert_condition.thresholds_max }}{{ ruleTypeOptions[row.alert_rule_type]?.unit || "" }}
            </template>
            <template v-slot:alert_time="{ row }">
              {{ row.alert_time ? row.alert_time.split("+")[0].replace("T", " ").replace("Z", " ") : "-" }}
            </template>
            <template v-slot:last_push_time="{ row }">
              {{ row.last_push_time ? row.last_push_time.split("+")[0].replace("T", " ").replace("Z", " ") : "-" }}
            </template>
            <template #status="{ row }">
              <span :class="`circle status-${row.status}`"></span>
              {{ statusOptions[row.status] }}
            </template>
            <template v-slot:action="{ row }">
              <bg-table-btns2 :page_size="3" :tableData="tableRows">
                <bg-table-btn :disabled="row.status != 2" @click="pushWarning(row)">推送提醒</bg-table-btn>
                <bg-table-btn :disabled="row.status != 2" @click="closeWarning(row)">关闭预警</bg-table-btn>
              </bg-table-btns2>
            </template>
          </bg-table>
        </div>
        <bg-pagination
          :page="filter.page"
          :size="filter.size"
          :total="tableTotal"
          @change-page="changePage"
          @change-size="changeSize">
        </bg-pagination>
      </div>
    </div>
    <!-- 推送提醒 -->
    <el-dialog title="推送提醒" v-model="pushDialog" width="780px" :before-close="cancelPushDialog">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: middle"
          icon="#bg-ic-s-circle-tips"></bg-icon
        >该推送为临时推送，可调整推送人员，仅本次有效！如固定通知人员，则前往【预警规则设置】调整预警内容
      </div>
      <ManualDistributionForm
        ref="manual_distribution_form"
        :noElLabel="false"
        methodLabel="预警工单推送"
        :history="state.history" />
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="cancelPushDialog">取消</el-button>
          <el-button type="primary" @click="pushConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关闭提醒 -->
    <el-dialog
      class="dialog_box"
      title="关闭预警"
      v-model="closeWarningDialog"
      width="400px"
      :before-close="cancelCloseWarningDialog">
      <el-form ref="closeForm" :model="closeFormData" :rules="closeRules" label-width="80px" class="bg_form">
        <el-form-item label="关闭备注" prop="close_notes">
          <el-input
            v-model="closeFormData.close_notes"
            type="textarea"
            :autosize="{ minRows: 2 }"
            show-word-page_size
            maxlength="30"
            resize="vertical"
            placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="" class="no-el-label" prop="close_remind" style="margin-bottom: 0px">
          <el-checkbox v-model="closeFormData.close_remind">
            <div>三天内将不再自动推送该告警信息给处置人员，</div>
            <div>可手动推送，但告警数据依然会出现</div>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="cancelCloseWarningDialog">取消</el-button>
          <el-button type="primary" @click="confirmClose">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs, computed, watch, nextTick, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { Search } from "@element-plus/icons-vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { useRouter } from "vue-router";
import ManualDistributionForm from "@/components/manual-distribution/form.vue";
import { GetRuleTypeOptions } from "@/components/env.js";

const router = useRouter();

const bgForm = ref(null);
const dataTable = ref(null);
const closeForm = ref(null);
const userTable = ref(null);
const manual_distribution_form = ref(null);
const statusOptions = {
  "": "全部",
  1: "已恢复",
  2: "未恢复",
  3: "已关闭",
};
const ruleTypeOptions = ref({});

const state = reactive({
  riskLevels: {
    "": "全部",
    1: "低风险",
    2: "一般风险",
    3: "较大风险",
    4: "重大风险",
  }, // 风险等级
  headers: [
    {
      label: "预警点",
      prop: "alert_point",
      width: 180,
    },
    {
      label: "预警时间",
      prop: "alert_time",
      width: 160,
    },
    {
      label: "预警分类",
      prop: "class_parent_name",
    },
    {
      label: "预警指标",
      prop: "class_name",
    },
    {
      label: "风险等级",
      prop: "risk_level",
    },
    {
      label: "当前报警值",
      prop: "current_value",
    },
    {
      label: "预警阈值",
      prop: "warn_threshold",
    },
    {
      label: "通知人数",
      prop: "notification_count",
      width: 80,
    },
    {
      label: "推送次数",
      prop: "push_count",
      width: 80,
    },
    {
      label: "最后推送时间",
      prop: "last_push_time",
      width: 160,
    },
    {
      label: "状态",
      prop: "status",
      width: 90,
    },
    {
      label: "操作",
      prop: "action",
      width: 180,
      fixed: "right",
    },
  ],
  tableRows: [], // 表格数据
  selected: [], //选择数据
  tableTotal: 0, // 表格数据条数
  filter: {
    risk_level: "", // 风险等级
    status: "", // 状态
    time: [],
    keyword: "",
    page: 1,
    page_size: 10,
  }, // 表格筛选项
  actionRow: null, // 当前操作的数据
  closeWarningDialog: false, // 删除弹窗
  closeFormData: {
    close_notes: "",
    close_remind: false,
  },
  closeRules: {
    close_notes: [{ required: true, message: "请输入关闭备注", trigger: "blur" }],
  },
  history: null,
  pushDialog: false,
  pushType: 0, // 1-单条推送 2-批量推送
  closeType: 0, // 1-单条推送 2-批量推送
});

const userTableFlag = computed(() => {
  return !!state.pushDialog;
});

const selectRows = (data) => {
  state.selected = data.selection;
};

const clearSelected = () => {
  dataTable.value.clearTable();
}; // 清空

const batchClose = () => {
  if (!state.selected || state.selected.length == 0) {
    ElMessage.error("请先勾选要关闭的预警数据");
    return;
  }
  state.closeType = 2;
  state.closeWarningDialog = true;
}; // 批量关闭

const goDetail = (row) => {
  router.push(`/forewarning/list/detail?id=${row.id}`);
}; // 查看详情

const changeSearch = (val) => {
  state.filter.keyword = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  state.filter = {
    warning_type: "", // 预警类型
    warning_target: "", // 预警指标
    risk_level: "", // 风险等级
    status: "", // 状态
    time: [],
    keyword: "",
    page: 1,
    page_size: 10,
  };
  changePage(1);
}; // 重置筛选项
const selectable = (row, index) => {
  return row.status === 2;
};
const getTableRows = () => {
  let [start_time = "", end_time = ""] = state.filter.time || [];
  let params = {
    ...state.filter,
    start_time,
    end_time,
  };
  Reflect.deleteProperty(params, "time");
  axios.get("/v1/api/alert_list/list", { params }).then((res) => {
    if (res.data.code == 200) {
      let { list, total_count } = res.data.data;
      state.tableRows = list || [];
      state.tableTotal = total_count;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}; // 获取表格数据

const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码

const changeSize = (size) => {
  state.filter.page_size = size;
  changePage(1);
}; // 改变每页条数

const batchPush = () => {
  if (!state.selected || state.selected.length == 0) {
    ElMessage.error("请先勾选要推送的数据");
    return;
  }
  state.pushType = 2;
  state.history = null;
  state.pushDialog = true;
}; // 批量推送
const pushWarning = (row) => {
  state.actionRow = row;
  state.pushType = 1;
  state.pushDialog = true;
  let alert_rules_id = row.alert_rules_id;
  axios.get(`/v1/api/alert_rules/list`, { params: { id: alert_rules_id } }).then((res) => {
    if (res.data.code == 200) {
      if (!res.data.data.list || res.data.data.list.length == 0) return;
      state.history = {
        method: res.data.data.list[0].notify_method || [],
        lists:
          res.data.data.list[0].notify_recipients?.map((e) => {
            return {
              user_id: e.system_account,
              user_name: e.user_name,
              phone: e.phone,
            };
          }) || [],
      };
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}; // 推送提醒

const cancelPushDialog = () => {
  state.pushDialog = false;
}; // 预警推送弹窗取消按钮：重置表单

const pushConfirm = async () => {
  const manual_distribution_form_valid = await manual_distribution_form.value.Submit();
  if (!manual_distribution_form_valid) return;
  const { method, lists } = manual_distribution_form.value.form || {};
  let params = {
    ids: state.pushType == 1 ? [`${state.actionRow.id}`] : state.selected.map((e) => `${e.id}`),
    notify_method: method || [],
    notify_recipients: lists?.map((e) => {
      return {
        system_account: e.user_id,
        user_name: e.user_name,
        phone: e.phone,
      };
    }),
  };
  axios
    .put("/v1/api/alert_list/batch/push", params)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("推送成功");
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .finally((e) => {
      cancelPushDialog();
      clearSelected();
      changePage(1);
    });
};
const closeWarning = (row) => {
  state.actionRow = row;
  state.closeType = 1;
  state.closeWarningDialog = true;
  console.log("关闭预警");
}; // 关闭预警

const cancelCloseWarningDialog = () => {
  closeForm.value.resetFields();
  state.closeWarningDialog = false;
}; // 关闭预警弹窗取消按钮：重置表单

const confirmClose = () => {
  closeForm.value.validate((valid) => {
    if (valid) {
      let params = {
        ids: state.closeType == 1 ? [state.actionRow.id] : state.selected.map((e) => e.id),
        close_remark: state.closeFormData.close_notes,
        defer_push: state.closeFormData.close_remind ? 1 : 0,
      };
      axios
        .put("/v1/api/alert_list/batch/close", params)
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success("关闭预警操作成功");
          } else {
            ElMessage.error(res.dta.msg);
          }
        })
        .finally((e) => {
          cancelCloseWarningDialog();
          clearSelected();
          changePage(1);
        });
    }
  });
}; // 关闭预警弹窗确定按钮：提交表单
const getRuleTypeOptions = async () => {
  ruleTypeOptions.value = await GetRuleTypeOptions();
  getTableRows();
};
onBeforeMount(() => {
  getRuleTypeOptions();
});

const {
  headers,
  tableRows,
  tableTotal,
  filter,
  riskLevels,
  stateOptions,
  closeWarningDialog,
  closeFormData,
  closeRules,
  pushDialog,
} = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  height: calc(100vh - 56px);
  padding: 0 24px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    height: 100%;
    .filter-group {
      .left-filter {
        flex: 1;
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
      }
      .right-action {
        width: 144px;
        padding-bottom: 16px;
        .el-button {
          width: 64px;
        }
      }
    }

    .table_container {
      height: calc(100% - 70px);
      width: 100%;
      padding: 0 16px;
      .table {
        max-height: calc(100% - 64px);
        .circle {
          display: inline-block;
          width: 6px;
          height: 6px;
          border-radius: 3px;
          transform: translateY(-2px);
        }
        .status {
          $statusObj: (
            1: #48ad97,
            3: #9e9e9e,
            2: #3759be,
          );
          @each $status, $color in $statusObj {
            &-#{$status} {
              background-color: $color;
            }
          }
        }
      }
    }
  }

  .bg_form {
    width: 100%;
    box-sizing: border-box;
    .el-form-item {
      margin-bottom: 16px;
      :deep().el-form-item__label {
        line-height: 36px;
        height: 36px;
      }
      .el-form-item__content {
        width: 100%;
        .el-textarea {
          :deep().el-input__count {
            bottom: 6px;
            right: 4px;
            font-family: Roboto-Regular;
            color: #a9b1c7;
          }
        }
      }
    }
  }
  :deep().dialog_box {
    .el-dialog__body {
      padding-bottom: 0;
    }
  }
}
.no-el-label {
  :deep(.el-form-item__content) {
    text-align: left;
    margin-left: 10px !important;
    .el-checkbox__label {
      line-height: 18px;
    }
  }
}
</style>
