import Tabs from '@/components/Tabs';
import ToggleView from '@/components/ToggleView';
import BaseCard from '@/pages/Common/components/BaseCard';
import EventPicList from '@/pages/Common/components/EventPicList';
import ListView from '@/pages/Common/components/ListView';
import ProcessCard from '@/pages/Common/components/ProcessCard';
import services from '@/services';
import { convertUnits } from '@/utils/ui';
import { CaretDownOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Flex, Select, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { GlobalModalServicesModalMethods } from '../../type';
import styles from './index.less';
import LineCharts from './LineCharts';

const UrbanOperation = ({
  modalDispatch,
  sourceSystemCode,
  datetType,
  lineData,
  time,
  showSourceSelect,
  sourceType,
}: {
  modalDispatch: GlobalModalServicesModalMethods;
  sourceSystemCode: string;
  datetType: string;
  lineData: any[];
  time: string;
  showSourceSelect: boolean;
  sourceType: string;
}) => {
  // 视图
  // const [viewType, setViewType] = useState<'list' | 'pic'>('pic'); //展示
  const viewType = useRef<'list' | 'pic'>('pic');

  const fetchParams = useRef({
    page: 1,
    count: 10,

    sourceSystemCode,
    type: datetType,
    time,
  });

  // tabs内容
  const defalutTabItems = [
    {
      key: '',
      label: '全部',
    },
    {
      key: '40,50,60',
      label: '处置中',
    },
    {
      key: '90',
      label: '已办结',
    },
  ];

  //事件列表
  const [listData, setListData] = useState<any>({
    items: [],
    loading: true,
    total: 0,
    page: 1,
    hasNext: false,
  });
  const [caseSourceOptions, setCaseSourceOptions] = useState<any>([]);
  const [eventStatistics, setEventStatistics] = useState<any>({});
  const [categoryStatistics, setCategoryStatistics] = useState([]);
  const [areaStatistics, setAreaStatistics] = useState([]);

  // 获取左侧顶部事件相关统计
  const getCityStatistics = () => {
    const params = {
      sourceSystemCodeY: fetchParams.current.sourceSystemCodeY,
      sourceSystemCode: fetchParams.current.sourceSystemCode,
      type: datetType,
      time,
    };
    services.CityProblemApi.getSourceSystemCloseRate(params).then((res) => {
      if (res.code === 200) {
        console.log(res);

        setEventStatistics(res.data);
      }
    });
  };

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

  const onChangeCategory = (value: string) => {
    getCategoryAnalysis(value);
  };

  // 高发类别统计
  const getAreaAnalysis = () => {
    const params = {
      region: 'district',
      top: 3,
      sourceSystemCodeY: fetchParams.current.sourceSystemCodeY,
      sourceSystemCode: fetchParams.current.sourceSystemCode,
      type: datetType,
      time,
    };
    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 { data: lineDataV1, run: getLineData } = useRequest(() =>
    services.CityProblemApi.getSourceSystemTrend({
      sourceSystemCodeY: fetchParams.current.sourceSystemCodeY,
      sourceSystemCode: fetchParams.current.sourceSystemCode,
      type: datetType,
      time,
    }),
  );
  const changeListTab = (value: string) => {
    fetchParams.current.caseStatus = value;
    fetchParams.current.page = 1;
    setListData({
      items: [],
      loading: true,
      total: 0,
      page: 1,
      hasNext: false,
    });
    getEventsList();
  };

  useRequest(services.CityProblemApi.getSourceSystemList, {
    onSuccess: (res: any) => {
      const data = res.data;
      if (res.code !== 200) {
        return;
      }
      if (sourceType && sourceType === 'all') {
        console.log(data);
        const options = data?.all?.map((item) => ({
          ...item,
          label: item?.name,
        }));
        setCaseSourceOptions([{ label: '全部来源', value: 'all' }, ...options]);
        
      }
      if (sourceType && sourceType === 'wnywxt') {
        console.log(data);
        
        const options = data?.wnywxt?.map((item) => ({
          ...item,
          label: item?.name,
        }));
        setCaseSourceOptions([{ label: '全部来源', value: 'all' }, ...options]);
      }
    },
  });

  const onChangeCaseSource = (value: string) => {
    console.log(value);

    // setSourceSystemCode(value);
    if (sourceType === 'all') {
      fetchParams.current.sourceSystemCode = value == 'all' ? undefined : value;
    } else {
      fetchParams.current.sourceSystemCodeY =
        value == 'all' ? undefined : value;
    }

    fetchParams.current.caseStatus = '';
    fetchParams.current.eventType = '';
    fetchParams.current.page = 1;
    setListData({
      items: [],
      loading: true,
      total: 0,
      page: 1,
      hasNext: false,
    });
    getCityStatistics();
    getCategoryAnalysis();
    getAreaAnalysis();
    getEventsList();
    getLineData();
  };
  useEffect(() => {
    getCityStatistics();
    getCategoryAnalysis();
    getAreaAnalysis();
    getEventsList();
  }, []);
  useEffect(() => {
    if (showSourceSelect) {
      modalDispatch.setOptions({
        headerLeft: () => {
          return (
            <div className={styles.searchBox}>
              <Select
                options={caseSourceOptions}
                style={{ width: '150px' }}
                placeholder="全部来源"
                suffixIcon={
                  <CaretDownOutlined style={{ fontSize: 20, color: '#fff' }} />
                }
                onChange={onChangeCaseSource}
              />
            </div>
          );
        },
      });
    }
  }, [showSourceSelect, caseSourceOptions]);
  return (
    <Flex gap={30} className={styles.wrap}>
      {/* {showSourceSelect && (
        <div className={styles.searchBox}>
          <Select
            options={caseSourceOptions}
            style={{ width: '150px' }}
            placeholder="全部来源"
            suffixIcon={
              <CaretDownOutlined style={{ fontSize: 20, color: '#fff' }} />
            }
            onChange={onChangeCaseSource}
          />
        </div>
      )} */}
      <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}>
                  {convertUnits(eventStatistics?.total?.value)?.num}
                </span>
                <span>{convertUnits(eventStatistics?.total?.value)?.unit}</span>
              </span>
              <span>总量</span>
            </Space>
            <Space direction="vertical">
              <span>
                <span className={styles.num}>
                  {convertUnits(eventStatistics?.accept?.value)?.num}
                </span>
                <span>
                  {convertUnits(eventStatistics?.accept?.value)?.unit}
                </span>
              </span>
              <span>立案</span>
            </Space>
            <Space direction="vertical">
              <span>
                <span className={styles.num}>
                  {eventStatistics?.rate?.value ?? '--'}
                </span>
                <span>%</span>
              </span>
              <span>处置率</span>
            </Space>
          </Flex>
        </BaseCard>

        <BaseCard
          title="趋势"
          style={{
            paddingTop: 20,
          }}
        >
          <div style={{ padding: '15px', width: '100%', height: '100%' }}>
            {/* <LineCharts data={eventStatistics.lately} /> */}
            <LineCharts
              data={
                lineDataV1?.data?.map((item) => ({
                  ...item,
                  name: item.time,
                })) || []
              }
            ></LineCharts>
          </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}>
            <Tabs
              onChange={changeListTab}
              itemkey={'key'}
              items={defalutTabItems}
            />
            <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 UrbanOperation;
