<template>
  <div>
    <div class="asj-h2">添加搜索词</div>
    <el-form :model="formData" label-position="top" style="margin-top: 20px" ref="formRef" :disabled="false">
      <el-form-item prop="name" :rules="{ required: true, message: '必填项', trigger: 'blur' }">
        <template #label>
          <span class="asj-h3">模板名称</span>
        </template>
        <el-input v-model="formData.name" style="width: 30%"></el-input>
      </el-form-item>

      <SearchTermAdd :rule="formData.rule" ref="searchTermAddRef" />
      <SearchTermBid :action="formData.rule.action" ref="searchTermBidRef" />
    </el-form>
    <conditionBuilder :data="formData.rule.conditions" ref="condiBuilderRef" />
    <FreqSetting :rule="formData.rule" />
    <div class="auto-page-foot">
      <el-button style="width: 200px" @click="cancel">取消</el-button>
      <el-button style="width: 200px" type="primary" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import SearchTermAdd from '../search-term-add.vue'
import FreqSetting from '../freq-setting.vue'
import SearchTermBid from '../search-term-bid.vue'
import conditionBuilder from '/@/components/conditionBuilder/index.vue'
import XEUtils from 'xe-utils'

interface Props {
  mode: string
  data: AutoTemplate
  submitFormData: Function
}
const props = defineProps<Props>()
const emits = defineEmits(['refresh'])
const formRef = ref()
const condiBuilderRef = ref()
const searchTermBidRef = ref()
const searchTermAddRef = ref()
const formData = ref(props.data)

const submitForm = async () => {
  const valid3 = await searchTermAddRef.value.validate()
  const valid2 = !XEUtils.includes(await condiBuilderRef.value.validate(), false)
  formRef.value.validate(async (valid: boolean) => {
    if (valid && valid2 && valid3 && searchTermBidRef.value.valid) {
      await props.submitFormData()
      emits('refresh')
    } else {
      console.log('验证失败：', [valid, valid2, valid3, searchTermBidRef.value.valid])
    }
  })
}
const cancel = () => {
  emits('refresh')
}
</script>

<style scoped></style>
