<template>
  <el-form ref="mcRef" :model="form" :rules="rules" label-width="120px" label-suffix=":">
    <el-form-item label="指标名称">
      {{form?.metricsName || '-'}}
    </el-form-item>
    <el-form-item label="指标类型">
      {{form?.metricsType || '-'}}
    </el-form-item>
    <el-form-item label="指标编码">
      {{form?.metricsCode || '-'}}
    </el-form-item>
    <el-form-item label="数据接口配置">
      <el-input type="textarea" placeholder="请输入数据接口配置" v-model="form.dataExp" :autosize="{ minRows: 4, maxRows: 6 }"/>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="onTest">测试</el-button>
      <span v-if="validateError===1" style="color:#1ab394;margin-left:10px;">
        数据获取正常,当前值:{{currentValue}}
      </span>
      <span v-if="validateError===2" style="color:#ee4433;margin-left:10px;">
        数据获取失败,请检查数据接口配置
      </span>
    </el-form-item>
  </el-form>
  <div class="row-btn">
    <el-button type="primary" @click="onSubmit" :disabled="!validate">提交</el-button>
    <el-button @click="emit('cancel')">取消</el-button>
  </div>
</template>
<script setup lang="ts">
import {getCurrentInstance, watchEffect} from "vue";
import {putMetrics} from "@/api/obj/metrics"
import {validateObj} from "@/api/obj/obj"
const {emit,proxy} = getCurrentInstance();
const mcRef = ref(null);
const validate = ref(false)
const currentValue = ref(0)
const validateError= ref(0)
const data = reactive({
  form:{},
  rules:{
    dataExp :[{required:true,message:"数据配置不能为空",trigger:"blur"}]
  }
})
const {form,rules} = toRefs(data)
const props = defineProps(['metrics'])
watchEffect(()=>{
  validate.value = false
  currentValue.value = 0
  validateError.value = 0
  form.value = {
    metricsName:props.metrics.metricsDef.metricsName,
    metricsType:props.metrics.metricsDef.metricsType,
    metricsCode:props.metrics.metricsDef.metricsCode,
    objMetricsId:props.metrics.objMetricsId,
    dataExp:props.metrics.dataExp
  }
})

const onTest=()=>{
  const {dataExp} = form.value
  validateError.value = 0
  validateObj({exp:dataExp}).then(res=>{
    proxy.$modal.msgSuccess(res.msg);
    currentValue.value = res.data
    validate.value = true
    validateError.value = 1
  }).catch(()=>{
    validateError.value = 2
  })
}

const onSubmit=()=>{
  const {objMetricsId,dataExp} = form.value
  putMetrics({objMetricsId,dataExp}).then(res=>{
    proxy.$modal.msgSuccess(res.msg);
    emit("success")
  })
}
</script>
<style scoped lang="scss">
.row-btn{
  border-top:1px solid #F1F1F1;
  margin-top:10px;
  padding-top:20px;
  display: flex;
  justify-content: center;
}
</style>
