<script lang="ts" setup>
/**
 * @Name: target-rule
 * @Description: 自动化-定向规则
 * @Author: Cheney
 */

import { ref } from 'vue';
import TargetSelect from '../target-select.vue';
import SelectTmpl from './select-tmpl.vue';
import FreqSetting from '../freq-setting.vue';
import { userFormData } from './common';
import TargetRuleSetting from '../target-rule-setting.vue';
import SaveRuleDialog from '/@/views/components/auto/auto-campaigns/save-rule-dialog.vue';
import { ElMessage } from 'element-plus';


interface Props {
  data: {
    campaignId: string;
    campaignType: string;
    profileId: string;
    ruleType: number;
  };
  RuleStatusButton?: { [key: string]: any };
}

const props = defineProps<Props>();
const emits = defineEmits(['refresh', 'updateRuleStatusButton']);

const formRef = ref();
const ruleSettingRef = ref();
const { formData, submitFormData } = userFormData(props);
const submitDialogVisible = ref(false);

const submitForm = async () => {
  await submitFormData();
  ElMessage.success('保存成功');
  emits('refresh');
};

function cancel() {
  emits('refresh');
}

async function handleSubmit() {
  const valid2 = await ruleSettingRef.value.validateForm();
  formRef.value.validate(async (valid: boolean) => {
    if (!valid || !valid2) {
      return;
    } else {
      if (formData.value.useTmpl) {
        await submitForm();
      } else {
        submitDialogVisible.value = true;
      }
    }
  });
}

watch(() => formData.value, (newData) => {
  emits('updateRuleStatusButton', newData.RuleStatusButton);
});
</script>

<template>
  <div class="mx-5">
    <div class="asj-h2">定向规则</div>
    <SelectTmpl :data="formData" />
    <el-card class="mt-3">
      <el-form ref="formRef" :model="formData" class="custom-card" label-position="top">
        <el-form-item>
          <!-- 频率设置 -->
          <FreqSetting :disabled="formData.useTmpl" :rule="formData.rule" />
          <el-divider />
          <!-- 生效对象 -->
          <TargetSelect
              :campaignInfo="data"
              :data="formData.rule"
              :useTmpl="formData.useTmpl"
              mode="auto"></TargetSelect>
        </el-form-item>
      </el-form>
    </el-card>
    <!--规则设置-->
    <el-card class="mt-3">
      <TargetRuleSetting ref="ruleSettingRef" :disabled="formData.useTmpl" :rule="formData.rule" />
    </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 lang="scss" scoped>
:deep(.custom-card .el-form-item__content) {
  display: block;
}
</style>
