<template>
  <div class="add-form">
    <el-form :model="state.form" ref="form_ref" :rules="state.rules" label-width="120px">
      <div class="add-form-item">
        <el-form-item label="指标名称" prop="name">
          <el-input v-model="state.form.name" :disabled="isEdit" placeholder="请输入指标名称"></el-input>
        </el-form-item>
        <el-form-item label="指标表达式" prop="indicator_expression">
          <div class="indicator-expression">
            <bg-code-editor v-model="state.form.indicator_expression"></bg-code-editor>
            <!-- <bg-codemirror v-model="state.form.indicator_expression"></bg-codemirror> -->
          </div>
        </el-form-item>
        <el-form-item label="预警范围" prop="">
          <warningScope
            :indicator_expression="state.form.indicator_expression"
            ref="table_form_ref"
            :warningScopeRows="warningScopeRows" />
        </el-form-item>
        <el-form-item label="预警规则类型" prop="rule_type">
          <el-select style="flex: 1" v-model="state.form.rule_type" placeholder="请选择" filterable>
            <el-option v-for="(value, key) in ruleTypeOptions" :key="key" :label="value.label" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="duration">
          <el-form-item label="持续时间" prop="time">
            <el-input v-model="state.form.time" placeholder="请输入持续时间" @input="inputNum">
              <template #prepend>
                <span>当预警持续</span>
              </template>
              <template #append>
                <el-select v-model="state.form.unit" placeholder="请选择">
                  <el-option v-for="(value, key) in unitOptions" :key="key" :label="value.label" :value="key">
                  </el-option>
                </el-select>
              </template>
            </el-input>
            <span class="duration-append">
              <span> 时产生报警 </span>
              <el-popover
                :width="300"
                title=""
                content="大于等于0的正整数，等于0时代表直接报警"
                trigger="hover"
                placement="top-start">
                <template #reference>
                  <bg-icon
                    style="font-size: 12px; color: #a9b1c7; margin-left: 8px; vertical-align: middle"
                    icon="#bg-ic-s-circle-tips"></bg-icon>
                </template>
              </el-popover>
            </span>
          </el-form-item>
        </div>
        <el-form-item label="检查周期" prop="inspection_cycle">
          <div style="flex: 1; display: flex; align-items: center; gap: 8px">
            <el-select style="flex: 1" v-model="state.form.inspection_cycle" placeholder="请选择检查周期">
              <el-option v-for="item in inspectionCycleOptions" :key="item" :label="item" :value="item"> </el-option>
            </el-select>
            <span>分钟</span>
          </div>
        </el-form-item>
        <el-form-item label="是否立即启用">
          <el-switch
            class="bg-switch-ele"
            v-model="state.form.state"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="是"
            inactive-text="否" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch, onMounted } from "vue";
