<template>
  <el-form :model="form" label-width="120" label-suffix=":" :rules="rules" ref="fRef">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="指标名称">{{ rowsInfo.metricsDef.metricsName }}</el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="指标类型">
          <dict-tag :options="metrics_category" :value="rowsInfo.metricsDef.metricsType"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="指标编码">{{ rowsInfo.metricsDef.metricsCode }}</el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="自动发现" prop="findFlag" v-if="disabled">
          <el-switch v-model="form.findFlag"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="数据接口配置" prop="dataExp" v-if="disabled">
      <el-input type="textarea" v-model="form.dataExp" placeholder="请输入数据接口配置" :autosize="{minRows: 3}"
                style="width:342px;margin-right:10px;"/>
      <el-button type="primary" @click="handleConfigKey">公式组装</el-button>
    </el-form-item>
    <el-form-item label="自动发现规则" prop="findRule" v-if="disabled && form.findFlag">
      <el-input v-model="form.findRule" type="textarea" :autosize="{minRows: 3}" placeholder="请输入自动发现规则"/>
    </el-form-item>
    <el-form-item label="关键字" prop="findKey" v-if="disabled && form.findFlag">
      <el-input v-model="form.findKey" placeholder="请输入关键字"/>
    </el-form-item>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="告警-低">
          <el-input v-model="form.alarmLow" @change="checkInput"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="告警-中">
          <el-input v-model="form.alarmMid" @change="checkInput"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="告警-高">
          <el-input v-model="form.alarmHigh" @change="checkInput"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="健康事件">
          <el-input v-model="form.event" @change="checkInput"/>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div class="food-btn">
    <el-button type="primary" @click="handleSubmit">提交</el-button>
    <el-button @click="emit('close')">取消</el-button>
  </div>
</template>
<script setup lang="ts">
import {updateDetail} from "@/api/metrics/detail";
import {updateMc} from "@/api/biz/mc"

const {proxy, emit} = getCurrentInstance()
const {metrics_category, sys_yes_no} = proxy.useDict("metrics_category", "sys_yes_no")
const props = defineProps({
  rowsInfo: {
    type: Object,
    default: () => {
    }
  },
  mc: {
    type: Boolean,
    default: false
  }
})
const form = ref({
  dataExp: "",
  findFlag: "",
  findRule: "",
  findKey: "",
  alarmLow: "",
  alarmMid: "",
  alarmHigh: "",
  event: ""
})
const passValidate = ref(true)

const disabled = computed(() => props.rowsInfo.metricsDef.metricsType != "1")
const rules = {
  dataExp: {required: true, message: '请输入数据接口配置', trigger: 'change'},
  findRule: {required: true, message: '请选择自动发现规则', trigger: 'change'},
  findKey: {required: true, message: '请输入关键字', trigger: 'change'},
  findFlag: {required: true, message: '请选择自动发现', trigger: 'change'}
}

const handleConfigKey = () => {
  proxy.getConfigKey("pm.web.url").then(res => {
    if (res.code === 200) {
      window.open(res.msg, '_blank');
    }
  })
}

const checkInput = (range) => {
  passValidate.value = validateRange(range)
  if (!passValidate.value) {
    proxy.$message.error("请输入正确的区间格式！")
  }
}
const validateRange = (range) => {
  // 正则表达式匹配各种区间的格式
  const regex = /^(\[|\()\s*([0-9]+(\.[0-9]+)?|)\s*,\s*([0-9]+(\.[0-9]+)?|)\s*(\]|\))$/;
  const match = range.match(regex);

  if (!match) {
    return false; // 如果格式不正确，则返回false
  }

  // 提取括号类型和两个数值
  const openBracket = match[1];// 开始的括号
  const num1Str = match[2]; // 第一个数
  const num2Str = match[4]; // 第二个数
  const closeBracket = match[7]; // 结束的括号

  let num1 = num1Str ? parseFloat(num1Str) : -Infinity;
  let num2 = num2Str ? parseFloat(num2Str) : Infinity;

  // 检查区间的有效性
  if (openBracket === '[' && num1 > num2) return false; // [x,y] 要求 x <= y
  if (openBracket === '(' && num1 >= num2) return false; // (x,y) 要求 x < y
  if (closeBracket === ']' && num1 > num2) return false; // (x,y] 要求 x < y
  if (closeBracket === ')' && num1 >= num2) return false; // [x,y) 要求 x < y

  return true;
}

const editData = (row) => {

  const keys = Object.keys(form.value)
  keys.forEach(p => {
    form.value[p] = row[p]
  })

  form.value.findFlag = row.findFlag === "Y"

  setTimeout(() => {
    proxy.$refs.fRef.clearValidate()
  })
}

const handleSubmit = () => {
  proxy.$refs.fRef.validate(valid => {
    if (valid) {
      const data = {...form.value}
      data.findFlag = data.findFlag ? "Y" : "N"
      handleUpdate({...props.rowsInfo, ...data})
    }
  })
}

// 更新
const handleUpdate = (row) => {
  if (!passValidate.value) return proxy.$message.error("区间无效,请检查")
  const request = props.mc ? updateMc : updateDetail
  request({...row}).then(res => {
    proxy.$modal.msgSuccess("修改成功");
    emit("reload")
  })
}

defineExpose({editData})

</script>
<style scoped lang="scss">
.food-btn {
  text-align: center;
  margin-top: 10px;
  border-top: 1px solid #F9F9F9;
  padding-top: 10px;
}
</style>
