<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container bg-scroll">
      <gap-title :hasLine="true" title="基本信息"></gap-title>
      <div class="info">
        <Info :labelData="labelData" :valueData="info">
          <template #status="{ item, valueData }">
            <span class="status-body">
              <span class="status" :class="`status-${valueData.status}`"></span>
              <span>{{ STATUS_OBJ[valueData[item.prop]] }}</span>
            </span>
          </template>
        </Info>
      </div>
      <div class="warn-scope" v-if="detection_type == 1 && watning_scope_data_key.length > 0">
        <gap-title :hasLine="true" title="预警范围"></gap-title>
        <div class="info">
          <Info :labelData="warning_scope_label" :valueData="watning_scope_data"> </Info>
        </div>
      </div>
      <div class="warn-scope" v-else>
        <gap-title :hasLine="true" title="指标表达式"></gap-title>
        <div class="indicator-expression">
          <!-- <bg-code-editor v-model="indicator_expression" :disabled="true"></bg-code-editor> -->
          <bg-codemirror :disabled="true" v-model="indicator_expression"></bg-codemirror>
        </div>
      </div>
      <gap-title :hasLine="true" title="预警规则"></gap-title>
      <div class="info">
        <bg-table border ref="ruletable" :headers="ruleHeaders" :rows="ruleRows" height="100%"> </bg-table>
      </div>
      <gap-title :hasLine="true" title="高级配置"> </gap-title>
      <div class="info">
        <Info :labelData="advanced_label" :valueData="advanced_data"> </Info>
      </div>
      <gap-title :hasLine="true" title="预警工单推送"> </gap-title>
      <div class="info">
        <Info :labelData="ticket_push_label" :valueData="ticket_push_data">
          <template #notification_method="{ valueData }">
            <span>{{ valueData.notification_method?.map((e) => METHODS[e]).join("，") || "" }}</span>
          </template>
        </Info>
        <div class="push-lists">
          <bg-table border ref="pushtable" :headers="pushHeaders" :rows="pushRows" height="100%" :isIndex="true">
          </bg-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, computed } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { useRoute } from "vue-router";
