<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';

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);

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() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      await submitFormData();
      emits('refresh');
    } else {
      console.log('验证失败');
    }
  });
}

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: 'xxx' }]">
          <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>
    <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>

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