<script setup lang="jsx">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { NTabs, NTab } from 'naive-ui';
import { useChatStore } from '@/stores/modules/chatStore';
import { BaseTable, ChatWelcome, RecodeSquareCardItem, TheSubMenu, TheChatView } from "@/components";
import { ChatBaseCard, ChatAnswer } from '@/components/Chat';
import { format, truncateDecimals } from "@/utils/format";
import { waterApi } from '@/api/water';
import {useInfinite, useRecommend, useScroll} from '@/composables'

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

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

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

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

const renderRowDom = ({ row, key }) => {
  const { exceed, value } = row[key] || {};
  const cls = exceed ? 'text-[#F44C49] font-bold' : 'text-[1A2029]'
  return (<span class={cls}>{truncateDecimals(value)} {exceed && <i>↑</i>}</span>)
}

const columns = [
  {
    title: '流量(m³/h)',
    key: 'name',
    titleAlign: 'center',
    align: 'center',
    className: 'small',
    width: '80px',
    render: (row) => renderRowDom({ row, key: '流量' })
  },
  {
    title: 'COD(mg/L)',
    key: 'small',
    titleAlign: 'center',
    align: 'center',
    className: 'small',
    width: '80px',
    render: (row) => renderRowDom({ row, key: 'COD' })
  },
  {
    title: 'TN(mg/L)',
    key: 'address',
    titleAlign: 'center',
    align: 'center',
    className: 'small',
    width: '80px',
    render: (row) => renderRowDom({ row, key: 'TN' })
  },
  {
    title: 'NH3-N(mg/L)',
    key: 'tags',
    titleAlign: 'center',
    align: 'center',
    className: 'small',
    width: '80px',
    render: (row) => renderRowDom({ row, key: 'NH3-N' })
  },
  {
    title: 'TP(mg/L)',
    key: 'COD',
    titleAlign: 'center',
    align: 'center',
    className: 'small',
    width: '80px',
    render: (row) => renderRowDom({ row, key: 'TP' })
  },
  {
    title: 'SS(mg/L)',
    key: '流量',
    titleAlign: 'center',
    align: 'center',
    className: 'age',
    width: '78px',
    render: (row) => renderRowDom({ row, key: 'SS' })
  }
]

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

// 打开详情
const handleOpenContent = async ({ id, category }) => {
  const { data } = await waterApi.getWaringDetails(id);
  const showVal = JSON.parse(data.showVal);
  const { basic, jsData, csData } = showVal;
  console.log( jsData );
  const textWhiteList = [
    { label: '报警时间', realKey: '报警时间', value: '', isWarning: false },
    { label: '报警值',   realKey: '报警值', value: 'mg/L', isWarning: true },
    { label: '管控值',   realKey: '管控值', value: 'mg/L', isWarning: false },
    { label: '标准值',   realKey: '标准值', value: 'mg/L', isWarning: false },
    // { label: '报警级别', realKey: '告警级别', value: '', isWarning: false },
    { label: '报警次数', realKey: '报警次数', value: '', isWarning: false },
    { label: '状态',     realKey: '状态', value: '', isWarning: false }
  ]

  answerResult.value = data.answer;

  textDataSources.value = format.textSorting(basic, textWhiteList);

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

  scrollToTop();
}

// 欢迎 - 问答
const handleWelcomeRecommend = question => {
  chatStore.setChatQuestion(question);
  router.push('/answer');
}
</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-if="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>
      </ChatBaseCard>
      
      <ChatAnswer 
        :loading="false"
        :delay-loading="false"
        :toggleVisibleIcons="false"
        :content="answerResult"
        v-if="answerResult"
      />

    </TheChatView>

  </section>
</template>

<style scoped lang="scss"></style>
