<template>
  <node :title="config.name" :mode="mode" :show-error="showError" :content="content" :error-info="errorInfo"
        @selected="emit('selected')" @delNode="emit('delNode')" @insertNode="type => emit('insertNode', type)"
        placeholder="请设置触发器" :header-bgc="headerBgc" :header-icon="SetUp"/>
</template>
<!--触发器节点-->
<script setup>
import Node from './Node.vue'
const emit = defineEmits()
import {defineProps, defineEmits, defineExpose} from "vue";
import {SetUp} from '@element-plus/icons-vue'
const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {}
    }
  },
  mode: {
    type: String,
    default: 'design'
  }
})
const showError = ref(false)
const errorInfo = ref('')
const viewer = computed(() => {
  return false;
})
const preview = computed(() => {
  return false;
})

const headerBgc = computed(() => {
  if (props.mode === 'design' || props.mode === 'view') {
    return '#BE2EF0'
  } else {
    return props.config.props.headerBgc
  }
})
const content = computed(() => {
  return '请设置触发器'
})
//校验数据配置的合法性
const validate = (err) => {
  showError.value = false
  if (props.config.props.type === 'WEBHOOK') {
    if (isNotEmpty(props.config.props.http.url)) {
      showError.value = false
    } else {
      showError.value = true
      errorInfo.value = '请设置WEBHOOK的URL地址'
    }
    if (restfulCheck(props.config.props.http.url)) {
      showError.value = false
    } else {
      showError.value = true
      errorInfo.value = 'WEBHOOK的URL地址不符合RESTful标准'
    }
  } else if (props.config.props.type === 'EMAIL') {
    if (!isNotEmpty(props.config.props.email.subject)
        || props.config.props.email.to.length === 0
        || !isNotEmpty(props.config.props.email.content)) {
      showError.value = true
      errorInfo.value = '请设置邮件发送配置'
    } else {
      showError.value = false
    }
  }
  if (showError) {
    err.push(`${props.config.name} 触发动作未设置完善`)
  }
  return !showError
}
//url规范性检查
const isNotEmpty = (obj) => {
  return (obj !== undefined && obj !== null && obj !== '' && obj !== 'null')
}
const restfulCheck = (url) => {
  const httpProtocolPattern = /^http:/;
  const httpsProtocolPattern = /^https:/;
  const restfulUrlPattern = /\/\w+\/\w+(\/\{[^}]+\})*/;
  if (httpProtocolPattern.test(url) || httpsProtocolPattern.test(url)) {
    return restfulUrlPattern.test(url);
  } else {
    return false;
  }
}
defineExpose({
  validate
})
</script>

<style scoped>

</style>
