<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 0 80px;">
      <div class="custom-card-title">
        <span class="custom-card-icon">|</span>
        <span class="custom-card-Text">广告组</span>
      </div>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top" label-width="120px" size="default" status-icon>
        <el-card shadow="never" body-style="padding-bottom: 0px" v-loading="adGroupLoading">
          <el-form-item label="广告组名称" prop="groupName">
            <el-input v-model="ruleForm.groupName" style="width: 310px"></el-input>
          </el-form-item>
          <el-form-item label="竞价优化" prop="groupName">
            <div>
              <el-radio-group v-model="bidOptimization" class="custom-radio-group">
                <el-radio label="reach" size="large" border class="custom-radio-group-item" style="margin: 0">
                  <div>
                    <div>针对页面访问量</div>
                    <div style="color: #8c8c8c; margin-top: -5px">
                      我们将优化您的竞价以获得更高的点击率。通过向更有可能点击广告的顾客展示您的广告来提高商品购买意向
                    </div>
                  </div>
                </el-radio>
                <el-radio label="clicks" size="large" border class="custom-radio-group-item" style="margin: 10px 0">
                  针对转化率
                  <div style="color: #8c8c8c; margin-top: -5px">
                    我们将优化您的竞价以获得更高的转化率。通过向更有可能购买商品的顾客展示您的广告来提高销量
                  </div>
                </el-radio>
                <el-radio label="conversions" size="large" border class="custom-radio-group-item">
                  针对可见展示量进行优化
                  <div style="color: #8c8c8c; margin-top: -5px">
                    我们将优化您的竞价以获得更高的可见展示次数。通过在亚马逊上向尽可能多的顾客展示您的广告来提高商品知名度
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item style="margin: 20px 0 -10px 48%">
            <el-button type="primary" plain :disabled="!respCampaignId" @click="submitForm(ruleFormRef)">保存</el-button>
          </el-form-item>
        </el-card>
        <PromoteProduct></PromoteProduct>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { Ref, inject, reactive, ref, watch } from 'vue'
import { postAdGroup } from '../api/index'
import PromoteProduct from './PromoteProduct.vue'
import { useShopInfo } from '/@/stores/shopInfo'
import emitter from '/@/utils/emitter'

const shopInfo = useShopInfo()
const { profile } = storeToRefs(shopInfo)
const respCampaignId = inject<Ref>('respCampaignId')

const ruleFormRef = ref<FormInstance>()
interface ruleForm {
  groupName: string
  adMix: string
  startDate: string
  endDate: string
  budget: string
}
const ruleForm = reactive<ruleForm>({
  groupName: 'AiTestX2024',
  adMix: '',
  startDate: '',
  endDate: '',
  budget: '1',
})
const rules = reactive<FormRules<ruleForm>>({
  groupName: [{ 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 submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      crateAdGroup()
    } else {
      console.error('error submit!', fields)
    }
  })
}

// 竞价优化按钮组
const bidOptimization = ref('clicks')

// 创建广告组
const adGroupLoading = ref(false)
const respAdGroupId = ref('')

async function crateAdGroup() {
  adGroupLoading.value = true
  const body = {
      profile_id: profile.value.profile_id,
      campaignId: respCampaignId.value,
      defaultBid: 0.1,
      bidOptimization: bidOptimization.value,
      state: 'paused',
      creativeType: 'IMAGE',
    }
  try {
    const response = await postAdGroup(body)
    if (response.data.adGroupId) {
      respAdGroupId.value = response.data.adGroupId
      ElMessage({ message: '广告组创建成功', type: 'success' })
    } else {
      ElMessage.error('广告组创建失败!')
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    adGroupLoading.value = false
  }
}

const emit = defineEmits(['send-groupId'])

watch(
  () => respAdGroupId.value,
  () => {
    emit('send-groupId', { adGroupId: respAdGroupId.value })
    setTimeout(() => {
      emitter.emit('respAdGroupId', respAdGroupId.value)
    }, 2000)
  }
)
</script>

<style scoped>
.customize-container {
  margin-top: 10px;
}
.custom-card-title {
  font-weight: 700;
  padding-bottom: 18px;
}
.custom-card-Text {
  font-size: 18px;
  padding-left: 5px;
}
.custom-card-icon {
  color: #306cd7;
  font-size: 26px;
}
.custom-radio-group {
  flex-direction: column;
  align-items: normal;
}
.custom-radio-group-item {
  height: auto;
  flex-direction: row;
  align-items: baseline;
}
</style>
