<script setup lang="ts">
import { Ref, inject, reactive, ref } from 'vue'
import { useShopInfo } from '/@/stores/shopInfo'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { request } from '/@/utils/service'

let selections = [] // 添加选中的项
let addedSels = [] // 删除选中的项
const currentPage = ref() // 当前页
const pageSize = ref(20) // 每页显示条目数
const totalItems = ref() // 数据总量
const negativeTabs = ref('first')
const topTabs = ref('first')
const loading = ref(false)
const respCampaignId = inject<Ref>('respCampaignId')
const respAdGroupId = inject<Ref>('respAdGroupId')
const shopInfo = useShopInfo()
const { profile } = storeToRefs(shopInfo)
const negativeTableData = ref([])
const addedNegetiveTableData = ref([])
let negativeGoodsLoading = ref(false)
let negativeList = reactive([])
const tableData = negativeList
let inputAddedNegGoods = ref([])
const negativeInput = ref('')

function setNegativeTableData(asin = '') {
  negativeGoodsLoading.value = true
  return request({
    url: '/api/sellers/listings/all/',
    method: 'GET',
    params: {
      page: currentPage.value,
      limit: pageSize.value,
      profile_id: profile.value.profile_id,
      asin,
    },
  })
    .then((resp) => {
      negativeTableData.value = resp.data
      inputAddedNegGoods.value = resp.data
      negativeGoodsLoading.value = false
    })
    .catch((error) => {
      console.error('Error fetching data:', error)
      negativeGoodsLoading.value = false
    })
}

 const negativeGoodsTextarea = ref('')
