<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 0 80px;" v-loading="campaignLoading">
      <div style="font-weight: 700; padding-bottom: 18px">
        <span style="color: #306cd7; font-size: 26px">|</span>
        <span style="font-size: 18px; padding-left: 5px">广告活动</span>
      </div>
      <el-form
        ref="campaignRuleFormRef"
        :model="campaignRuleForm"
        :rules="campaignRules"
        label-position="top"
        label-width="120px"
        class="demo-ruleForm"
        size="default"
        status-icon>
        <div class="flex-between">
          <el-form-item label="广告活动名称" prop="campaignName" style="width: 48%">
            <el-input v-model="campaignRuleForm.campaignName" placeholder="请输入广告活动名称" />
          </el-form-item>
          <el-form-item label="广告组合" prop="adMix" style="width: 48%">
            <el-select v-model="campaignRuleForm.adMix" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in adMixOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex-between">
          <div class="flex-between" style="width: 48%">
            <el-form-item label="开始时间" prop="startDate" style="width: 49%">
              <el-date-picker
                v-model="campaignRuleForm.startDate"
                type="date"
                label="Pick a date"
                placeholder="开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate" style="width: 49%">
              <el-date-picker
                v-model="campaignRuleForm.endDate"
                type="date"
                label="Pick a date"
                placeholder="开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </div>
          <div class="flex-between" style="width: 48%">
            <el-form-item label="预算" required prop="budget" style="width: 100%">
              <el-input v-model="campaignRuleForm.budget" minlength="1" maxlength="7" placeholder="请输入" style="width: 100%">
                <template #prepend>$</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="投放类型">
          <el-radio-group v-model="targetType" @change="changeTargetType">
            <el-radio label="T00030">受众</el-radio>
            <el-radio label="T00020">内容相关投放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin: 20px 0 -10px 48%">
          <el-button type="primary" plain @click="submitCampaignForm(campaignRuleFormRef)">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { defineEmits, onMounted, reactive, ref, watch } from 'vue'
import { getAdMixSelect, postCampaignsData } from '../api/index'
import { useShopInfo } from '/@/stores/shopInfo'

const shopInfo = useShopInfo()
const { profile } = storeToRefs(shopInfo)

// 投放类型
const targetType = ref('T00030')

const campaignRuleFormRef = ref<FormInstance>()
interface campaignRuleForm {
  campaignName: string
  adMix: string
  startDate: string
  endDate: string
  budget: string
}
const campaignRuleForm = reactive<campaignRuleForm>({
  campaignName: '',
  adMix: '',
  startDate: '',
  endDate: '',
  budget: '1',
})
const campaignRules = reactive<FormRules<campaignRuleForm>>({
  campaignName: [{ required: true, message: '请输入广告活动', trigger: 'blur' }],
  startDate: [{ type: 'date', required: true, message: '请选择时间', trigger: 'blur' }],
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { pattern: /^(?:[1-9]\d{0,5}|1000000)(?:\.\d{1,2})?$/, message: '预算必须是1到1000000之间的数字，小数点后最多两位', trigger: 'blur' },
  ],
})
const submitCampaignForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      createCampaigns()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 广告组合相关
const adMixOptions = ref([])
async function buildAdMix() {
  try {
    const response = await getAdMixSelect()
    adMixOptions.value = response.data.map((option) => {
      return {
        value: option.portfolioId,
        label: option.name,
      }
    })
  } catch (error) {
    console.error('请求失败：', error)
  }
}

// 创建广告活动相关功能
const campaignLoading = ref(false)
const respCampaignId = ref('')
const respCampaignName = ref('')
async function createCampaigns() {
  campaignLoading.value = true

  // 构建基础请求体
  const campaignData = {
    profile_id: profile.value.profile_id,
    budget: campaignRuleForm.budget,
    budgetType: 'daily',
    name: campaignRuleForm.campaignName,
    startDate: campaignRuleForm.startDate,
    endDate: campaignRuleForm.endDate,
    costType: 'cpc',
    state: 'paused',
    tactic: targetType.value,
  }

  try {
    const response = await postCampaignsData(campaignData)
    respCampaignId.value = response.data.campaignId
    respCampaignName.value = response.data.campaignName

    if (response.data.campaignId) {
      ElMessage({ message: '广告活动创建成功', type: 'success' })
    } else {
      ElMessage.error('广告活动创建失败!')
    }
  } catch (error) {
    console.error('请求失败：', error)
  } finally {
    campaignLoading.value = false
  }
}

// 提供数据给父组件
const emit = defineEmits(['send-campaign', 'send-targetType'])

watch([respCampaignId, respCampaignName], () => {
  if (respCampaignId.value && respCampaignName.value) {
    emit('send-campaign', {
      id: respCampaignId.value,
      name: respCampaignName.value,
    })
  }
})

function changeTargetType(value: string) {    // 发送新的 targetType 值给父组件
  targetType.value = value
  emit('send-targetType', { type: targetType.value })
}

onMounted(() => {
  buildAdMix()
})
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
}
.left {
  margin-right: 12px;
  width: 60%;
}
.title {
  font-size: 14px;
  line-height: 20px;
  color: #1d2129;
}
.tip {
  font-size: 14px;
  line-height: 20px;
  color: #4e5969;
}
</style>
