<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>
      <div class="main-container" v-loading="loading">
        <div class="left-container">
          <el-tabs v-model="topTabName" class="demo-tabs">
            <div class="tab-container-fixed-top">
              <span class="tab-top-label">添加定向时的竞价设置: </span>
              <el-select v-model="bidType">
                <el-option v-for="item in bidTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input v-model="bid" :disabled="bidType == '1'" style="width: 200px">
                <template #prepend>$</template>
              </el-input>
            </div>
            <el-tab-pane label="品类" name="category">
              <el-tabs v-model="viewsTabName" type="border-card" @tab-click="handleTabClick">
                <el-tab-pane label="建议" name="advice">
                  <div style="height: 525px">
                    <div>动态细分</div>
                    <hr style="margin: 5px 0" />
                    <div>
                      <div style="display: flex; justify-content: space-between">
                        <div>与广告商品相似</div>
                        <el-button type="primary" size="small" link @click="addDynamicSegment">添加</el-button>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="搜索" name="search">
                  <CategorySearch @add-to-table="handleAddToTable" @form-submitted="handleRefine"></CategorySearch>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <el-tab-pane label="单个商品" name="single">
              <el-tabs v-model="purchasesTabName" type="border-card">
                <el-tab-pane label="建议" name="advice">
                  <div style="height: 525px"></div>
                </el-tab-pane>
                <el-tab-pane label="搜索" name="search">
                  <SingleSearch @updateSelected="handleSelectedCommodities"></SingleSearch>
                </el-tab-pane>
                <el-tab-pane label="输入" name="input">
                  <div style="height: 525px"></div>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 右侧内容区 -->
        <div class="right-container">
          <div class="right-container-top">
            <el-text class="mx-1" style="padding-left: 15px">已添加: {{ addedTableData.length }}</el-text>
            <el-text class="mx-1" type="success">成功: {{ successCount }}</el-text>
            <el-text class="mx-1" type="danger">失败: {{ failureCount }}</el-text>
            <el-button link type="danger" @click="handleDeleteAll" style="margin-right: 15px">删除所有</el-button>
          </div>
          <el-table :data="addedTableData" :header-cell-style="changeTableHeader" height="600" style="width: 100%">
            <el-table-column prop="date" label="商品">
              <template #default="{ row }">
                <div v-if="row.currentTitle" style="color: black; font-weight: 450">{{ row.currentTitle }}</div>
                <div v-if="row.cna || row.dialogTitle">
                  分类: <span style="color: black">{{ row.cna ? row.cna : row.dialogTitle }}</span>
                </div>
                <div v-if="row.brand">
                  品牌: <span style="color: black">{{ row.brand ? row.brand : '--' }}</span>
                </div>
                <div v-if="row.low_prices || row.high_prices">
                  商品价格: <span style="color: black">${{ row.low_prices ? row.low_prices : '--' }}</span>
                  <span> -</span>
                  <span style="color: black"> ${{ row.high_prices ? row.high_prices : '--' }}</span>
                </div>
                <div v-if="row.delivery">
                  配送:
                  <span style="color: black">{{ row.delivery ? deliveryMap[row.delivery] : '--' }}</span>
                </div>
                <div v-if="row.lookback">
                  回溯期: <span style="color: black">{{ row.lookback ? row.lookback : '--' }}</span>
                </div>
                <div v-if="row.audienceName">
                  <div style="font-weight: 500; color: #000">{{ row.category }}</div>
                  <el-tooltip class="box-item" effect="dark" :content="row.audienceName" placement="top">
                    <div style="white-space: nowrap; text-overflow: ellipsis; overflow: hidden">{{ row.audienceName }}</div>
                  </el-tooltip>
                  <div style="color: rgba(0, 0, 0, 0.45)">预估人数: {{ row.lowerBoundInclusive }} - {{ row.upperBoundExclusive }}</div>
                </div>
                <div v-if="row.image_link" style="display: flex; align-items: center">
                  <div style="margin-right: 8px; line-height: normal">
                    <el-image class="img-box" :src="row.image_link" />
                  </div>
                  <div>
                    <el-tooltip class="box-item" effect="dark" :content="row.title" placement="top">
                      <div class="double-line">{{ row.title ? row.title : '--' }}</div>
                    </el-tooltip>
                    <span
                      >ASIN:
                      <span class="data-color" style="margin-right: 8px">{{ row.asin ? row.asin : '--' }}</span>
                    </span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="竞价" width="160">
              <template #default="{ row }">
                <el-input v-model.number="bid">
                  <template #prepend>$</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="当前建议竞价" width="160">
              <template #default="{ row }">
                <div>$</div>
                <div>$</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="{ row }">
                <el-button link type="danger" size="small" @click="singleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: space-around; padding-top: 15px">
            <el-button type="primary" plain :disabled="!addedTableData.length" @click="handleSave">保存</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type TabsPaneContext } from 'element-plus'
import { storeToRefs } from 'pinia'
import { Ref, inject, onMounted, ref, watch } from 'vue'
import { postCustomOperation } from '../api/index'
import CategorySearch from './CategorySearch.vue'
import SingleSearch from './SingleSearch.vue'
import { useShopInfo } from '/@/stores/shopInfo'
import emitter from '/@/utils/emitter'

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

// tab栏
const topTabName = ref('category')

function handleTabClick(tab: TabsPaneContext, event: Event) {
  if (tab.props.label == '搜索') {
    emitter.emit('get-category-tree-data')
  }
}

// tab栏顶部固定部分功能
const bidType = ref('2')
const bidTypeOptions = [
  {
    value: '1',
    label: '建议竞价',
  },
  {
    value: '2',
    label: '自定义竞价',
  },
]
const bid = ref('0.3')

