<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, getBrands, postCampaignsData } from '../api/index'
import { useShopInfo } from '/@/stores/shopInfo'
import emitter from '/@/utils/emitter'

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
  commodityPage: string
  otherPlace: string
  firstPage: string
}
const campaignRuleForm = reactive<campaignRuleForm>({
  campaignName: '',
  adMix: '',
  startDate: '',
  endDate: '',
  budget: '',
  frequency: 'DAILY',
  brand: '',
  isBid: false,
  commodityPage: '',
  otherPlace: '',
  firstPage: '',
})
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' },
  ],
  commodityPage: [
    { required: true, message: '必填', trigger: 'blur' },
    { pattern: /^-?(99|[1-8]?[0-9]?[0-9])$/, message: '请输入-99到900之间的数字', trigger: 'blur' },
  ],
  otherPlace: [
    { required: true, message: '必填', trigger: 'blur' },
    { pattern: /^-?(99|[1-8]?[0-9]?[0-9])$/, message: '请输入-99到900之间的数字', trigger: 'blur' },
  ],
  firstPage: [
    { required: true, message: '必填', trigger: 'blur' },
    { pattern: /^-?(99|[1-8]?[0-9]?[0-9])$/, message: '请输入-99到900之间的数字', trigger: 'blur' },
  ],
})
const frequencyOptions = [
  {
    value: 'DAILY',
    label: '每日',
  },
  {
    value: 'lifeCycle',
    label: '生命周期',
    disabled: true,
  },
]
const brandOptions = ref([])

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

async function getBrandOption() {
  const response = await getBrands({ profile_id: profile.value.profile_id })
  brandOptions.value = response.data
}

const adMixOptions = ref([])
async function getAdMix() {
  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 prevCampaignId = ref('')
const prevCampaignName = ref('')
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,
    brandEntityId: campaignRuleForm.brand,
    bidOptimization: campaignRuleForm.isBid,
    bidOptimizationStrategy: '',
    startDate: campaignRuleForm.startDate,
    endDate: campaignRuleForm.endDate,
    smartDefault: 'MANUAL',
    costType: 'CPC',
    goal: 'PAGE_VISIT',
    state: 'PAUSED',
    ...(campaignRuleForm.firstPage && { h_percentage: campaignRuleForm.firstPage }),
    ...(campaignRuleForm.commodityPage && { d_percentage: campaignRuleForm.commodityPage }),
    ...(campaignRuleForm.otherPlace && { o_percentage: campaignRuleForm.otherPlace }),
    ...(campaignRuleForm.adMix && { portfolioId: campaignRuleForm.adMix }),
  }

  try {
    const response = await postCampaignsData(campaignData)

    respCampaignId.value = response.data.campaignId
    respCampaignName.value = response.data.campaignName

    if (response.data.campaignId) {
      // 如果创建成功，更新 respCampaignId 和 respCampaignName，同时保留上一次成功的值
      prevCampaignId.value = respCampaignId.value
      prevCampaignName.value = respCampaignName.value
      respCampaignId.value = response.data.campaignId
      respCampaignName.value = response.data.campaignName
      ElMessage({ message: '广告活动创建成功', type: 'success' })
    } else {
      // 如果创建失败，检查是否有上一次成功的值，如果有就保留
      if (prevCampaignId.value) {
        respCampaignId.value = prevCampaignId.value
        respCampaignName.value = prevCampaignName.value
      }
      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,
    })
  }
})

watch(
  () => campaignRuleForm.brand,
  () => {
    emitter.emit('brandEntityId', brandOptions.value)
  }
)

onMounted(() => {
  getAdMix()
  getBrandOption()
})
</script>

<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" 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: 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.brandId" :label="item.brandRegistryName" :value="item.brandEntityId" />
          </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>
        <div style="width: 55%" v-if="campaignRuleForm.isBid == false">
          <el-card shadow="never" body-style="padding: 10px 10px 5px 10px;">
            <div style="margin-bottom: 10px; font-weight: 500">
              <span style="color:#f56c6c;margin-right: 4px;">*</span>
              展示位置出价调整
            </div>
            <div style="display: flex; align-items: center">
              <div class="left">
                <div class="title">商品页面</div>
                <div class="tip">产品详情页面为顾客提供在亚马逊所售卖商品的详情信息</div>
              </div>
              <el-form-item prop="commodityPage" style="margin-bottom: 0px !important; width: 37%;">
                <el-input v-model="campaignRuleForm.commodityPage" maxlength="3" placeholder="-99 ~ 900">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="display: flex; align-items: center; margin-top: 10px">
              <div class="left">
                <div class="title">搜索结果顶部(首页)</div>
                <div class="tip">亚马逊首页 http://www.amazon.com</div>
              </div>
              <el-form-item prop="firstPage" style="margin-bottom: 0px !important; width: 37%">
                <el-input v-model="campaignRuleForm.firstPage" maxlength="3" placeholder="-99 ~ 900" style="width: 100%">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="display: flex; align-items: center; margin-top: 10px">
              <div class="left">
                <div class="title">搜索结果的其余位置</div>
                <div class="tip">其他位置集合, 例如搜索页</div>
              </div>
              <el-form-item prop="otherPlace" style="margin-bottom: 0px !important; width: 37%">
                <el-input v-model="campaignRuleForm.otherPlace" maxlength="3" placeholder="-99 ~ 900">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="color: #8d9095; padding-left: 60%; margin-top: 10px">示例: $5.00 竞价降低 40% 将变为 $3.00</div>
          </el-card>
        </div>
        <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>

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