'use client'

import cn from '@/utils/classnames'
import ReactECharts from 'echarts-for-react'
import * as echarts from 'echarts'
import useSWR from 'swr'
import { fetchStatistic } from '@/service/common'
import { useAppContext } from '@/context/app-context'

const cardClass = 'bg-[#FCFCFC] border rounded-[10px] border-[#E6E7EB] p-6 flex'
const Statistic = () => {
  const { currentWorkspace, isCurrentWorkspaceOwner } = useAppContext()
  const { data: data1 }: any = useSWR(
    {
      url: '/datasets/count',
      params: {
        tenant_id: currentWorkspace.id,
      },
    },
    fetchStatistic,
  )
  const datasetsCount = data1?.data?.datasets_count || 0
  const deptsCount = data1?.data?.depts_count || 0
  const tagsCount = data1?.data?.tags_count || 0
  const { data: data2 }: any = useSWR(
    {
      url: '/datasets/type-stats',
      params: {
        tenant_id: currentWorkspace.id,
      },
    },
    fetchStatistic,
  )
  const typeData = data2?.data || []
  const typeOptions = {
    grid: {
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'horizontal',
      top: 0,
      itemWidth: 8,
      itemHeight: 8,
    },
    series: [
      {
        type: 'pie',
        radius: ['26%', '50%'],
        data: typeData.map((v: any) => {
          v.value = v.count || 0
          v.name = v.type
          return v
        }),
        label: {
          formatter: '{b} {d}%',
          overflow: 'break',
        },
        emphasis: {
          disabled: true,
        },
      },
    ],
  }
  const { data: data3 }: any = useSWR(
    {
      url: '/datasets/update-stats',
      params: {
        tenant_id: currentWorkspace.id,
      },
    },
    fetchStatistic,
  )
  const updateData = data3?.data || []
  const updateOptions = {
    grid: {
      top: 40,
      bottom: 20,
      left: 40,
      right: 0,
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: updateData.map((v: any) => v.period),
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: {
        fontSize: 10,
        interval: 0,
        color: 'rgba(87, 98, 117, 1)',
      },
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitNumber: 3,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(239, 241, 248, 1)',
        },
      },
      axisLabel: {
        fontSize: 10,
      },
    },
    series: [
      {
        type: 'bar',
        data: updateData.map((v: any) => v.count),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2078FC' },
            { offset: 1, color: '#5DC9F9' },
          ]),
        },
      },
    ],
  }
  const { data: data4 }: any = useSWR(
    {
      url: '/tags',
      params: {
        type: 'knowledge',
        label_map: true,
      },
    },
    fetchStatistic,
  )
  const tagData = data4 || []
  const tagColors = ['#7185fb', '#4bc97d', '#2079fe', '#dba53c', '#4ec5f9']
  const tagOptions = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        type: 'graph',
        layout: 'force',
        data: tagData.map((v: any) => ({ name: v.name, value: Number(v.binding_count) })).sort((a: any, b: any) => b.value - a.value).map((v: any, i: number) => {
          if (i < Math.floor(tagData.length / 4)) {
            v.symbolSize = 100
            v.label = {
              fontSize: 30,
            }
          }
          else if (i < Math.floor(tagData.length / 2)) {
            v.symbolSize = 90
            v.label = {
              fontSize: 24,
            }
          }
          else if (i < Math.floor(tagData.length * 3 / 4)) {
            v.symbolSize = 80
            v.label = {
              fontSize: 20,
            }
          }
          else {
            v.symbolSize = 70
            v.label = {
              fontSize: 16,
            }
          }
          v.itemStyle = {
            color: tagColors[i % tagColors.length],
          }
          return v
        }),
        links: [],
        roam: true,
        force: {
          repulsion: 110,
          edgeLength: [10, 50],
        },
        symbolSize: 60,
        label: {
          show: true,
          color: '#ffffff',
        },
        emphasis: {
          disabled: true,
        },
      },
    ],
  }
  return (
    <div className="w-full px-12">
      <div className={cn('w-full gap-6', cardClass)}>
        <div className="flex h-[120px] grow items-center bg-[url('/imgs/statistic-bg.png')] bg-[length:100%_100%] bg-no-repeat pl-6">
          <img src="/imgs/statistic-icon-1.png" className="mr-6 h-16 w-16"/>
          <div>
            <div className="text-[36px] text-[#111111]">{datasetsCount}</div>
            <div className="text-[#111111]">知识库总量</div>
          </div>
        </div>
        <div className="flex h-[120px] grow items-center bg-[url('/imgs/statistic-bg.png')] bg-[length:100%_100%] bg-no-repeat pl-6">
          <img src="/imgs/statistic-icon-2.png" className="mr-6 h-16 w-16"/>
          <div>
            <div className="text-[36px] text-[#111111]">{deptsCount}</div>
            <div className="text-[#111111]">部门总量</div>
          </div>
        </div>
        <div className="flex h-[120px] grow items-center bg-[url('/imgs/statistic-bg.png')] bg-[length:100%_100%] bg-no-repeat pl-6">
          <img src="/imgs/statistic-icon-3.png" className="mr-6 h-16 w-16"/>
          <div>
            <div className="text-[36px] text-[#111111]">{tagsCount}</div>
            <div className="text-[#111111]">标签总量</div>
          </div>
        </div>
      </div>
      <div className='mt-6 flex w-full gap-8'>
        <div className={cn(cardClass, 'h-[360px] flex-1 flex-col overflow-hidden')}>
          <div className="text-2xl font-bold text-[#333333]">知识库类别统计</div>
          <div className="relative mt-3 flex flex-1 items-center justify-center">
            <img src="/imgs/statistic-icon-4.png" className="absolute"/>
            <ReactECharts option={typeOptions} className="flex-1" />
          </div>
        </div>
        <div className={cn(cardClass, 'h-[360px] flex-1 flex-col overflow-hidden')}>
          <div className="text-2xl font-bold text-[#333333]">知识库更新情况统计</div>
          <ReactECharts option={updateOptions} className="flex-1" />
        </div>
        <div className={cn(cardClass, 'h-[360px] flex-1 flex-col overflow-hidden bg-[url("/imgs/statistic-icon-5.png")] bg-[length:100%_100%] bg-no-repeat')}>
          <div className="text-2xl font-bold text-[#333333]">标签云图</div>
          <ReactECharts option={tagOptions} className="flex-1" />
        </div>
      </div>
    </div>
  )
}

export default Statistic
