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 } 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 params = {
    page: 1,
    count: 10,
    caseStatus: '',
    searchText: '',
    isDispose: '1',
  }

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

  const [fetchParams, setFetchParams] = useState<any>(params)
  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: '',
      type: '',
      time: '',
      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',
      type: '',
      time: '',
      top: 3,
      isDispose: 1,
    }
    services.CityProblemApi.getAreaDistribAnalysisApi(params).then(res => {
      if (res.code === 200) {
        setAreaStatistics(res.data)
      }
    })
  }


  // 时限统计
  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)
        const total = res.data?.reduce((prev: any, cur: any) => {
          return prev + Number(cur.value)
        }, 0)
        setTotal(total)
      }
    })
  }

  // 获取事件列表
  const getEventsList = () => {
    services.CityProblemApi.getZzEventListApi(fetchParams).then((res) => {
      if (res.code === 200) {
        setListData({ ...res.data, items: res.data.items })
      }
    })
  }

  const changeListTab = (value: string) => {
    setFetchParams({ ...fetchParams, caseStatus: value === '0' ? '' : value }) // 为0就传空
  }

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

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


  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={() => {
                    setFetchParams({...fetchParams, searchText: searchText })
                  }}
                />
              }
              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) => {
              setFetchParams({ ...fetchParams, page: data.pageNum, count: data.pageSize })
            }}
            handleDetail={(details) => {
              setDetailModalOpt({ open: true, title: '事件详情', eventId: details.eventId })
            }}
          />
        ) : (
          <EventPicList
            listData={listData}
            listHeight={640}
            setParams={(data) => {
              setFetchParams({ ...fetchParams, page: data.page })
            }}
            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