<script lang="ts" setup>
/**
 * @Name: timer-budget.vue
 * @Description: 自动化-分时预算
 * @Author: Cheney
 */

import { ref } from 'vue';
import SelectTmpl from './select-tmpl.vue';
import TimerBudgetTable from '/@/components/TimerBudgetTable/index.vue';
import XEUtils from 'xe-utils';
import { userFormData } from './common';
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']);
const formRef = ref();
const { formData, submitFormData } = userFormData(props);

const submitDialogVisible = ref(false);


function checkConditions(rule: any, value: any, callback: any) {
  for (const bidList of formData.value.rule.conditions) {
    for (const info of bidList) {
      if (info.value && XEUtils.toNumber(info.value) > 0) {
        return callback();
      }
    }
  }
  callback(new Error('请先设置预算！'));
}

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

function handleSubmit() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    } else {
      if (formData.value.useTmpl) {
        await submit();
      } else {
        submitDialogVisible.value = true;
      }
    }
  });
}

function cancel() {
  emits('refresh');
}
</script>

<template>
  <div class="mx-5">
    <div class="asj-h2">分时预算</div>
    <SelectTmpl :data="formData" />
    <el-card class="mt-3">
      <el-form :model="formData" label-position="top" style="margin-top: 20px" ref="formRef">
        <el-form-item prop="rule.conditions" :rules="[{ validator: checkConditions, trigger: 'blur'}]">
          <template #label>
            <span class="custom-title-icon"></span>
            <span class="asj-h3">设置预算</span>
          </template>
          <TimerBudgetTable
              :data="formData.rule.conditions"
              @click="formRef.clearValidate('rule.conditions')"
              :disabled="formData.useTmpl" />
        </el-form-item>
      </el-form>
    </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>
.custom-title-icon {
  padding-right: 10px;
}

.custom-title-icon:before {
  content: '';
  width: 4px;
  height: 15px;
  background: #3569d6;
  position: absolute;
  transform: translateY(25%);
}
</style>
