import { Flex, Space, useMemo } from 'antd'
import styles from './index.less'
import ListTabs from '@/pages/Common/components/ListTabs'
import ProcessCard from '@/pages/Common/components/ProcessCard'
import BaseCard from '@/pages/Common/components/BaseCard'
import ListView from '@/pages/Common/components/ListView'
import EventPicList from '@/pages/Common/components/EventPicList'
import EventDetail from '@/pages/Common/Event/EventDetail'
import ToggleView from '@/components/ToggleView'
import LineCharts from './LineCharts'
import Tabs from '@/components/Tabs';
import { useEffect, useState } from 'react'
import { eventList } from '@/mock/event'
import services from '@/services'
import Modal from '@/components/HncyModal';

interface CommonListProps {
  type: string,
  extra?: any
}

const CommonList = (props: CommonListProps) => {

  const { type, extra } = props

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

  // tabs内容
  const defalutTabItems = [
    {
      key: '1',
      label: '全部'
    },
    {
      key: '2',
      label: '处置中'
    },
    {
      key: '3',
      label: '已办结'
    }
  ]

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

  const params = {
    page: 1,
    count: 10,
    caseStatus: '',
    eventType: '',
    isDispose: '1',
  }

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

  const [fetchParams, setFetchParams] = useState<any>(params)

  const [eventStatistics, setEventStatistics] = useState<any>({})
  const [categoryStatistics, setCategoryStatistics] = useState([])
  const [areaStatistics, setAreaStatistics] = useState([])
  const [importEventStatistics, setImportEventStatistics] = useState([])


  // 获取左侧顶部事件相关统计
  const getCityStatistics = () => {
    const params = {
      eventType: '',
      type: '',
      time: '',
      singleType: ""
    }
    if(type !== '3') {
      params.singleType = type
    }
    services.CityProblemApi.getContentStatisticsApi(params).then(res => {
      if (res.code === 200) {
        setEventStatistics(res.data)
      }
    })
  }

  // 高发类别统计
  const getCategoryAnalysis = (category = 'mainClass') => {
    const params = {
      category: category,
      type: '',
      time: '',
      top: 3,
      singleType: ""
    }
    if(type !== '3') {
      params.singleType = type
    }
    services.CityProblemApi.getCategoryTopAnalysisApi(params).then(res => {
      if (res.code === 200) {
        setCategoryStatistics(res.data)
      }
    })
  }

  const onChangeCategory = (value:string) => {
    console.log('onChangeCategory', value)
    getCategoryAnalysis(value)
  }

  // 高发类别统计
  const getAreaAnalysis = () => {
    const params = {
      region: 'district',
      type: '',
      time: '',
      top: 3,
      singleType: ""
    }
    if(type !== '3') {
      params.singleType = type
    }
    services.CityProblemApi.getAreaDistribAnalysisApi(params).then(res => {
      if (res.code === 200) {
        setAreaStatistics(res.data)
      }
    })
  }

  // 事件列表
  const getEventsList = (caseStatus = '', isDispose = '', eventType = '', isOther = '', collectionModel = '') => {
    const params = {
      page: 1,
      count: 10,
      singleType: "",
      caseStatus: caseStatus,
      isDispose: isDispose,
      eventType: eventType,
      isOther: isOther,
      collectionModel
    }
    if(type !== '3') {
      params.singleType = type
    }
    if(extra?.eventType) {
      params.eventType = extra.eventType
    }
    if(extra?.isOther) {
      params.isOther = extra.isOther
    }
    if(extra?.collectionModel) {
      params.collectionModel = extra.collectionModel
    }
    services.CityProblemApi.getZzEventListApi(params).then((res) => {
      if (res.code === 200) {
        setListData({ ...res.data, items: res.data.items })
      }
    })
  }

  // 事件统计
  const getImportEventStatistics = () => {
    const params = {
      singleType: type
    }
    services.CityProblemApi.getImportEventStatisticsApi(params).then(res => {
      if (res.code === 200) {
        const result = res.data.map(item => {
          return {
            label: `${item.case_status_name} ${item.total}`,
            key: item.case_status
          }
        })
        setImportEventStatistics(result)
        if(type === '3') {
          getEventsList()
        } else {
          getEventsList(result[0]?.key)
        }
      }
    })
  }

  const changeListTab = (value: string) => {
    console.log(value)
    getEventsList(value)
  }

  const changeTab = (value: string) => {
    if(value === '1') {
      getEventsList()
    } else if(value === '2') {
      getEventsList('90')
    }else if(value === '3') {
      getEventsList('', '1')
    }
  }

  useEffect(() => {
    getCityStatistics()
    getCategoryAnalysis()
    getAreaAnalysis()
    getImportEventStatistics()
  },[])

  return (
    <Flex gap={30} className={styles.wrap}>
      <Space direction='vertical' size={15} className={styles.left}>

        <BaseCard
          style={{
            paddingTop: 15
          }}
        >
          <Flex justify='space-between' className={styles.top}>
            <Space direction='vertical' >
              <span>
                <span className={styles.num}>{eventStatistics.disposalNum}</span>
                <span>件</span>
              </span>
              <span>处置中</span>
            </Space>
            <Space direction='vertical' >
              <span>
                <span className={styles.num}>{eventStatistics.caseClosedNum}</span>
                <span>件</span>
              </span>
              <span>已办结</span>
            </Space>
            <Space direction='vertical' >
              <span>
                <span className={styles.num}>{eventStatistics.ratio}</span>
                <span>%</span>
              </span>
              <span>办结率</span>
            </Space>
          </Flex>
        </BaseCard>

        <BaseCard
          title='趋势（近30天）'
          style={{
            paddingTop: 20
          }}
        >
          <div style={{ padding: '15px', width: '100%', height: '100%' }}>
            <LineCharts data={eventStatistics.lately} />
          </div>
        </BaseCard>

        <ProcessCard
          title='高发类别'
          extra={
            <Tabs
              style={{
                background: 'transparent',
                height: '30px'
              }}
              itemStyle={{
                borderRadius: '25px',
                background: 'rgba(7, 50, 93, 0.8)',
                fontSize: '16px',
                marginLeft: 8
              }}
              onChange={onChangeCategory}
              itemkey={'key'}
              items={[ 
                {
                  key: 'mainClass',
                  label: '大类'
                },
                {
                  key: 'subClass',
                  label: '小类'
                },
                {
                  key: 'subdivisionClass',
                  label: '细类'
                }
              ]}
            />
          }
          data={categoryStatistics}
          strokeColor={{
            '0%': '#38F2E3',
            '100%': '#3DC3FF',
          }}
        />

        <ProcessCard
          title='高发区域'
          data={areaStatistics}
          strokeColor={{
            '0%': '#FFCCCC',
            '100%': '#EEFFEB',
          }}
        />
      </Space>
      <div className={styles.right}>
        <Flex justify='flex-end' style={{ marginBottom: 20 }}>
          <Space size={20}>
            {
              type === '3' ? <Tabs onChange={changeTab} itemkey={'key'} items={defalutTabItems} /> :
              <Tabs onChange={changeListTab} itemkey={'key'} items={importEventStatistics} />
            }
            
            <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 CommonList;