<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { NTabs, NTab } from 'naive-ui';
// import * as G2Plot from '@antv/g2plot';
import * as echarts from 'echarts';
import { getAreaOptions, areaOptions } from '@/utils/echartOptions'
// import { Area } from '@antv/g2plot';
import { useChatStore } from '@/stores/modules/chatStore';
import { BaseTable, ChatWelcome, RecodeSquareCardItem, TheSubMenu, TheChatView } from "@/components";
import { ChatBaseCard, ChatAnswer } from '@/components/Chat';
import { formatToData, replaceArray } from "@/utils/format";
import { waterApi } from '@/api/water';
import { useInfinite, useRecommend, useScroll } from '@/composables'
import { columns } from './config';

const { recommendList } = useRecommend({ type: 3 });
const { scrollRef, scrollToTop } = useScroll();
const { recordList, isFetching, onScrolltolower, onRestore } = useInfinite('/front/bigModel/warning/pageList', { type: 2, warningStatus: 0 });

const router = useRouter();
const chatStore = useChatStore();

const answerResult = ref("");
const textDataSources = ref(null);
const chartTitle = ref("");

let chart = {};
const echartRef = ref({});

// 进出水数据
const jsTableData = ref([]);
const csTableData = ref([]);

// 切换Tabs
const onChangeTabs = warningStatus => {
  answerResult.value = '';
  textDataSources.value = '';
  onRestore({ warningStatus })
}

// 打开详情
const handleOpenContent = async ({ id, reason: title }) => {
  const { data } = await waterApi.getWaringDetails(id);
  const showVal = JSON.parse(data.showVal);
  const { basic, jsData, csData, chartsData, chartsTitle } = showVal;

  answerResult.value = data.answer;

  chartTitle.value = chartsTitle;

  basic.title = title
  textDataSources.value = formatToData(basic, '预测值');

  jsTableData.value = [jsData];
  csTableData.value = [csData];

  createLineChat(chartsData);
  scrollToTop();
}

// 创建图表
const createLineChat = (data) => {
  const [xAxisData, yData] = data.reduce((acc, { time, val }) => {
    acc[0].push(time);
    acc[1].push(val);
    return acc;
  }, [[], []]);

  const seriesPast = replaceArray([...yData], yData.length - 3, 3, null);
  const seriesFuture = replaceArray([...yData], 0, 5, null);
  const option = getAreaOptions({xAxisData, seriesList: [seriesPast, seriesFuture]});
  chart.setOption(option);
}

// 欢迎 - 问答
const handleWelcomeRecommend = question => {
  chatStore.setChatQuestion(question);
  router.push('/answer');
}

onMounted(() => {
  chart = echarts.init(echartRef.value, 'light');
})
</script>

<template>
  <section class="flex items-start h-full" id="warning">


    <TheSubMenu title="预测预警" @scrollToLower="onScrolltolower" :loading="isFetching">
      <template #top>
        <div class="border-[#DAE5ED]">
          <n-tabs type="line" justify-content="space-evenly">
            <n-tab name="oasis" tab="正在预警" @click="onChangeTabs(0)"></n-tab>
            <n-tab name="thebeatles" tab="历史预警" @click="onChangeTabs(1)"></n-tab>
          </n-tabs>
        </div>
      </template>
      <div class="px-[12px] py-[14px] text-[#5e5e5e]">
        <div class="grid grid-cols-1 gap-[12px]">
          <RecodeSquareCardItem v-for="item in recordList" :key="item.id" :item="item" @on-click="handleOpenContent" />
        </div>
      </div>
    </TheSubMenu>

    <TheChatView ref="scrollRef" :is-footer="false">
      <ChatWelcome title="您好,我是LibraAI工艺管控助手" card-title="常见处理方案：" :sub-title="[
      '报警分析功能具备实时监测与预警机制，检测到异常情况推送相关工作人员确保问题及时处理',
      '报警时间为每小时警报，请大家及时处理'
    ]" v-if="!textDataSources" :card-content="recommendList" @on-click="handleWelcomeRecommend" />
      <ChatBaseCard v-show="textDataSources">
        <div class="waring-answer-wrapper">
          <dl class="message-inner warning-info_medium ">
            <dt class="mb-[2px] font-bold text-[#1A2029]">{{ textDataSources?.title }}</dt>
            <dd v-for="item, index in textDataSources?.list" :key="index"><span
                :class="{ 'text-[#F44C49]': item.isWarning }">{{ item.label }}： {{ item.value }}</span></dd>
          </dl>
          <div class="table-inner">
            <div class="warning-table mb-[8px]">
              <div class="title">
                <span>当前进水数据：</span>
              </div>
              <div class="main">
                <BaseTable :columns="columns" :data="jsTableData"></BaseTable>
              </div>
            </div>
            <div class="warning-table">
              <div class="title">
                <span>当前出水数据：</span>
              </div>
              <div class="main">
                <BaseTable :columns="columns" :data="csTableData"></BaseTable>
              </div>
            </div>
          </div>
        </div>
        <div class="echart-warpper">
          <span>{{ chartTitle }}</span>
          <div id="chartContainer" class="w-[600px] h-[200px]" ref="echartRef"></div>
          <ul class="flex justify-between w-[600px] text-center text-[12px] text-[#666] leading-[18px]">
            <li class="w-[370px] pl-[40px]">
              <span class="inline-block w-[10px] h-[2px] mb-[2px] mr-[4px] bg-[#2185da]"></span>
              <span>过去</span>
            </li>
            <li class="flex-1 pr-[30px]">
              <span class="inline-block w-[10px] h-[2px] mb-[2px] mr-[4px] bg-[#2ee055]"></span>
              <span>未来</span>
            </li>
          </ul>
        </div>

      </ChatBaseCard>

      <ChatAnswer :loading="false" :delay-loading="false" :toggleVisibleIcons="false" :content="answerResult"
        v-if="answerResult" />

    </TheChatView>
  </section>
</template>

<style lang="scss" scoped>
.echart-warpper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-flow: column;
  width: 100%;
  padding: 50px 0 30px 0;
  border-radius: 8px;
  // background: #eee;
  // border: 1px solid #ccc;
}
</style>