<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="add-form-main bg-scroll">
        <add-form ref="add_form" :row="infoData"></add-form>
      </div>
      <div class="add-btns">
        <el-button size="default" @click="Cancle">取消</el-button>
        <el-button type="primary" size="default" @click="SaveSubmit">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from "vue";
import { useRouter, useRoute } from "vue-router";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import addForm from "../modules/add-form.vue";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
import { Save } from "../modules/interface.js";
import { Empty, GetRuleTypeOptions } from "@/components/env.js";
const infoData = ref({});
const ruleTypeOptions = ref({});
const router = useRouter();
const route = useRoute();
const { id } = route.query;
const Cancle = () => {
  router.go(-1);
};
const add_form = ref(null);
const SaveSubmit = async () => {
  let res = await add_form.value.Submit();
  if (!res) return;
  console.log("res: ", res);
  Save(res, { id }, () => {
    Cancle();
  });
};
const staticTypeOptions = ref([]);
const findTypeBySecond = (id) => {
  return staticTypeOptions.value.find((e) => {
    return e.children.find((e_c) => e_c.class_id == id);
  });
};
const getInfoData = () => {
  axios
    .get("/v1/api/alert_rules", {
      params: {
        id: id,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        const { data } = res.data;
        let isEmpty = Empty(data.alert_rule_type, ruleTypeOptions.value);
        let type_json = {
          1: () => {
            let obj = {
              key: "static",
              type_com_ref: {
                warn_type: data.class_id,
                warn_indicator: data.metric_config_id,
                warn_target: findTypeBySecond(data.class_id)?.class_id || "",
                rule_type: data.alert_rule_type,
              },
            };
            if (isEmpty) {
              obj.type_com_ref.risk_level = data.alert_condition[0].risk_level;
            } else {
              obj.type_com_ref.warning_scpoe_form =
                data.alert_range?.map((e) => {
                  return {
                    ...e,
                    value: e.value == ".*" ? "" : e.value,
                    select: e.value == ".*" ? "all" : e.compare,
                    options: [],
                  };
                }) || [];
              obj.type_com_ref.ruleRows =
                data.alert_condition?.map((e) => {
                  return {
                    from: e.thresholds_min,
                    to: e.thresholds_max,
                    risk_level: e.risk_level,
                  };
                }) || [];
            }
            return obj;
          },
          2: () => {
            let obj = {
              key: "custom",
              type_com_ref: {
                warn_target: data.class_parent_name,
                warn_type: data.class_name,
                warn_indicator: data.metric_config_name,
                indicator_expression: data.expr,
                rule_type: data.alert_rule_type,
              },
            };
            if (isEmpty) {
              obj.type_com_ref.risk_level = data.alert_condition[0].risk_level;
            } else {
              obj.type_com_ref.ruleRows =
                data.alert_condition?.map((e) => {
                  return {
                    from: e.thresholds_min,
                    to: e.thresholds_max,
                    risk_level: e.risk_level,
                  };
                }) || [];
            }
            return obj;
          },
        };
        let d = type_json[`${data.detection_type}`]();
        infoData.value = {
          name: data.metric_name,
          type_key: d.key,
          unit: data.duration_unit,
          time: data.duration,
          inspection_cycle: data.check_period,
          push_num: data.notify_push_count,
          push_frequency: data.notify_push_frequency,
          enabled: data.is_enabled ? 1 : 2,
          type_com_ref: d.type_com_ref,
          manual_distribution_form: {
            method: data.notify_method,
            lists:
              data.notify_recipients?.map((e) => {
                return {
                  user_id: e.system_account,
                  user_name: e.user_name,
                  phone: e.phone,
                };
              }) || [],
          },
        };
      } else {
        ElMessage.error(res.data.data);
      }
    });
};
const getRuleTypeOptions = async (cb) => {
  ruleTypeOptions.value = await GetRuleTypeOptions();
  getInfoData();
};
const getStaticTypeOptions = () => {
  axios.get("/v1/api/alert_class/tree").then(async (res) => {
    if (res.data.code == 200) {
      staticTypeOptions.value = res.data.data;
      getRuleTypeOptions();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
onBeforeMount(() => {
  getStaticTypeOptions();
});
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  height: calc(100vh - 56px);
  padding: 0 24px 16px;
  min-height: 100%;
  .main_container {
    height: calc(100% - 46px);
    padding: 0;
    .add-form-main {
      padding: 24px;
      height: calc(100% - 68px);
    }
    .add-btns {
      height: 68px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      border-top: 1px solid #ddd;
      padding: 0 24px;
    }
  }
}
</style>