watch(
  bidType,
  () => {
    if (bidType.value == '1') {
      bid.value = ''
    } else {
      bid.value = '0.3'
    }
  },
  { immediate: true }
)

const viewsTabName = ref('advice')
const purchasesTabName = ref('advice')

// 获取单个商品的搜索数据
function handleSelectedCommodities(selectedCommodities) {
  const selectedMap = new Map(selectedCommodities.map((item) => [item.asin, item]))

  addedTableData.value = addedTableData.value.filter((item) => item.source !== 'single' || selectedMap.has(item.asin))

  selectedCommodities.forEach((commodity) => {
    const exists = addedTableData.value.some((item) => item.asin === commodity.asin && item.source === 'single')
    if (!exists) {
      addedTableData.value.push({
        ...commodity,
        bid: bid.value,
        source: 'single',
      })
    } else {
      ElMessage({
        message: `商品 ${commodity.asin} 已经添加，不能重复添加`,
        type: 'warning',
      })
    }
  })
}

// 已添加的表格数据
const addedTableData = ref([])

// 删除所有Table数据
function handleDeleteAll() {
  addedTableData.value = []
}

// 单个删除功能
function singleDelete(row) {
  addedTableData.value = addedTableData.value.filter((item) => item !== row)
}

function handleAddToTable(data) {
  // 检查该数据是否已经存在于 addedTableData 中
  // const exists = addedTableData.value.some((item) => item.classificationId === data.cid)
  // if (!exists) {
  const tableRow = {
    type: 'c',
    cna: data.cna,
    bid: bid.value,
    classificationId: data.cid,
  }
  addedTableData.value.push(tableRow)
  // addedTableData.value.push(data)
  // } else {
  //   ElMessage({
  //     message: '请勿重复添加',
  //     type: 'warning',
  //   })
  // }
}

// 点击细化后弹窗确认触发
function handleRefine(data) {
  const tableRow = {
    type: 'c',
    brand: data.selectedLabels,
    bid: bid.value,
    brandId: data.selectedBrands,
    classificationId: data.cid,
    delivery: data.delivery,
    dialogTitle: data.dialogTitle,
    low_prices: data.prices.lowest,
    high_prices: data.prices.highest,
    low_rating: data.starRating[0],
    high_rating: data.starRating[1],
  }
  addedTableData.value.push(tableRow)
}

const deliveryMap = {
  eligible: '具备Prime资格',
  diseligible: '不具备Prime资格',
  all: '所有',
}
const promoteGoodsAsin = ref('')

function addDynamicSegment() {
  const newProduct = {
    currentTitle: '与广告商品相似',
    type: 'p',
    // lookback: viewsLookBack.value,
    asin: promoteGoodsAsin.value,
    bid: bid.value,
    productType: 'similarProduct',
  }
  const exists = addedTableData.value.some((item) => item.type === newProduct.type && item.productType === newProduct.productType)

  if (!exists) {
    addedTableData.value.push(newProduct)
  } else {
    ElMessage({
      message: '已经添加了相关商品，不能重复添加',
      type: 'warning',
    })
  }
}

// 点击保存触发
const loading = ref(false)
const successCount = ref('')
const failureCount = ref('')

async function handleSave() {
  const body = {
    profile_id: profile.value.profile_id,
    campaignId: respCampaignId.value,
    adGroupId: respAdGroupId.value,
    tactic: 'T00020',
    expressionType: 'manual',
    expressionList: addedTableData.value,
    state: 'paused',
  }
  try {
    loading.value = true
    const response = await postCustomOperation(body)
    successCount.value = response.data.success.length
    failureCount.value = response.data.error.length
    if (response.data.error.length == 0) {
      addedTableData.value = []
      ElMessage({
        message: '创建成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '创建失败',
        type: 'error',
      })
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    loading.value = false
  }
}

function changeTableHeader(row) {
  if (row) {
    return {
      background: '#f5f7fa',
    }
  }
}

onMounted(() => {
  emitter.on('send-firstAsin', (value: any) => {
    promoteGoodsAsin.value = value
  })
})
</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;
}
.main-container {
  display: flex;
  border: 1px solid #e5e7eb;
  height: 700px;
  margin-bottom: 20px;
  border-radius: 6px;
}
.left-container {
  width: 50%;
  height: 699px;
  border-right: 1px solid #e5e7eb;
}
.right-container {
  width: 50%;
  height: 699px;
  border-bottom: 0;
}
.right-container-top {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.demo-tabs {
  padding: 0 10px;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
/* 选中时的字体颜色 */
::v-deep(.demo-tabs .el-tabs__item.is-top.is-active) {
  color: #3569d6;
}
/* 选中时的下划线颜色 */
::v-deep(.demo-tabs .el-tabs__active-bar.is-top) {
  background-color: #3569d6;
}
.tab-container-fixed-top {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  gap: 8px;
  font-size: 13px;
  margin: 10px 0;
}
.tab-top-label {
  color: #4e5969;
  font-weight: 700;
  margin-right: 10px;
}
.align-center-bottom {
  align-items: center;
  margin-bottom: 12px;
}
.tab-title {
  line-height: 20px;
  padding-bottom: 10px;
  color: #8e9095;
}
.select-label {
  padding-right: 5px;
  color: #606266;
}
/* 修改隐藏table底部border */
::v-deep(.el-table__inner-wrapper::before) {
  background-color: #ffffff;
}
.double-line {
  color: #1e2128;
  font-weight: 500;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  white-space: pre-wrap;
  word-break: break-word;
}
.data-color {
  color: rgb(30, 33, 41);
}
.img-box {
  width: 60px;
  height: 60px;
  margin-top: 5px;
  border: 1px solid rgb(194, 199, 207);
  border-radius: 4px;
}
</style>
