<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { storeToRefs } from 'pinia'
import { defineEmits, onMounted, reactive, ref, watch } from 'vue'
import { getBrands, getStoreurl } from '../api/index'
import ProductSetCommodity from '../component/ProductSetCommodity.vue'
import VideoCommodity from '../component/VideoCommodity.vue'
import { useShopInfo } from '/@/stores/shopInfo'
import emitter from '/@/utils/emitter'
import Product from '/@/assets/product.png'
import Shop from '/@/assets/shop.png'
import Video from '/@/assets/video.png'

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

const adFormatRadio = ref('productSet')
const arrivalsRadio = ref('flagshipStore')
const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  shop: string
  page: string
}
const ruleForm = reactive<RuleForm>({
  shop: '',
  page: '',
})
const rules = reactive<FormRules<RuleForm>>({
  shop: [{ required: true, message: '请选择', trigger: 'change' }],
  page: [{ required: true, message: '请选择', trigger: 'change' }],
})
const validateField = (fieldName) => {
  ruleFormRef.value.validateField(fieldName, () => {})
}

const flagshipStoreRuleFormRef2 = ref<FormInstance>()
interface flagshipStoreRuleForm2 {
  focusShop: string
}
const flagshipStoreRuleForm2 = reactive<flagshipStoreRuleForm2>({
  focusShop: '',
})
const flagshipStoreRules2 = reactive<FormRules<flagshipStoreRuleForm2>>({
  focusShop: [{ required: true, message: '请选择', trigger: 'change' }],
})
const validateField2 = (fieldName) => {
  flagshipStoreRuleFormRef2.value.validateField(fieldName, () => {})
}

const shopOptions = ref([])
const pageOptions = ref([])
const focusShopOptions = ref([])

async function getShopOptions() {
  try {
    const response = await getBrands({ profile_id: profile.value.profile_id })
    const shopOption = response.data.map((item) => {
      return {
        value: item.brandRegistryName,
        label: 'ZOSI',
      }
    })
    focusShopOptions.value = response.data
    shopOptions.value = shopOption
  } catch (error) {
    console.log('error:', error)
  }
}

watch(
  () => ruleForm.shop,
  () => {
    setTimeout(() => {
      emitter.emit('video-shop', focusShopOptions.value[0])
    }, 2000)
  },
  { deep: true }
)

watch(
  () => flagshipStoreRuleForm2.focusShop,
  () => {
    setTimeout(() => {
      emitter.emit('spotlight-shop', focusShopOptions.value[0])
    }, 2000)
  }
)

async function getPageOptions() {
  try {
    const response = await getStoreurl({ profile_id: profile.value.profile_id })
    pageOptions.value = response.data.storePageInfo
  } catch (error) {
    console.log('error:', error)
  }
}
let selectedPage: any = ''

watch(
  () => ruleForm.page,
  (newPageValue) => {
    selectedPage = pageOptions.value.find((page) => page.storePageUrl === newPageValue)
    if (selectedPage) {
      setTimeout(() => {
        emitter.emit('page', selectedPage.storePageUrl)
      }, 2000)
    } else {
      console.log('No page selected or matching page not found')
    }
  }
)

const emit = defineEmits([
  'update:adFormatRadio',
  'update:arrivalsRadio',
  'update:flagshipStoreShop',
  'update:pageOptions',
  'update:addedTableData',
  'update:focusShopSelect',
])

function handleUpdateAddedData(data) {
  emit('update:addedTableData', data)
}

// 监听 adFormatRadio 的变化并触发事件
watch(
  adFormatRadio,
  (newValue) => {
    emit('update:adFormatRadio', newValue)
  },
  { immediate: true }
)

watch(
  arrivalsRadio,
  (newValue) => {
    emit('update:arrivalsRadio', newValue)
  },
  { immediate: true }
)

watch(
  () => ruleForm.shop,
  (newValue) => {
    emit('update:flagshipStoreShop', newValue)
    if (newValue === 'ZOSI') {
      getPageOptions()
    }
    if (!ruleForm.shop) {
      ruleForm.page = ''
      pageOptions.value = []
    }
  }
)

watch(
  () => ruleForm.page,
  (newValue) => {
    emit('update:pageOptions', newValue)
  }
)

watch(
  () => flagshipStoreRuleForm2.focusShop,
  (newValue) => {
    emit('update:focusShopSelect', newValue)
  },
  { deep: true }
)

