<template>
  <div class="guidelines-data-wrap">
    <div class="part-div">
      <div>
        <a-tabs
          v-model:activeKey="tabData"
          @tab-click="onSearch"
          class="a-tab-class"
          default-active-key="placement_guide"
        >
          <a-tab-pane key="placement_guide" title="投放指南"></a-tab-pane>
          <a-tab-pane key="guide_history">
            <template #title>历史投放指南</template>
          </a-tab-pane>
        </a-tabs>
      </div>
      <!--表单组件搜索-->
      <listSearchForm v-model:query="query" @onSearch="onSearch"></listSearchForm>

      <component
        :is="currentComponent"
        :listData="tabData === 'placement_guide' ? placementGuideList : guideHistoryList"
        @onSearch="onSearch"
        @updateQuery="handleUpdateQuery"
      />

      <div v-if="listData.total > 0" class="pagination-box flex justify-end">
        <a-pagination
          :total="listData.total"
          size="mini"
          show-total
          show-jumper
          show-page-size
          :current="query.page"
          :page-size="query.pageSize"
          @change="onPageChange"
          @page-size-change="onPageSizeChange"
        />
      </div>
    </div>

    <div v-if="tabData === 'placement_guide'">
      <a-spin :loading="loading" tip="AI分析中">
        <!--    本月摘要-->
        <MonthData :overview="aiResult.overview"></MonthData>

        <!--    投放建议-->
        <PlacementSuggestions :optimization="aiResult.optimization"></PlacementSuggestions>
        <!--      投放行动指南-->
        <ActionGuideDistribution :action_guide="aiResult.action_guide"></ActionGuideDistribution>
      </a-spin>
    </div>
    <div v-if="tabData == 'placement_guide'">
      <a-space class="down-btn">
        <a-button type="outline" @click="downPage">
          <template #icon>
            <icon-download />
          </template>
          <template #default>下载</template>
        </a-button>
        <a-button type="primary" @click="handleSave">
          <template #icon>
            <icon-drive-file />
          </template>
          <template #default>保存</template>
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import PlacementGuideList from './components/table-data/placementGuideList.vue';
import listSearchForm from './components/table-data/listSearchForm.vue';
import GuideListHistory from './components/table-data/guideListHistory.vue';
import MonthData from './components/month-data/index.vue';
import PlacementSuggestions from './components/placement-suggestions/index.vue';
import ActionGuideDistribution from './components/action-guide-distribution';
import {
  getAiResult,
  getPlacementGuide,
  getPlacementGuideHistory,
  savePlacementGuide,
} from '@/api/all/propertyMarketing';
import { Message } from '@arco-design/web-vue';
import html2canvas from 'html2canvas';
import { AiResultStatus } from '@/views/property-marketing/put-account/investment-guidelines/constants';

const tabData = ref('placement_guide');

const query = reactive({
  platform: '',
  date_time: '',
  sort_column: '',
  sort_order: '',
  page_size: 20,
  page: 1,
});

const currentComponent = computed(() => {
  return tabData.value === 'placement_guide' ? PlacementGuideList : GuideListHistory;
});
const onPageChange = (current) => {
  query.page = current;
  onSearch();
};
const onPageSizeChange = (pageSize) => {
  query.page_size = pageSize;
  onSearch();
};

const handleUpdateQuery = (payload) => {
  payload.order = payload.order === 'ascend' ? 'asc' : 'desc';
  query.sort_column = payload.column;
  query.sort_order = payload.order;
  onSearch();
};

const loading = ref(false);

const listData = reactive({
  total: 0,
  list: [],
});
const placementGuideList = ref([]); // 投放指南数据
const guideHistoryList = ref([]); // 历史投放指南数据

const onSearch = async () => {
  let result;
  if (tabData.value === 'placement_guide') {
    result = await getPlacementGuide(query);
    placementGuideList.value = result?.data?.data || [];
  } else {
    result = await getPlacementGuideHistory(query);
    guideHistoryList.value = result?.data?.data || [];
  }
  listData.total = result.data.total;
  if (placementGuideList.value.length > 0) {
    loading.value = true;
    startTask();
  }
};
const aiResult = reactive({
  optimization: [], // 投放建议优化
  action_guide: [], // 新投放建议生成
  overview: [], // 新投放建议生成
});

// 下载当前页面

const downPage = async () => {
  await nextTick(); // 确保 DOM 更新完成
  html2canvas(document.querySelector('.guidelines-data-wrap')).then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = imgData;
    const timestamp = new Date().getTime();
    link.download = `投放指南-${timestamp}.png`;
    link.click();
  });
};
const saveForm = reactive({
  account: [],
  plan: [],
  platform: [],
  aiResult: [],
  code: '',
});
const timerRef = ref<number | null>(null);

const startTask = () => {
  if (timerRef.value !== null) return;
  timerRef.value = setInterval(async () => {
    try {
      const { code, data } = await getAiResult(query);
      console.log('定时任务执行结果:', data);
      if (data.ai_result_status === AiResultStatus.SUCCESS || data.ai_result_status === AiResultStatus.FAILED) {
        stopTask();
        console.log('任务已完成，定时器已关闭');
      }
      if (data.ai_result_status === AiResultStatus.SUCCESS) {
        loading.value = false;
        aiResult.optimization = data.result?.optimization?.modules || [];
        aiResult.action_guide = data.result?.action_guide?.modules || [];
        aiResult.overview = data.result?.overview || [];
      }
      saveForm.code = data?.code;
      console.log(aiResult, 'aiResult');
    } catch (error) {
      console.error('定时任务执行出错:', error);
      stopTask();
    }
  }, 5000);
};
const stopTask = () => {
  if (timerRef.value !== null) {
    clearInterval(timerRef.value); // 清除定时器
    timerRef.value = null; // 重置引用
    console.log('定时器已停止');
  }
};
onUnmounted(() => {
  stopTask();
});
const handleSave = async () => {
  const updatedSaveForm = {
    ...saveForm,
    ai_result: aiResult,
  };
  const { code, message, data } = await savePlacementGuide(updatedSaveForm);
  if (code === 200) {
    Message.success(message);
  }
};
onMounted(() => {
  onSearch();
});
</script>

<style lang="scss">
@import './style.scss';
</style>
