<script lang="ts" setup>
/**
 * @Name: search-term
 * @Description: 自动化-添加搜索词
 * @Author: Cheney
 */
import { ref, computed } from 'vue';
import SearchTermAdd from '../search-term-add.vue';
import SearchTermBid from '../search-term-bid.vue';
import SelectTmpl from './select-tmpl.vue';
import FreqSetting from '../freq-setting.vue';
import conditionBuilder from '/@/components/conditionBuilder/index.vue';
import { userFormData } from './common';
import XEUtils from 'xe-utils';
import SaveRuleDialog from '/@/views/components/auto/auto-campaigns/save-rule-dialog.vue';

interface Props {
  data: {
    campaignId: string;
    campaignType: string;
    profileId: string;
    ruleType: number;
  };
  RuleStatusButton?: { [key: string]: any };
}
const props = defineProps<Props>();


const emits = defineEmits(['refresh']);
const formRef = ref();
const searchTermAddRef = ref();
const searchTermBidRef = ref();
const condiBuilderRef = ref();
const { formData, submitFormData } = userFormData(props);
const submitDialogVisible = ref(false);

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

function handleSubmit() {
  if (formData.value.useTmpl) {
    submitForm();
  } else {
    submitDialogVisible.value = true;
  }
}
</script>

<template>
  <div class="mx-5">
    <div class="asj-h2">添加搜索词</div>
    <SelectTmpl :data="formData" />
    <el-card class="mt-3">
      <FreqSetting :rule="formData.rule" :disabled="formData.useTmpl" />
      <el-divider />
      <el-form :model="formData" label-position="top" ref="formRef" :disabled="formData.useTmpl">
        <SearchTermAdd :rule="formData.rule" :disabled="formData.useTmpl" ref="searchTermAddRef" />
        <SearchTermBid :action="formData.rule.action" ref="searchTermBidRef" />
      </el-form>
    </el-card>
    <el-card class="mt-3">
      <conditionBuilder :data="formData.rule.conditions" ref="condiBuilderRef" :disabled="formData.useTmpl" />
    </el-card>
    <SaveRuleDialog
        v-model="submitDialogVisible"
        :formData="formData"
        :formRef="formRef"
        @submit="submitForm"
    />
    <div class="auto-page-foot">
      <el-button style="width: 200px" @click="cancel">取消</el-button>
      <el-button style="width: 200px" type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </div>
</template>

<style scoped></style>