// 输入tab的textarea
function addNegativeGoods() {
  console.log('negativeGoodsTextarea', negativeGoodsTextarea.value)
  loading.value = true

  setNegativeTableData(negativeGoodsTextarea.value)
    .then(() => {
      addedNegetiveTableData.value = [...addedNegetiveTableData.value, ...inputAddedNegGoods.value]
    })
    .catch((error) => {
      console.error('Error fetching data:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

function addSingleNegativeGoods(scope) {
  const isAlreadyAdded = addedNegetiveTableData.value.some((item) => item.asin === scope.row.asin)
  if (!isAlreadyAdded) {
    addedNegetiveTableData.value.push(scope.row)
  } else {
    console.log('Item is already added.')
  }
}

function delAllNegativeGoods() {
  addedNegetiveTableData.value = []
}

function delSingleNegativeGoods(scope) {
  const index = addedNegetiveTableData.value.findIndex((item) => item.asin === scope.row.asin)

  if (index !== -1) {
    addedNegetiveTableData.value.splice(index, 1)
    console.log('Item removed successfully.')
  } else {
    console.log('Item not found.')
  }
}

function searchNegativeGoods(e) {
  console.log(e)
  if (e === '') {
    negativeTableData.value = []
  } else {
    setNegativeTableData(e)
  }
}

function handleAddedNegGoods(selection) {
  addedSels = selection
}


async function negativeGoodsSave() {
  console.log(addedNegetiveTableData.value)
  const asinList = addedNegetiveTableData.value.map((item) => item.asin)
  console.log('🚀 ~ negativeGoodsSave ~ asinList-->>', asinList)
  negativeGoodsLoading.value = true
  console.log('addedNegetiveTableData', addedNegetiveTableData.value)
  try {
    const requestData = {
      profile_id: profile.value.profile_id,
      campaignId: respCampaignId.value,
      adGroupId: respAdGroupId.value,
      asinList: asinList,
      matchType: 'ASIN_SAME_AS',
      state: 'PAUSED',
    }
    const filteredRequestData = Object.fromEntries(Object.entries(requestData).filter(([_, v]) => v != null))
    const resp = await request({
      url: '/api/ad_manage/sptargets/add/negative/targets/',
      method: 'POST',
      data: filteredRequestData,
    })
    console.log('🚀 ~ negativeWordsSave ~ resp-->>', resp)
    negativeGoodsLoading.value = false
    if (resp.data.success.length !== 0) {
      ElMessage({
        message: '否定商品创建成功',
        type: 'success',
      })
      delAllNegative()
    } else {
      ElMessage.error('否定商品创建失败!')
    }
  } catch (error) {
    console.error('请求失败：', error)
  }
}

function delAllNegative() {
  negativeList.length = 0
}

const headerCellStyle = (args) => {
  if (args.rowIndex === 0) {
    return {
      backgroundColor: 'rgba(245, 245, 245, 0.9)',
    }
  }
}
</script>

<template>
  <div prop="matchType" style="width: 100%; margin-top: 20px">
    <el-divider content-position="left">
      <span style="font-size: 18px; font-weight: 700">否定商品</span>
    </el-divider>
    <div style="width: 100%; height: 600px; display: flex; border: 1px solid #e5e7ec; border-radius: 6px" v-loading="negativeGoodsLoading">
      <div style="width: 50%; border-right: 1px solid #e5e7ec">
        <el-tabs v-model="topTabs" stretch>
          <el-tab-pane label="排除商品" name="first">
            <el-tabs v-model="negativeTabs" class="demo-tabs">
              <el-tab-pane label="搜索" name="first">
                <div style="margin-bottom: 10px">
                  <el-input placeholder="按ASIN搜索" v-model="negativeInput" @change="searchNegativeGoods" clearable />
                </div>
                <el-table
                  height="495"
                  style="width: 100%"
                  v-loading="loading"
                  :data="negativeTableData"
                  :header-cell-style="headerCellStyle"
                  :show-header="false">
                  <el-table-column prop="asin" label="商品">
                    <template #default="scope">
                      <div style="display: flex; align-items: center">
                        <div style="margin-right: 8px; line-height: normal">
                          <el-image class="img-box" :src="scope.row.image_link" />
                        </div>
                        <div>
                          <el-tooltip class="box-item" effect="dark" :content="scope.row.title" placement="top">
                            <div class="single-line">{{ scope.row.title ? scope.row.title : '--' }}</div>
                          </el-tooltip>
                          <span>
                            ASIN: <span class="data-color" style="margin-right: 8px">{{ scope.row.asin ? scope.row.asin : '--' }}</span>
                          </span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="Name" width="120" align="right">
                    <template #header> </template>
                    <template #default="scope">
                      <el-button type="primary" size="small" @click="addSingleNegativeGoods(scope)" text>添加</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="输入" name="second">
                <el-input
                  v-model="negativeGoodsTextarea"
                  :rows="17"
                  type="textarea"
                  disabled="true"
                  maxlength="11000"
                  style="padding: 10px 10px" />
                <div style="display: flex; flex-direction: row-reverse; margin-top: 10px">
                  <el-button style="margin-right: 10px" type="primary" text bg @click="addNegativeGoods">添加</el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
          <el-tab-pane label="排除品牌" name="second">

          </el-tab-pane>
        </el-tabs>
      </div>
      <div style="width: 50%">
        <el-card class="box-card" shadow="never" style="border: none">
          <template #header>
            <div class="card-header">
              <span style="font-weight: 550; font-size: 15px; color: #1f2128">已添加: {{ addedNegetiveTableData.length }}</span>
              <el-button class="button" type="danger" text bg @click="delAllNegativeGoods">全部删除</el-button>
            </div>
          </template>
          <div class="card-body"></div>
        </el-card>
        <div style="padding: 0 10px 0 10px; margin-top: -30px">
          <el-table
            :data="addedNegetiveTableData"
            height="473"
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            @selection-change="handleAddedNegGoods">
            <el-table-column prop="asin" label="商品">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 8px; line-height: normal">
                    <el-image class="img-box" :src="scope.row.image_link" />
                  </div>
                  <div>
                    <el-tooltip class="box-item" effect="dark" :content="scope.row.title" placement="top">
                      <div class="single-line">{{ scope.row.title ? scope.row.title : '--' }}</div>
                    </el-tooltip>
                    <span
                      >ASIN:
                      <span class="data-color" style="margin-right: 8px">{{ scope.row.asin ? scope.row.asin : '--' }}</span>
                    </span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="right">
              <template #default="scope">
                <el-button type="primary" size="small" @click="delSingleNegativeGoods(scope)" text>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="display: flex; justify-content: space-around; padding-top: 10px">
          <el-button plain type="primary" @click="negativeGoodsSave" :disabled="!addedNegetiveTableData.length">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
::v-deep(.el-form--default.el-form--label-top .el-form-item .el-form-item__label) {
  font-weight: 500;
}
.column-margin-bottom label.el-radio.is-bordered {
  margin-bottom: 10px;
  padding: 35px;
}
::v-deep(.column-margin-bottom label.el-radio.is-bordered span.el-radio__inner) {
  margin-top: -18px;
  margin-left: -15px;
}
.demo-tabs > .el-tabs__content {
  padding: 52px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
/* 广告组商品Tab栏 */
::v-deep(.demo-tabs .el-tabs__nav-scroll) {
  overflow: hidden;
  margin-left: 20px;
}
::v-deep(.el-tabs__nav-wrap::after) {
  height: 2px !important;
}
::v-deep(.el-table__inner-wrapper::before) {
  background-color: white;
}
// 表格内容边距
div {
  & #pane-first,
  & #pane-second {
    margin: 10px;
  }
}
// 输入底部样式
::v-deep(.card-box .el-card__body) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  width: 100%;
  // margin: 10px 0 10px 10px;
  margin-right: 10px;
}
.single-line {
  color: rgb(30, 33, 41);
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  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;
}
::v-deep(.goods-orientation-tabs .el-tabs__nav-scroll) {
  margin-left: -20px !important;
}
::v-deep(.category-tabs .el-tabs__nav) {
  margin-left: 20px;
}
::v-deep(.goods-orientation-tabs #tab-1) {
  /* 商品定向Tab栏 */
  border-right: 0;
}
</style>
