<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"/>

      <el-form-item prop="rule.action.matchType" required :rules="{ required: true, message: '请至少选择一种匹配方式', trigger: 'change' }">
        <template #label>
          <span class="asj-h3">匹配方式</span>
        </template>
        <el-checkbox-group v-model="formData.rule.action.matchType">
          <el-checkbox label="EXECT">精准</el-checkbox>
          <el-checkbox label="PHRASE">词组</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </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 conditionBuilder from '/@/components/conditionBuilder/index.vue'
import XEUtils from 'xe-utils'

interface Props {
  mode: string
  data: AutoTemplate
  submitFormData: Function
  candidateFields: any[]
}
const props = withDefaults(defineProps<Props>(), {
  candidateFields: () => {
    return [
      { label: '曝光量', value: 'impressions' },
      { label: '点击量', value: 'clicks' },
      { label: '转化率', value: 'cr', suffix: '%' },
      { label: '单次点击费用', value: 'cpc', prefix: '$' },
      { label: '关键词', value: 'keyword', type: 'array', options: [{ label: '精确匹配', value: 'exect' }] },
      { label: '否定词', value: 'neg_keyword', type: 'array' },
    ]
  },
})
const emits = defineEmits(['refresh'])
const formRef = ref()
const searchTermAddRef = ref()
const condiBuilderRef = ref()
const formData = ref(props.data)
if (!formData.value.rule.action.matchType) {
  formData.value.rule.action.matchType = []
}

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

<style scoped></style>
