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

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

const tableData = reactive([])
let negativeWordsLoading = ref(false)
let negativeList = reactive([])
let negativeWordsTextarea = ref('')
let NEGATIVE_PHRASE = ref(true)
let NEGATIVE_EXACT = ref(true)
let exactNegativeList = reactive([]) // 用于存储精确否定的数组
let phraseNegativeList = reactive([]) // 用于存储词组否定的数组

function addNegative() {
  const trimmedText = negativeWordsTextarea.value.trim()
  const items = trimmedText.split(/,|\n/)

  items.forEach((item) => {
    const trimmedItem = item.trim()
    if (trimmedItem) {
      let phraseEntry = '词组: ' + trimmedItem
      let exactEntry = '精确: ' + trimmedItem

      if (NEGATIVE_PHRASE.value && !negativeList.some((n) => n.negativeWords === phraseEntry)) {
        negativeList.push({ negativeWords: phraseEntry })
        phraseNegativeList.push(trimmedItem) // 添加到词组否定数组
      }
      if (NEGATIVE_EXACT.value && !negativeList.some((n) => n.negativeWords === exactEntry)) {
        negativeList.push({ negativeWords: exactEntry })
        exactNegativeList.push(trimmedItem) // 添加到精确否定数组
      }
    } else {
      console.log('有空项目,未被添加到列表中')
    }
  })

  negativeWordsTextarea.value = ''
  console.log('🚀 ~ exactNegativeList-->>', exactNegativeList)
  console.log('🚀 ~ phraseNegativeList-->>', phraseNegativeList)
}

function delAllNegative() {
  // negativeList.splice(0, negativeList.length)
  negativeList.length = 0
  exactNegativeList.length = 0
  phraseNegativeList.length = 0
}

function delSingleNegative(scope) {
  const index = negativeList.findIndex((item) => item.negativeWords === scope.row.negativeWords)
  if (index !== -1) {
    // 确定被删除的项是词组还是精确
    const isPhrase = scope.row.negativeWords.startsWith('词组: ')
    const isExact = scope.row.negativeWords.startsWith('精确: ')

    // 从 negativeList 删除
    if (negativeList.length) {
      negativeList.splice(index, 1)
      console.log(`已删除索引为 ${index} 的条目`)
    } else {
      console.log('无效的索引，无法删除条目')
    }

    // 从 exactNegativeList 或 phraseNegativeList 删除
    const trimmedItem = scope.row.negativeWords.substring(4).trim() // 从 '词组: ' 或 '精确: ' 后开始截取
    if (isPhrase) {
      const phraseIndex = phraseNegativeList.findIndex((item) => item === trimmedItem)
      if (phraseIndex !== -1) {
        phraseNegativeList.splice(phraseIndex, 1)
      }
    } else if (isExact) {
      const exactIndex = exactNegativeList.findIndex((item) => item === trimmedItem)
      if (exactIndex !== -1) {
        exactNegativeList.splice(exactIndex, 1)
      }
    }
  } else {
    console.log('无效的索引，无法删除条目')
  }
}

async function negativeWordsSave() {
  negativeWordsLoading.value = true
  console.log('negativeList', negativeList)
  createNegativeWords()
  // try {
  //   const requestData = {
  //     profile_id: profile.value.profile_id,
  //     campaignId: respCampaignId.value,
  //     adGroupId: respAdGroupId.value,
  //     state: 'PAUSED',
  //     EkeywordList: exactNegativeList,
  //     PkeywordList: phraseNegativeList,
  //   }
  //   const filteredRequestData = Object.fromEntries(Object.entries(requestData).filter(([_, v]) => v != null))

  //   console.log('🚀 ~ negativeWordsSave ~ resp-->>', resp)
  //   negativeWordsLoading.value = false
  //   if (resp.data.negativeKeyworderror.length !== 0) {
  //     ElMessage({
  //       message: '否定词创建成功',
  //       type: 'success',
  //     })
  //     delAllNegative()
  //   } else {
  //     ElMessage.error('否定词创建失败!')
  //   }
  // } catch (error) {
  //   console.error('请求失败：', error)
  // }
}

async function createNegativeWords() {
  const negativeWordsData = {
    profile_id: profile.value.profile_id,
    campaignId: respCampaignId.value,
    adGroupId: respAdGroupId.value,
    state: 'PAUSED',
    EkeywordList: exactNegativeList,
    PkeywordList: phraseNegativeList,
  }
  const filteredRequestData = Object.fromEntries(Object.entries(negativeWordsData).filter(([_, v]) => v != null))
  try {
    const response = await postNegativeWordData(filteredRequestData)
    console.log('🚀 ~ createCampaigns ~ response-->>', response)
      if (response.data.negativeKeyworderror.length !== 0) {
      ElMessage({
        message: '否定词创建成功',
        type: 'success',
      })
      delAllNegative()
    } else {
      ElMessage.error('否定词创建失败!')
    }
  } catch (error) {
    console.error('请求失败：', error)
  } finally {
    negativeWordsLoading.value = false
  }
}

function changeNegTableHeader(args) {
  if (args.rowIndex === 0) {
    return {
      color: '#505968',
    }
  }
}
</script>

<template>
  <div 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: 520px; display: flex; border: 1px solid #e5e7ec; border-radius: 6px">
      <div style="width: 50%; border-right: 1px solid #e5e7ec">
        <div style="margin: 10px 0">
          <span style="margin-left: 25px; color: #e47470">*</span>
          <span style="color: #666666; margin-right: 10px">匹配类型: </span>
          <el-checkbox v-model="NEGATIVE_PHRASE" label="词组否定" />
          <el-checkbox v-model="NEGATIVE_EXACT" label="精确否定" />
        </div>
        <el-input
          v-model="negativeWordsTextarea"
          :rows="17"
          type="textarea"
          placeholder="请输入关键词，多个关键词使用逗号或者换行符分隔。(最多添加1000个关键词)"
          maxlength="11000"
          style="padding: 0 20px" />
        <div style="display: flex; flex-direction: row-reverse; margin-top: 10px">
          <el-button style="margin-right: 18px" type="primary" text bg :disabled="!negativeWordsTextarea" @click="addNegative">添加</el-button>
        </div>
      </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">已添加: {{ negativeList.length }}</span>
              <el-button class="button" type="danger" text bg @click="delAllNegative">全部删除</el-button>
            </div>
          </template>
          <div class="card-body">
            <el-table :data="negativeList" style="width: 100%; height: 370px; padding-bottom: 0" :header-row-style="changeNegTableHeader">
              <el-table-column prop="negativeWords" label="否定词" width="auto" />
              <el-table-column prop="operate" label="操作" width="60" align="right">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="delSingleNegative(scope)" text>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
        <div style="display: flex; justify-content: space-around">
          <el-button type="primary" plain @click="negativeWordsSave" :disabled="!negativeList.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;
}
.demo-tabs > .el-tabs__content {
  padding: 52px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
/* 左侧表格Tab栏 */
::v-deep(.el-tabs__nav-scroll) {
  overflow: hidden;
  margin-left: 20px;
}
::v-deep(.el-table__inner-wrapper::before) {
  background-color: white;
}
// 表格内容边距
div {
  & #pane-first,
  & #pane-second {
    margin: 10px;
  }
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  width: 100%;
  margin-right: 10px;
}
.data-color {
  color: rgb(30, 33, 41);
}
</style>