import gapTitle from "@/components/gap-title.vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import Info from "@/components/warn-detail/info.vue";
import { METHODS } from "@/components/manual-distribution/env.js";
import { GetRuleTypeOptions, Empty, WIELESS_SMALL, WIELESS_BIG } from "@/components/env.js";
const route = useRoute();
const { id } = route.query;
const STATUS_OBJ = ["禁用", "启用"];
const ruleTypeOptions = ref({});
const selectRule = {
  "=": "等于",
  "!=": "不等于",
  "=~": "正则匹配",
  "!~": "正则不匹配",
};
const riskLevelOptions = {
  4: "重大风险",
  3: "较大风险",
  2: "一般风险",
  1: "低风险",
};
const unitOptions = {
  s: "秒",
  m: "分钟",
  h: "小时",
};
const labelData = [
  [
    {
      label: "预警规则名称",
      prop: "warning_rule_name",
    },
    {
      label: "启用状态",
      prop: "status",
    },
  ],
  [
    {
      label: "预警分类",
      prop: "warning_target",
    },
    {
      label: "预警对象",
      prop: "warning_type",
    },
  ],
  [
    {
      label: "预警指标",
      prop: "warning_index",
    },
    {
      label: "创建人",
      prop: "create_by",
    },
  ],
  [
    {
      label: "创建时间",
      prop: "create_time",
    },
    {
      label: "更新时间",
      prop: "update_time",
    },
  ],
];
const info = ref({});
const warning_scope_label = ref([]);
const watning_scope_data = ref({});
const advanced_label = [
  [
    {
      prop: "duration",
      label: "持续时间",
    },
  ],
  [
    {
      prop: "inspection_cycle",
      label: "检查周期",
    },
  ],
];
const advanced_data = ref({});
const ticket_push_label = [
  [
    {
      prop: "notification_method",
      label: "预警通知方式",
    },
  ],
  [
    {
      prop: "push_num",
      label: "消息推送次数",
    },
  ],
  [
    {
      prop: "push_frequency",
      label: "消息推送频率",
    },
  ],
];
const ticket_push_data = ref({});
const ruleHeaders = ref([
  {
    prop: "risk_level",
    label: "风险程度",
  },
]);
const ruleRows = ref([]);
const pushHeaders = [
  {
    prop: "system_account",
    label: "账号",
  },
  {
    prop: "user_name",
    label: "姓名",
  },
  {
    prop: "phone",
    label: "联系方式",
  },
];
const pushRows = ref([]);
const detection_type = ref(1);
const indicator_expression = ref("");
const getInfoData = () => {
  axios
    .get("/v1/api/alert_rules", {
      params: {
        id: id,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        const { data } = res.data;
        detection_type.value = data.detection_type;
        indicator_expression.value = data.expr;
        info.value = {
          warning_rule_name: data.metric_name,
          status: data.is_enabled,
          warning_target: data.class_parent_name,
          warning_type: data.class_name,
          warning_index: data.metric_config_name,
          create_by: data.created_by,
          create_time: data.created_at,
          update_time: data.updated_at,
        };
        data.alert_range.forEach((e) => {
          warning_scope_label.value.push([
            {
              prop: e.chinese_name || e.name,
              label: e.chinese_name || e.name,
            },
          ]);
          watning_scope_data.value[e.chinese_name || e.name] =
            e.value == ".*" ? "全部" : `${selectRule[e.compare]} ${e.value}`;
        });
        let isEmpty = Empty(data.alert_rule_type, ruleTypeOptions.value);
        if (!isEmpty) {
          ruleHeaders.value = [
            {
              prop: "warning_threshold",
              label: "预警阈值",
            },
            ...ruleHeaders.value,
          ];
        }
        let unit = ruleTypeOptions.value[data.alert_rule_type]?.unit || "";
        ruleRows.value = data.alert_condition.map((e) => {
          let min = e.thresholds_min + unit;
          if (e.thresholds_min === undefined) {
            if (ruleTypeOptions.value[data.alert_rule_type].down !== "") {
              min = ruleTypeOptions.value[data.alert_rule_type].down + unit;
            } else {
              min = WIELESS_SMALL;
            }
          }
          let max = e.thresholds_max + unit;
          if (e.thresholds_max === undefined) {
            if (ruleTypeOptions.value[data.alert_rule_type].up !== "") {
              max = ruleTypeOptions.value[data.alert_rule_type].up + unit;
            } else {
              max = WIELESS_BIG;
            }
          }
          return {
            warning_threshold: `${min} - ${max}`,
            risk_level: riskLevelOptions[e.risk_level],
          };
        });
        advanced_data.value = {
          duration: data.duration == 0 ? "直接产生预警" : data.duration + unitOptions[data.duration_unit],
          inspection_cycle: data.check_period + "分钟",
        };
        ticket_push_data.value = {
          notification_method: data.notify_method,
          push_num: data.notify_push_count + "次",
          push_frequency: data.notify_push_frequency + "分钟",
        };
        pushRows.value = data.notify_recipients;
      } else {
        ElMessage.error(res.data.data);
      }
    });
};
const getRuleTypeOptions = async () => {
  ruleTypeOptions.value = await GetRuleTypeOptions();
  getInfoData();
};
onBeforeMount(() => {
  getRuleTypeOptions();
});
</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%;
    padding: 24px;
    :deep(.gap-title) {
      margin-bottom: 16px;
    }
    .warn-scope {
      margin-bottom: 24px;
      .indicator-expression {
        height: 300px;
        width: 100%;
        :deep(.vue-ace-editor) {
          margin-top: 0;
        }
      }
    }
    .info {
      max-width: 1072px;
      width: 100%;
      padding: 0 8px 0;
      &:not(:last-child) {
        padding-bottom: 24px;
      }
      .push-lists {
        margin-top: 16px;
      }
    }
  }
}
.status {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 8px;
  $statusObj: (
    1: #48ad97,
    0: #9e9e9e,
  );
  @each $status, $color in $statusObj {
    &-#{$status} {
      background-color: $color;
    }
  }
}
.status-body {
  display: flex;
  align-items: center;
}
</style>