function shopChanged() {
  setTimeout(() => {
    emitter.emit('send-brandEntityId', { brandEntityId: focusShopOptions.value })
  }, 2000)
}

watch([adFormatRadio, arrivalsRadio], () => {
  ruleForm.shop = ''
  ruleForm.page = ''

  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate(['shop', 'page'])
  }
})

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

<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 20px 80px;">
      <div class="custom-card-title-content">
        <span class="custom-fake-icon">|</span>
        <span class="custom-card-title">广告格式</span>
      </div>
      <div class="ad-format-radios">
        <el-radio-group v-model="adFormatRadio" class="ad-format-radio-group">
          <el-radio class="ad-format-radio" label="productSet" border>
            <div class="ad-format-radio-content">
              <div class="ad-format-radio-title">商品集</div>
              <img :src="Product" class="ad-format-radio-img" />
              <!-- <div style="background-color: #1e2128; width: 300px; height: 200px; margin: 0 auto"></div> -->
              <div class="ad-format-radio-desc">使用图片将流量引导至商品详情页面, 以推广多件商品</div>
            </div>
          </el-radio>
          <el-radio class="ad-format-radio" label="focus" border>
            <div class="ad-format-radio-content">
              <div class="ad-format-radio-title">品牌旗舰店焦点</div>
              <img :src="Shop" class="ad-format-radio-img" />
              <!-- <div style="background-color: #4c649d; width: 200px; height: 200px; margin: 0 auto"></div> -->
              <div class="ad-format-radio-desc">将流量引流到品牌旗舰店, 包括子页</div>
            </div>
          </el-radio>
          <el-radio class="ad-format-radio" label="video" border>
            <div class="ad-format-radio-content">
              <div class="ad-format-radio-title">视频</div>
              <img :src="Video" class="ad-format-radio-img" />
              <!-- <div style="background-color: #43abc3; width: 200px; height: 200px; margin: 0 auto"></div> -->
              <div class="ad-format-radio-desc">使用视频宣传您的品牌或产品, 将流量吸引至您的品牌旗舰店或商品详情页</div>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
      <div class="customize-font" v-if="adFormatRadio === 'productSet'">需要帮助创建图片或品牌旗舰店？</div>
      <div class="customize-font" v-if="adFormatRadio === 'focus'">在创建或编辑品牌旗舰店时需要帮助？</div>
      <div class="customize-font" v-if="adFormatRadio === 'video'">在创建或编辑视频时需要帮助？</div>

      <div class="custom-hint">
        <div class="custom-hint-title">着陆页</div>
        <el-tooltip content="顾客在与您的广告互动后将被引导至着陆页" placement="top">
          <el-icon color="#616266"><InfoFilled /></el-icon>
        </el-tooltip>
      </div>

      <div class="land-Page" v-if="adFormatRadio === 'productSet' || adFormatRadio === 'video'">
        <el-radio-group v-model="arrivalsRadio" class="ad-format-radio-group">
          <el-radio label="flagshipStore" border class="flagshipStore-radio">
            <div>亚马逊品牌旗舰店(包括子页面)</div>
            <div>
              <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-position="top"
                label-width="120px"
                class="demo-ruleForm"
                size="default"
                status-icon>
                <div style="display: flex; margin-top: 10px">
                  <el-form-item label="选择一个店铺" prop="shop" style="width: 48%; margin-right: 10px">
                    <el-select
                      v-model="ruleForm.shop"
                      clearable
                      style="width: 100%"
                      @change="shopChanged"
                      @blur="validateField('shop')"
                      :disabled="arrivalsRadio == 'newArrivals' || arrivalsRadio == 'productDetailsPage'">
                      <el-option v-for="item in shopOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="选择一个页面" prop="page" style="width: 48%">
                    <el-select
                      v-model="ruleForm.page"
                      clearable
                      style="width: 100%"
                      @blur="validateField('page')"
                      :disabled="arrivalsRadio == 'newArrivals' || arrivalsRadio == 'productDetailsPage'">
                      <el-option v-for="item in pageOptions" :key="item.storePageId" :label="item.storePageName" :value="item.storePageUrl" />
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </el-radio>
          <el-radio class="land-page-radio" label="newArrivals" border v-if="adFormatRadio === 'productSet'">
            <div>新着陆页</div>
            <div>选择要推广的商品, 我们将为您创建一个落地页</div>
          </el-radio>
          <el-radio class="land-page-radio" label="productDetailsPage" border v-if="adFormatRadio === 'video'">
            <div>商品详情页</div>
          </el-radio>
        </el-radio-group>
      </div>

      <div v-if="adFormatRadio === 'focus'">
        <p class="custom-flagshipStore-hint">亚马逊上的品牌旗舰店(必须有4个或更多页面, 每个页面有1个或更多独特的商品)</p>
        <el-form
          ref="flagshipStoreRuleFormRef2"
          :model="flagshipStoreRuleForm2"
          :rules="flagshipStoreRules2"
          label-position="top"
          label-width="120px"
          class="demo-ruleForm"
          size="default"
          status-icon>
          <el-form-item label="选择一个店铺" prop="focusShop">
            <el-select
              v-model="flagshipStoreRuleForm2.focusShop"
              clearable
              @blur="validateField2('focusShop')"
              style="padding-top: 10px; margin-top: -15px; width: 500px">
              <el-option v-for="item in focusShopOptions" :key="item.brandId" :label="item.brandRegistryName" :value="item.brandEntityId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div
        class="custom-product-title"
        v-if="(adFormatRadio === 'productSet' && arrivalsRadio === 'newArrivals') || (adFormatRadio === 'video' && arrivalsRadio === 'productDetailsPage')">
        <span class="custom-fake-icon">|</span>
        <span class="custom-card-title">商品</span>
      </div>
      <ProductSetCommodity v-if="adFormatRadio === 'productSet' && arrivalsRadio === 'newArrivals'"></ProductSetCommodity>
      <VideoCommodity @update-added-data="handleUpdateAddedData" v-if="adFormatRadio === 'video' && arrivalsRadio === 'productDetailsPage'"></VideoCommodity>
    </el-card>
  </div>
