<template>
  <div class="static-form">
    <el-form :model="state.form" ref="form_ref" :rules="state.rules" label-width="110px">
      <div class="static-form-item">
        <el-form-item label="预警对象/分类" prop="warn_type">
          <el-cascader
            :disabled="props.isEdit"
            ref="cascader_ref"
            style="flex: 1"
            placeholder="请选择预警对象/分类"
            :options="staticTypeOptions"
            v-model="state.form.warn_type"
            @change="changeWarnStaticType"
            :props="cascaderProps">
          </el-cascader>
        </el-form-item>
        <el-form-item label="预警指标" prop="warn_indicator">
          <el-select
            style="flex: 1"
            :disabled="!formFormat.warn_type || props.isEdit"
            v-model="state.form.warn_indicator"
            placeholder="请选择预警指标">
            <el-option v-for="(value, key) in warningIndexOptions" :key="key" :label="value" :value="key"> </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div>
        <div v-if="state.form.warning_scpoe_form.length > 0">
          <gap-title :hasLine="true" title="预警范围"></gap-title>
          <div class="static-form-item">
            <div class="warning-scope-main">
              <div class="warn-scpoe-form" v-for="(item, index) in state.form.warning_scpoe_form" :key="index">
                <el-form-item :label="item.chinese_name">
                  <el-select
                    class="warn-scpoe-select"
                    v-model="item.select"
                    style="width: 114px"
                    @change="changeSelect(index, item)">
                    <el-option v-for="(value, key) in selectRule" :key="key" :label="value" :value="key" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  label=""
                  class="no-el-label warn-scpoe-input-item"
                  prop="value"
                  :rules="[
                    {
                      validator: (rule, value, callback) => validateValue(rule, value, callback, item, index),
                      trigger: showSelect.includes(item.select) ? 'change' : 'blur',
                    },
                  ]">
                  <el-input
                    class="warn-scpoe-input-value"
                    v-model="state.form.warning_scpoe_form[index].value"
                    :placeholder="`请输入${item.chinese_name}`"
                    v-if="!showSelect.includes(item.select)"
                    :disabled="item.select == 1">
                  </el-input>
                  <el-select
                    class="warn-scpoe-input-value"
                    v-else
                    v-model="item.value"
                    :placeholder="`请选择${item.chinese_name}`"
                    filterable
                    :loading="item.loading"
                    remote
                    :remote-method="(query) => remoteMethod(query, index)"
                    multiple>
                    <el-option v-for="item in item.options" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <gap-title :hasLine="true" title="预警规则"></gap-title>
        <div class="static-form-item">
          <div class="warning-rule-main">
            <el-form-item label="风险程度" prop="risk_level" v-if="isEmpty">
              <el-select style="flex: 1" v-model="state.form.risk_level" placeholder="请选择风险程度" filterable>
                <el-option v-for="item in riskLevelOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <Gateway v-else ref="warn_type_com" :rule_type="alert_rule_type" />
          </div>
        </div>
      </div>
      <!-- <component
        ref="warn_type_com"
        :is="warnTypeCom[formFormat.warn_type]"
        :type="formFormat.warn_type"
        :form="warn_type_com_form"
        v-if="formFormat.warn_type"></component> -->
    </el-form>
  </div>
</template>

