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

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

const ToDisposed = ({
  modalDispatch,
}: {
  modalDispatch: ChildrenModalMethods;
}) => {
  // 视图
  // const [viewType, setViewType] = useState<'list' | 'pic'>('pic'); //展示
  const viewType = useRef<'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) {
          if (viewType.current === 'list') {
            setListData(res.data);
          } else {
            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="高发区域Top3"
          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.current}
              setType={(type) => {
                viewType.current = type;
                fetchParams.current.page = 1;
                setListData({
                  items: [],
                  loading: true,
                  total: 0,
                  page: 1,
                  hasNext: false,
                });
                getEventsList();
              }}
            />
          </Space>
        </Flex>
        {viewType.current === 'list' ? (
          <ListView
            listData={listData}
            listHeight={540}
            setParams={(data) => {
              fetchParams.current.page = data.pageNum;
              fetchParams.current.count = data.pageSize;
              getEventsList();
            }}
            handleDetail={(details) => {
              modalDispatch.push(
                'EventDetail',
                {
                  w: 'fit-content',
                  props: {
                    eventId: details.eventId,
                  },
                },
                1,
              );
            }}
          />
        ) : (
          <EventPicList
            listData={listData}
            listHeight={640}
            setParams={(page) => {
              fetchParams.current.page = page;
              getEventsList();
            }}
            handleDetail={(details) => {
              modalDispatch.push(
                'EventDetail',
                {
                  w: 'fit-content',
                  props: {
                    eventId: details.eventId,
                  },
                },
                1,
              );
            }}
          />
        )}
      </div>
    </Flex>
  );
};

export default ToDisposed;