</template>

<style scoped>
.custom-card-title-content {
  font-weight: 700;
  padding-bottom: 18px;
}
.custom-fake-icon {
  color: #306cd7;
  font-size: 26px;
}
.custom-card-title {
  font-size: 18px;
  padding-left: 5px;
}
.customize-font {
  color: #1e2128;
  font-weight: 600;
  margin-top: 10px;
}
.ad-format-radio {
  height: auto;
  width: 100%;
  flex: 1;
  flex-direction: column-reverse;
  align-items: center;
}
.land-page-radio {
  height: 132px;
  flex: 1;
  align-items: flex-start;
  padding: 15px 10px 0 10px;
}
.customize-container {
  margin-top: 10px;
}
::v-deep(.ad-format-radios .el-radio-group .el-radio__inner) {
  /* 广告格式单选按钮 */
  margin-bottom: 3px;
}
::v-deep(.land-Page .el-radio-group .el-radio__inner) {
  /* 着陆页单选按钮 */
  margin-top: 3px;
}
::v-deep(.land-Page .el-radio__label) {
  width: 100%;
}
::v-deep(.ad-format-radios label.el-radio.is-bordered.is-checked.el-radio--default) {
  background: #f5f7fe;
}
::v-deep(.land-Page label.el-radio.is-bordered.is-checked.el-radio--default) {
  background: #f5f7fe;
}
.img-style {
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

.ad-format-radio-group {
  display: flex;
  justify-content: space-between;
}
.ad-format-radio-content {
  padding: 10px 0;
}
.ad-format-radio-title {
  padding-bottom: 5px;
  text-align: center;
  font-size: 16px;
  font-weight: 700;
  color: #333;
}
.ad-format-radio-img {
  width: 330px;
  height: 260px;
  margin: 0 auto;
  object-fit: cover;
}
.ad-format-radio-desc {
  padding-top: 5px;
  color: #333;
  font-weight: 400;
  text-align: center;
}
.custom-hint {
  display: flex;
  align-items: center;
  margin: 20px 0 5px 0;
}
.custom-hint-title {
  color: #616266;
  font-weight: 450;
}
.flagshipStore-radio {
  height: auto;
  width: 100%;
  flex: 2;
  align-items: flex-start;
  padding: 15px 10px 0 10px;
}
.custom-flagshipStore-hint {
  padding: 10px 0 15px 0;
}
.custom-product-title {
  font-weight: 700;
  padding: 20px 0 10px 0;
}
</style>
