import { Flex, Space, Input } from 'antd'
import styles from './index.less'
import PieCharts from './PieCharts'
import AnalysisItem from './AnalysisItem'
import Tabs from '@/components/Tabs';
import BaseCard from '@/pages/Common/components/BaseCard'
import EventDetail from '@/pages/Common/Event/EventDetail'
import ToggleView from '@/components/ToggleView'
import { eventList } from '@/mock/event'
import ListView from '@/pages/Common/components/ListView'
import EventPicList from '@/pages/Common/components/EventPicList'
import { useState, useEffect, useRef } from 'react'
import services from '@/services';
import Modal from '@/components/HncyModal';
import { SearchOutlined } from '@ant-design/icons';

/**
 * 
 * @description 待处置事件
 */

const ToDisposed = () => {

  // 事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<{
    open: boolean;
    title: string;
    eventId: string;
  }>({
    open: false,
    title: '',
    eventId: ''
  })

  // 视图
  const [viewType, setViewType] = useState<'list' | 'pic'>('pic'); //展示

  const fetchParams = useRef({
    page: 1,
    count: 10,
    dealOverdue: '',
    searchText: '',
    isDispose: '1',
  });

  //事件列表
  const [listData, setListData] = useState<any>({
    items: eventList,
    loading: true,
    total: 0,
    page: 1,
    hasNext: false,
  });

  const [sourceStatistics, setSourceStatistics] = useState([])
  const [areaStatistics, setAreaStatistics] = useState([])
  const [timeLimitsOptions, setTimeLimitsOptions] = useState([])
  const [total, setTotal] = useState(0)
  const [searchText, setSearchText] = useState('')

  // 获取左侧来源分布统计
  const getSourceStatistics = () => {
    const params = {
      sourceSystemCode: '',
      isDispose: 1
    }
    services.CityProblemApi.getSourceStatisticsApi(params).then(res => {
      if (res.code === 200) {
        // 排个序 为了颜色显示
        setSourceStatistics(res.data?.sort((a: any, b: any) => b.valueNum - a.valueNum))
      }
    })
  }

  // 高发类别统计
  const getAreaAnalysis = () => {
    const params = {
      region: 'district',
      top: 3,
      isDispose: 1,
    }
    services.CityProblemApi.getAreaDistribAnalysisApi(params).then(res => {
      if (res.code === 200) {
        setAreaStatistics(res.data)
      }
    })
  }
  // 获取事件列表
  const getEventsList = () => {
    services.CityProblemApi.getZzEventListApi(fetchParams.current).then((res) => {
      if (res.code === 200) {
        let result = {
          ...res.data,
          items:
            fetchParams.current.page === 1 ? res.data.items : [...listData.items, ...res.data.items],
        };
        setListData(result);
      }
    });
  }

  // 时限统计
  const getTimeLimits = () => {
    const params = {
      isDispose: 1,
    }
    services.CityProblemApi.getTimeLimitsApi(params).then((res) => {
      if (res.code === 200) {
        const result = res.data?.map((item: any) => {
          return {
            label: `${item.name} ${item.value}`,
            key: item.type
          }
        })
        setTimeLimitsOptions(result)
        fetchParams.current.dealOverdue = result[0]?.key
        getEventsList()
        const total = res.data?.reduce((prev: any, cur: any) => {
          return prev + Number(cur.value)
        }, 0)
        setTotal(total)
      }
    })
  }

  const changeListTab = (value: string) => {
    fetchParams.current.dealOverdue = value
    fetchParams.current.page = 1
    setListData({
      items: [],
      loading: true,
      total: 0,
      page: 1,
      hasNext: false,
    })
    getEventsList();
  }

  const handleSearch = () => {
    fetchParams.current.searchText = searchText
    fetchParams.current.page = 1
    setListData({
      items: [],
      loading: true,
      total: 0,
      page: 1,
      hasNext: false,
    })
    getEventsList();
  }

  useEffect(() => {
    getEventsList()
  }, [fetchParams])

  useEffect(() => {
    getSourceStatistics()
    getAreaAnalysis()
    getTimeLimits()
  }, [])


  return (
    <Flex gap={30} className={styles.wrap}>
      <Space direction='vertical' size={0} className={styles.left}>
        <BaseCard
          title='来源分布'
          style={{
            paddingTop: 20,
            borderRadius: '20px 20px 0 0'
          }}
        >
          <Flex className={styles.content} gap={10} align='center'>
            <div>
              <PieCharts
                dataSource={sourceStatistics || []}
                style={{ width: 140, height: 130 }}
                color={['#FF9B5D', '#FFE335', '#29B5FF']}
              />
            </div>
            <div>
              {
                sourceStatistics.map((source: any, index: number) => (
                  <AnalysisItem key={source.type} item={source} color={['#FF9B5D', '#FFE335', '#29B5FF'][index]} />
                ))
              }
            </div>
          </Flex>
        </BaseCard>
        <BaseCard
          title='区县分布'
          style={{
            paddingTop: 30,
            borderRadius: '0 0 20px 20px'
          }}
        >
          <Flex className={styles.content} gap={10} align='center'>
            <div>
              <PieCharts
                dataSource={areaStatistics || []}
                style={{ width: 140, height: 130 }}
                color={['#85E979', '#52F9FF', '#FFFCA1']}
              />
            </div>
            <div>
              {
                areaStatistics.map((source: any, index: number) => (
                  <AnalysisItem key={source.type} item={source} color={['#85E979', '#52F9FF', '#FFFCA1'][index]} />
                ))
              }
            </div>
          </Flex>
        </BaseCard>
      </Space>
      <div className={styles.right}>
        <Flex justify='space-between' style={{ marginBottom: 20 }}>
          <span className={styles.tips}>{total} 条事件还未处置结案</span>
          <Space size={20}>
            <Tabs
              onChange={changeListTab}
              itemkey={'key'}
              items={timeLimitsOptions}
              itemStyle={{
                fontFamily: 'initial'
              }}
            />
            <Input
              allowClear
              className={styles.searhInput}
              placeholder="输入事件名称、编号搜索事件"
              style={{ width: 310 }}
              suffix={
                <SearchOutlined
                  style={{ cursor: 'pointer' }}
                  onClick={handleSearch}
                />
              }
              onChange={(e) => {
                setSearchText(e.target.value)
              }}
              value={searchText}
            />
            <ToggleView type={viewType} setType={(type) => setViewType(type)} />
          </Space>
        </Flex>
        {viewType === 'list' ? (
          <ListView
            listData={listData}
            listHeight={540}
            setParams={(data) => {
              fetchParams.current.page = data.pageNum;
              fetchParams.current.count = data.pageSize;
              getEventsList()
            }}
            handleDetail={(details) => {
              setDetailModalOpt({ open: true, title: '事件详情', eventId: details.eventId })
            }}
          />
        ) : (
          <EventPicList
            listData={listData}
            listHeight={640}
            setParams={(page) => {
              fetchParams.current.page = page;
              getEventsList()
            }}
            handleDetail={(details) => {
              setDetailModalOpt({ open: true, title: '事件详情', eventId: details.eventId })
            }}
          />
        )}
      </div>
      <Modal
        open={detailModalOpt?.open}
        title={detailModalOpt?.title}
        onCancel={() => setDetailModalOpt({ open: false, title: '', eventId: '' })}
        width={1160}
        height={950}
      >
        <EventDetail eventId={detailModalOpt?.eventId} />
      </Modal>
    </Flex >
  )
}

export default ToDisposed