<script setup lang="ts">
/**
 * @Name: index.vue
 * @Description: Targeting-SearchTerm 跳转页面
 * @Author: Cheney
 */

import { useRoute } from 'vue-router';
import { targetingColumns, searchTermColumns } from './useColumns';
import { reactive, ref, onBeforeMount } from 'vue';
import { storeToRefs } from 'pinia';
import { usePublicData } from '/@/stores/publicData';
import * as api from './api';
import { debounce } from 'lodash';

const publicData = usePublicData();
const { dateRange } = storeToRefs(publicData);
const route = useRoute();
const { searchRoot } = route.query;
const date = ref([dateRange.value[0], dateRange.value[1]]);
const searchType = ref('BROAD');
const targetingSearchRoot = ref('');
const searchTermSearchRoot = ref('');

const TargetingLoading = ref(false);
const searchTermLoading = ref(false);
const targetingOptions: any = reactive({
  height: 'auto',
  border: false,
  round: true,
  columnConfig: {
    resizable: true,
  },
  toolbarConfig: {
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  columns: targetingColumns,
  data: [],
});
const targetingPage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15,
});

const searchTermOptions: any = reactive({
  height: 'auto',
  border: false,
  round: true,
  columnConfig: {
    resizable: true,
  },
  toolbarConfig: {
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  columns: searchTermColumns,
  data: [],
});
const searchTermPage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15,
});

onBeforeMount(() => {
  fetchTableData();
});

function targetingPageChange({ currentPage, pageSize }) {
  targetingPage.currentPage = currentPage;
  targetingPage.pageSize = pageSize;
  fetchTargetingData();
}

function searchTermPageChange({ currentPage, pageSize }) {
  searchTermPage.currentPage = currentPage;
  searchTermPage.pageSize = pageSize;
  fetchSearchTermData();
}

const fetchTableData = debounce(
  () => {
    targetingPage.currentPage = 1;
    targetingPage.pageSize = 15;
    searchTermPage.currentPage = 1;
    searchTermPage.pageSize = 15;
    fetchTargetingData();
    fetchSearchTermData();
  },
  500,
  { leading: true, trailing: false }
); // 首次调用立即执行，500毫秒内的后续调用不生效

async function fetchTargetingData() {
  TargetingLoading.value = true;

  const query = {
    date_start: date.value[0],
    date_end: date.value[1],
    page: targetingPage.currentPage,
    limit: targetingPage.pageSize,
    search_root: targetingSearchRoot.value ? targetingSearchRoot.value : searchRoot,
    search_type: searchType.value, // BROAD, PHRASE, EXACT, AUTO
    term_type: 'TARGETING', // TARGETING, SEARCHTERM
  };
  try {
    const response = await api.getTargetingData(query);
    targetingOptions.data = response.data;
    targetingPage.total = response.total;
  } catch (error) {
    console.log('error=>', error);
  } finally {
    TargetingLoading.value = false;
  }
}

async function fetchSearchTermData() {
  searchTermLoading.value = true;

  const query = {
    date_start: date.value[0],
    date_end: date.value[1],
    page: targetingPage.currentPage,
    limit: targetingPage.pageSize,
    search_root: searchTermSearchRoot.value ? searchTermSearchRoot.value : searchRoot,
    search_type: searchType.value,
    term_type: 'SEARCHTERM',
  };
  try {
    const response = await api.getTargetingData(query);
    searchTermOptions.data = response.data;
    searchTermPage.total = response.total;
  } catch (error) {
    console.log('error=>', error);
  } finally {
    searchTermLoading.value = false;
  }
}
</script>