<script setup>
import { computed, nextTick, reactive, ref, shallowReactive, watch } from "vue";
import gapTitle from "@/components/gap-title.vue";
// import CommonCom from "./common-com.vue";
import Gateway from "./gateway.vue";
const showSelect = ["4", "5"];
const selectRule = ref({
  1: "全部",
  2: "等于",
  3: "不等于",
  4: "正则匹配",
  5: "正则不匹配",
});
const riskLevelOptions = ref([
  {
    id: 1,
    name: "重大风险",
  },
  {
    id: 2,
    name: "较大风险",
  },
  {
    id: 3,
    name: "一般风险",
  },
  {
    id: 4,
    name: "低风险",
  },
]);
// const warnTypeCom = shallowReactive({
//   colony: CommonCom,
//   node: CommonCom,
//   group: CommonCom,
//   gateway: Gateway,
// });
const props = defineProps({
  form: {
    type: Object,
    default: null,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});
const changeSelect = (index, item) => {
  console.log("item.select: ", item.select);
  if (showSelect.includes(item.select)) {
    state.form.warning_scpoe_form[index].value = [];
  } else {
    state.form.warning_scpoe_form[index].value = "";
  }
};
const validateValue = (rule, value, callback, item, index) => {
  if (!item.is_required || item.select == 1) return callback();
  if (item.value == "") {
    let msg = showSelect.includes(item.select) ? `请选择${item.chinese_name}` : `请输入${item.chinese_name}`;
    return callback(new Error(msg));
  }
  return callback();
};
const state = reactive({
  form: {
    warn_type: [],
    warn_indicator: "",
    risk_level: "",
    warning_scpoe_form: [],
  },
  rules: {
    warn_type: [{ type: "array", required: true, message: "请选择预警对象/分类", trigger: "change" }],
    warn_indicator: [{ required: true, message: "请选择预警指标", trigger: "change" }],
    risk_level: [{ required: true, message: "请选择风险程度", trigger: "change" }],
  },
});
const module_data = {
  id: "20da8f87-628a-4f0c-bd9c-0ad176d18d59",
  class_id: 101,
  metric_name: "xx请求次数告警",
  expr: 'shttp_requests_total{method="GET",$pod$}',
  duration: 5,
  duration_unit: "m",
  check_period: 3,
  is_enabled: 1,
  alert_rule_type: "9f1e6170-65e8-4e14-9c17-6a7b87a900a7",
  created_by: "",
  created_at: "2023-06-28 17:28:29",
  updated_by: "",
  updated_at: "2023-06-28 17:54:33",
  alert_range: [
    {
      variable_name: "$pod$",
      metric_name: "shttp_requests_total",
      metric_label: "pod",
      chinese_name: "demoString",
      is_required: true,
      is_linked: true,
    },
    {
      variable_name: "$image$",
      metric_name: "shttp_requests_total",
      metric_label: "image",
      chinese_name: "镜像",
      is_required: true,
      is_linked: true,
    },
  ],
};
const isEmpty = computed(() => {
  return false;
  //   return module_data.alert_rule_type == "9f1e6170-65e8-4e14-9c17-6a7b87a900a7";
});
state.form.warning_scpoe_form = module_data.alert_range.map((e) => {
  return {
    ...e,
    value: "",
    select: "1",
    options: [],
    loading: false,
  };
});
watch(
  () => state.form,
  (n) => {
    console.log(n);
  },
  {
    deep: true,
  }
);
const remoteMethod = (query, index) => {
  console.log("query, index: ", query, index);
  if (!query) {
    state.form.warning_scpoe_form[index].options = [];
    return;
  }
  state.form.warning_scpoe_form[index].loading = true;
  setTimeout(() => {
    state.form.warning_scpoe_form[index].loading = false;
    state.form.warning_scpoe_form[index].options = [
      {
        id: 1,
        name: 111,
      },
      {
        id: 2,
        name: 222,
      },
    ];
  }, 1000);
};
const warn_type_com_form = computed(() => props.form?.warn_type_com || null);
watch(
  () => props.form,
  (n) => {
    if (!n) return;
    state.form.warn_type = n.warn_target && n.warn_type ? [n.warn_target, n.warn_type] : [];
    state.form.warn_indicator = n.warn_indicator;
  },
  { deep: true, immediate: true }
);
const cascaderProps = {
  value: "id",
  label: "label",
};
const staticTypeOptions = [
  {
    id: "1",
    label: "容器云平台",
    children: [
      {
        id: "colony",
        label: "容器集群",
        options: {
          1: "服务中断",
          2: "CPU使用率",
          3: "内存使用率",
          4: "磁盘使用率",
        },
      },
      {
        id: "node",
        label: "容器节点",
        options: {
          1: "服务中断",
          2: "CPU使用率",
          3: "内存使用率",
          4: "磁盘使用率",
        },
      },
      {
        id: "group",
        label: "容器组",
        options: {
          1: "服务中断",
          2: "CPU使用率",
          3: "内存使用率",
        },
      },
      {
        id: "gateway",
        label: "网关",
        options: {
          1: "平均响应时长（入口网关）",
        },
      },
    ],
  },
];
const formFormat = computed(() => {
  let [warn_target = "", warn_type = ""] = state.form.warn_type || [];
  let obj = {
    ...state.form,
    warn_target,
    warn_type,
    isEmpty: isEmpty.value,
  };
  if (isEmpty.value) {
    obj.warn_type_com = warn_type_com.value?.form || {};
  }
  return obj;
});
const warningIndexOptions = ref({});
const cascader_ref = ref(null);
const changeWarnStaticType = async () => {
  const { data } = cascader_ref.value.getCheckedNodes()[0];
  warningIndexOptions.value = data.options;
  let keys = Object.keys(warningIndexOptions.value);
  state.form.warn_indicator = keys[0];
  setTimeout(() => {
    form_ref.value.clearValidate(["warn_indicator"]);
  });
};
const changeRuleType = () => {};
const form_ref = ref(null);
const warn_type_com = ref(null);
const Submit = async () => {
  let form_valid = await new Promise((resolve, reject) => {
    form_ref.value.validate((res) => resolve(res));
  });
  if (isEmpty.value) return form_valid;
  let warn_type_com_valid = (await warn_type_com.value?.Submit()) || true;
  return form_valid && warn_type_com_valid;
};
const ruleHeaders = [
  {
    prop: "warning_threshold",
    label: "预警阈值",
    width: "500px",
  },
  {
    prop: "risk_level",
    label: "风险程度",
  },
];
defineExpose({
  Submit,
  form: formFormat,
  form_ref,
});
</script>

<style lang="scss" scoped>
.static-form {
  :deep(.gap-title) {
    margin-bottom: 16px;
  }
  &-item {
    max-width: 1080px;
    width: 100%;
    padding-left: 8px;
    .warning-scope-main {
      //   display: grid;
      //   grid-template-columns: 1fr 1fr;
      //   grid-column-gap: 16px;
      :deep(.el-input-group__prepend) {
        border-radius: 4px;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .warn-scpoe-form {
        width: 100%;
        display: flex;
        align-items: center;
        .warn-scpoe-select {
          width: 114px !important;
          :deep(.el-input__wrapper) {
            background-color: #2b4695;
            border-radius: 4px;
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
            .el-input__inner {
              color: #fff;
            }
          }
        }
        .warn-scpoe-input-item {
          flex: 1;
          .warn-scpoe-input-value {
            flex: 1;
            :deep(.el-input__wrapper) {
              border-top-left-radius: 0;
              border-bottom-left-radius: 0;
            }
          }
        }
      }
    }
  }
}
.no-el-label {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>
