<script lang="ts" setup>
/**
 * @Name: switch-campaign
 * @Description: 自动化-广告活动
 * @Author: Cheney
 */

import { ref, watch } from 'vue';
import SelectTmpl from './select-tmpl.vue';
import conditionBuilder from '/@/components/conditionBuilder/index.vue';
import { userFormData } from './common';
import FreqSetting from '../freq-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 condiBuilderRef = ref();
const { formData, submitFormData } = userFormData(props);
formData.value.rule.action.state = [];
formData.value.rule.action.setTime = '';
const submitDialogVisible = ref(false);
const showError = ref(false);

const condidateFields = [
  { label: '曝光量', value: 'impressions' },
  { label: '点击量', value: 'clicks' },
  { label: '转化率', value: 'cr', suffix: '%' },
  { label: '单次点击费用', value: 'cpc', prefix: '$' },
];
const defaultTime = new Date();

function disabledDate(date) {
  return date < new Date().setHours(0, 0, 0, 0);
}

// 限制小时
const disabledHour = () => {
  const arrs = [];
  for (let i = 0; i < 24; i++) {
    if (new Date().getHours() <= i) continue;
    arrs.push(i);
  }
  return arrs;
};

// 限制分
const disabledMinute = () => {
  const arrs = [];
  for (let i = 0; i < 60; i++) {
    if (new Date().getMinutes() <= i) continue;
    arrs.push(i);
  }
  return arrs;
};

function addConditions() {
  if (formData.value.rule.conditions.length === 0) {
    condiBuilderRef.value.addConditionGroup();
  }
}

async function validateConditionsForm() {
  const validList = await condiBuilderRef.value.validate();
  console.log('=>(switch-campaign.vue:77) validList', validList);
  return !validList.includes(false);
}

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

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

async function handleSubmit() {
  const valid2 = await validateConditionsForm();
  formRef.value.validate(async (valid: any) => {
    const actionState = formData.value.rule.action.state;
    if (!valid  || (actionState.includes('paused') && !valid2)) return;
    if (formData.value.rule.action.state.length === 0) return;

    const selectedTime = new Date(formData.value.rule.action.setTime).setSeconds(0, 0);;
    if (selectedTime < new Date().setSeconds(0, 0)) {
      ElMessage.error('保存失败，请重新选择时间');
      return;
    }

    try {
      if (formData.value.useTmpl) {
        await submitForm();
      } else {
        submitDialogVisible.value = true;
      }
    } catch (error) {
      console.error('提交失败:', error);
    }
  });
}

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">
      <FreqSetting :disabled="formData.useTmpl" :rule="formData.rule" />
      <el-divider />
      <el-form ref="formRef" :disabled="formData.useTmpl" :model="formData" label-position="top"
               style="margin-top: 20px">
        <div class="asj-h3">
          <span class="custom-title-icon"></span>
          操作
        </div>
        <el-checkbox-group v-model="formData.rule.action.state" :disabled="formData.useTmpl">
          <div>
            <el-checkbox label="enabled">开始</el-checkbox>
            <div v-show="formData.rule.action.state.includes('enabled')" style="display: block; margin: 10px 0">
              <el-form-item
                  :rules="[{ required: formData.rule.action.state.includes('enabled'), message: '必填项', trigger: 'blur' }]"
                  prop="rule.action.setTime">
                <el-date-picker
                    v-model="formData.rule.action.setTime"
                    :default-time="defaultTime"
                    :disabled-date="disabledDate"
                    :disabled-hours="disabledHour"
                    :disabled-minutes="disabledMinute"
                    format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm"
                />
              </el-form-item>
            </div>
          </div>
          <el-checkbox label="paused" @click="addConditions">暂停</el-checkbox>
        </el-checkbox-group>
        <el-form-item v-if="formData.rule.action.state.length === 0" style="color: red">
          <span style="font-size: 12px;">请至少选择一种操作</span>
        </el-form-item>
      </el-form>
      <div v-show="formData.rule.action.state.includes('paused')">
        <conditionBuilder
            ref="condiBuilderRef"
            :candidate-fields="condidateFields"
            :data="formData.rule.conditions"
            :disabled="formData.useTmpl" />
      </div>
    </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>