import gapTitle from "@/components/gap-title.vue";
import ManualDistributionForm from "@/components/manual-distribution/form.vue";
import { MAX_DAY, ONLY_INPUT_NUM } from "@/components/env.js";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import warningScope from "./warning-scope.vue";
import { GetRuleTypeOptions, Empty } from "@/components/env.js";
const props = defineProps({
  row: {
    type: Object,
    default: null,
  },
});
// 当前是否是编辑
const isEdit = computed(() => !!props.row);
// 获取旧数据
const warningScopeRows = computed(() => props.row?.warningScopeRows || []);
// 持续时间单位
const unitOptions = {
  s: { label: "秒", max: MAX_DAY * 24 * 3600 },
  m: { label: "分钟", max: MAX_DAY * 24 * 60 },
  h: { label: "小时", max: MAX_DAY * 24 },
};
const state = reactive({
  form: {
    name: "",
    indicator_expression: "",
    rule_type: "",
    time: 10,
    unit: "s",
    inspection_cycle: 1,
    state: 1,
  },
  rules: {
    name: [{ required: true, message: "请输入指标名称", trigger: "blur" }],
    rule_type: [{ required: true, message: "请选择预警规则类型", trigger: "change" }],
    indicator_expression: [{ required: true, message: "请输入指标表达式", trigger: "blur" }],
    time: [{ required: true, message: "请输入持续时间", trigger: "blur" }],
  },
});
// 预警规则类型下拉
const ruleTypeOptions = ref({});
const getRuleTypeOptions = async () => {
  ruleTypeOptions.value = await GetRuleTypeOptions();
};
// 当预警持续输入限制
const inputNum = () => {
  state.form.time = state.form.time.replace(/[^\d]/g, "");
  let time = +state.form.time;
  let { max } = unitOptions[state.form.unit];
  if (time > +max) {
    state.form.time = max;
    ElMessage.closeAll();
    ElMessage.error(`最大值：${max}`);
  }
};
// 检查周期下拉数据
const inspectionCycleOptions = ref([1, 3, 5, 10, 20]);
// form表单元素
const form_ref = ref(null);
// table的form表单元素
const table_form_ref = ref(null);
// 提交调用
const Submit = async () => {
  let form_valid = await new Promise((resolve, reject) => {
    form_ref.value.validate((res) => resolve(res));
  });
  let table_form_valid = await table_form_ref.value.Submit();
  if (form_valid && table_form_valid) {
    let obj = {
      ...state.form,
      ...table_form_ref.value?.form,
    };
    if (!isEdit.value) {
      setTimeout(() => {
        state.form.indicator_expression = "";
        table_form_ref.value.form_ref.resetFields();
        form_ref.value.resetFields();
      }, 100);
    }
    return obj;
  }
  return;
};
watch(
  () => state.form.indicator_expression,
  (n) => {
    form_ref.value?.validateField(["indicator_expression"]);
  }
);
// 监听是否是编辑，是则插入原数据
watch(
  () => props.row,
  async (n) => {
    if (!n) return;
    state.form.name = n.name;
    state.form.rule_type = n.rule_type;
    state.form.inspection_cycle = n.inspection_cycle || 1;
    state.form.state = n.state || 1;
    state.form.time = n.time || 10;
    state.form.unit = n.unit || "s";
    state.form.indicator_expression = n.indicator_expression;
  },
  { deep: true, immediate: true }
);
// 获取第一级指标范围列表
onMounted(() => {
  getRuleTypeOptions();
});
defineExpose({
  Submit,
});
</script>

<style lang="scss" scoped>
.add-form {
  :deep(.gap-title) {
    margin-bottom: 16px;
  }
  &-item {
    max-width: 1080px;
    width: 100%;
    .indicator-expression {
      height: 300px;
      width: 100%;
      :deep(.vue-ace-editor) {
        margin-top: 0;
      }
    }

    .duration {
      flex: 1;
      display: flex;
      align-items: center;
      :deep(.el-form-item) {
        flex: 1;
        .el-input {
          margin-right: 8px;
          flex: 1;
        }
        .el-input-group__prepend {
          width: 102px;
          border-radius: 4px;
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
        .el-input-group__append {
          width: 80px;
          border-radius: 4px;
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
      }
      //   :deep(.el-form-item__content) {
      //     display: flex;
      //     align-items: center;
      //     gap: 8px;
      //     > .el-input {
      //       flex: 1;
      //       width: 80px;
      //     }
      //   }
    }
    .duration-append {
      display: flex;
      align-items: center;
      color: #404a62;
    }
    :deep(.el-switch__inner) {
      .is-hide {
        display: none;
      }
    }
    :deep(.el-input-group__append, .el-input-group__prepend) {
      border-radius: 4px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
}
</style>
<style lang="scss">
.el-form-item {
  min-height: 36px;
  label {
    height: 36px;
    line-height: 36px;
  }
  .el-input__inner {
    min-height: 34px;
  }
}
</style>
