<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="formSize"
        status-icon>
        <div class="flex-between">
          <el-form-item label="广告活动名称" prop="campaignName" style="width: 48%">
            <el-input v-model="campaignRuleForm.campaignName" />
          </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: 65%">
              <el-input v-model="campaignRuleForm.budget" minlength="1" maxlength="7" placeholder="请输入" style="width: 100%">
                <template #prepend>$</template>
              </el-input>
            </el-form-item>
            <el-form-item label="频率" prop="frequency" style="width: 34%">
              <el-select v-model="campaignRuleForm.frequency" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in frequencyOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="品牌" prop="brand" required style="width: 48%">
          <el-select v-model="campaignRuleForm.brand" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <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-item label="自动竞价" style="margin-bottom: -13px">
          <el-form-item>
            <el-switch v-model="campaignRuleForm.isBid" />
            <span style="margin-left: 10px; color: #88909b">允许亚马逊自动优化搜索结果首页以外的广告位竞价</span>
          </el-form-item>
        </el-form-item>
        <el-form-item style="margin-left: 48%; margin-bottom: -10px">
          <el-button type="primary" plain @click="submitCampaignForm(campaignRuleFormRef)">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

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

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

const formSize = ref('default')
const campaignRuleFormRef = ref<FormInstance>()
interface campaignRuleForm {
  campaignName: string
  adMix: string
  startDate: string
  endDate: string
  budget: string
  frequency: string
  brand: string
  isBid: boolean
}
const campaignRuleForm = reactive<campaignRuleForm>({
  campaignName: 'AiTestW01',
  adMix: '',
  startDate: '',
  endDate: '',
  budget: '',
  frequency: 'daily',
  brand: 'zosi',
  isBid: false,
})
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 frequencyOptions = [
  {
    value: 'daily',
    label: '每日',
  },
  {
    value: 'lifeCycle',
    label: '生命周期',
    disabled: true,
  },
]
const brandOptions = [
  {
    value: 'zosi',
    label: 'ZOSI',
  },
]
const submitCampaignForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      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: campaignRuleForm.frequency,
    name: campaignRuleForm.campaignName,
    bidOptimization: campaignRuleForm.isBid,
    bidOptimizationStrategy: '',
    startDate: campaignRuleForm.startDate,
    endDate: campaignRuleForm.endDate,
    goal: 'PAGE_VISIT',
    state: 'PAUSED',
  }
  const filteredRequestData = Object.fromEntries(Object.entries(campaignData).filter(([_, v]) => v != null))
  try {
    const response = await postCampaignsData(filteredRequestData)
    respCampaignId.value = response.data.campaignId
    respCampaignName.value = response.data.campaignName
    console.log('🚀 ~ createCampaigns ~ response-->>', response)
    if (response.data.campaignId) {
      ElMessage({
        message: '广告活动创建成功',
        type: 'success',
      })
    } else {
      ElMessage.error('广告活动创建失败!')
    }
  } catch (error) {
    console.error('请求失败：', error)
  } finally {
    campaignLoading.value = false
  }
}

const emit = defineEmits(['update-campaign'])

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

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

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
}
</style>