<template>
  <div class="mx-3">
    <el-divider>
      <div class="font-bold text-xl">
        <!--<el-icon style="top: 3px">-->
        <!--  <DataAnalysis />-->
        <!--</el-icon>-->
        {{ searchRoot }}
      </div>
    </el-divider>
  </div>
  <div class="py-2 px-2.5">
    <el-card shadow="hover" style="border: none" body-class="flex justify-between">
      <div class="flex flex-wrap gap-7">
        <div>
          <span class="font-medium mr-0.5">搜索词类型 </span>
          <el-select v-model="searchType" placeholder="请选择" style="width: 130px">
            <el-option label="自动匹配" value="AUTO"></el-option>
            <el-option label="宽泛匹配" value="BROAD"></el-option>
            <el-option label="短语匹配" value="PHRASE"></el-option>
            <el-option label="精准匹配" value="EXACT"></el-option>
          </el-select>
        </div>
        <div>
          <span class="font-medium mr-0.5">日期 </span>
          <el-date-picker
            v-model="date"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="To"
            :disabled-date="(time: Date) => time > new Date()"
            :popper-options="{ placement: 'bottom-end' }"
            :clearable="false" />
        </div>
      </div>
      <el-button type="primary" plain @click="fetchTableData" icon="search">查询</el-button>
    </el-card>
    <el-card shadow="hover" class="mt-3" style="border: none" body-style="padding-top: 10px">
      <div class="w-full overflow-hidden" style="height: 950px" v-loading="TargetingLoading">
        <vxe-grid v-bind="targetingOptions">
          <template #toolbar_buttons>
            <span class="font-medium text-xl" style="color: #000000"> Targeting-关联关键词 </span>
            <el-input v-model="targetingSearchRoot" placeholder="请输入关键词回车搜索" @change="fetchTargetingData" class="ml-5" style="width: 200px;"></el-input>
          </template>
          <template v-for="col in targetingColumns" #[`${col.field}_default`]="{ row }">
            <div v-if="col.field === 'targeting'">
              <el-tooltip effect="dark" :content="row.targeting" placement="top" :show-after="300">
                <div class="font-medium overflow-hidden whitespace-nowrap text-ellipsis">
                  {{ row.targeting }}
                </div>
              </el-tooltip>
            </div>
            <div v-else-if="col.field === 'ctr_1d'">
              <span class="font-medium"> {{ row.ctr_1d }}% </span>
            </div>
            <div v-else-if="col.field === 'cr_1d'">
              <span class="font-medium"> {{ row.cr_1d }}% </span>
            </div>
            <div v-else class="font-medium">
              {{ row[col.field] ? row[col.field] : '--' }}
            </div>
          </template>
          <template #pager>
            <vxe-pager
              :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
              v-model:current-page="targetingPage.currentPage"
              v-model:page-size="targetingPage.pageSize"
              :total="targetingPage.total"
              @page-change="targetingPageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </el-card>
    <el-card shadow="hover" class="mt-3" style="border: none" body-style="padding-top: 10px">
      <div class="w-full overflow-hidden" style="height: 950px" v-loading="searchTermLoading">
        <vxe-grid v-bind="searchTermOptions">
          <template #toolbar_buttons>
            <span class="font-medium text-xl" style="color: #000000"> SearchTerm-相关搜索结果 </span>
            <el-input v-model="searchTermSearchRoot" placeholder="请输入搜索词回车搜索" @change="fetchTargetingData" class="ml-5" style="width: 200px;"></el-input>
          </template>
          <template v-for="col in searchTermColumns" #[`${col.field}_default`]="{ row }">
            <div v-if="col.field === 'searchTerm'">
              <el-tooltip effect="dark" :content="row.searchTerm" placement="top" :show-after="300">
                <div class="font-medium overflow-hidden whitespace-nowrap text-ellipsis">
                  {{ row.searchTerm }}
                </div>
              </el-tooltip>
            </div>
            <div v-else-if="col.field === 'ctr_1d'">
              <span class="font-medium"> {{ row.ctr_1d }}% </span>
            </div>
            <div v-else-if="col.field === 'cr_1d'">
              <span class="font-medium"> {{ row.cr_1d }}% </span>
            </div>
            <div v-else class="font-medium">
              {{ row[col.field] ? row[col.field] : '--' }}
            </div>
          </template>
          <template #pager>
            <vxe-pager
              :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
              v-model:current-page="searchTermPage.currentPage"
              v-model:page-size="searchTermPage.pageSize"
              :total="searchTermPage.total"
              @page-change="searchTermPageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
/* 修改 el-divider 的背景颜色 */
:deep(.el-divider__text.is-center.el-divider__text) {
  background-color: #f8f8f8;
}
</style>
