<template>
  <div>
    <div class="asj-h2">分时预算</div>
    <el-form :model="formData" label-position="top" style="margin-top: 20px" ref="formRef">
      <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>

      <el-form-item prop="rule.conditions" :rules="[{ validator: checkConditions, trigger: 'xxx' }]">
        <template #label>
          <span class="asj-h3">设置预算</span>
        </template>
        <TimerBudgetTable :data="formData.rule.conditions" @click="formRef.clearValidate('rule.conditions')" />
      </el-form-item>
    </el-form>

    <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, onMounted } from 'vue'
import TimerBudgetTable from '/@/components/TimerBudgetTable/index.vue'
import XEUtils from 'xe-utils'

interface Props {
  mode: string
  data: AutoTemplate
  submitFormData: Function
}
const props = defineProps<Props>()
const emits = defineEmits(['refresh'])
const formRef = ref()
const formData = ref(props.data)
if (props.mode === 'add') {
  for (let i = 0; i < 7; i++) {
    const tmp = []
    for (let j = 0; j < 24; j++) {
      tmp.push({ type: '', value: '' })
    }
    formData.value.rule.conditions.push(tmp)
  }
}

const 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('请先设置预算！'))
}
const submitForm = async () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      await props.submitFormData()
      emits('refresh')
    } else {
      console.log('验证失败')
    }
  })
}
const cancel = () => {
  emits('refresh')
}
</script>

<style scoped></style>
