import BlueTable from '@/components/BlueTable';
import EmptySpace from '@/components/EmptySpace';
import Tabs from '@/components/Tabs';
import services from '@/services';
import { useRequest } from 'ahooks';
import { Flex, Progress, Space } from 'antd';
import dayjs from 'dayjs';
import { memo, useEffect, useMemo, useState } from 'react';
import LineCharts from '../../components/IndLineCharts';
import TimeLineCharts from '../../components/TimeLineCharts';
import TopSarch from '../../components/TopSarch';
import { useGlobalModalServices } from '../../provider';

import Loading from '../../components/Loading';
import { csxq, jqxc, zxcq } from '../AdministPunish/NumTop5';
import styles from './index.less';

/**日常巡查modal */
const DyaPatrol = (props: any) => {
  const [areaKey, setAreaKey] = useState('all');
  const { dispatch } = useGlobalModalServices();
  const [activeKey, setActiveKey] = useState('1');
  const [searchTime, setSearchTime] = useState({
    key: 'day',
    startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
    endTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
  });
  const [classType, setClassType] = useState('0'); //大类小类

  //总数
  const { data: total } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-xzcf-sjzs',
        params: {
          ...searchTime,
        },
      }),
    {
      refreshDeps: [searchTime],
    },
  );
 

  //工作子新
  const { data: starData, loading: starLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-zdxmfztj',
        params: {
          ...searchTime,
          endTime:
            searchTime.key == 'day'
              ? dayjs().format('YYYY-MM-DD')
              : searchTime.endTime,
        },
      }),
    {
      refreshDeps: [searchTime],
    },
  );

  //处罚趋势本月本年本日
  const { data: cfqsYear, loading: yearLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-ryntj',
        params: {
          sj:
            searchTime.key === 'day'
              ? dayjs().subtract(1, 'day').format('YYYY-MM-DD')
              : dayjs().format('YYYY-MM-DD'),
          // sj: '2024-12-01',
          type: searchTime.key,
        },
      }),
    {
      refreshDeps: [searchTime],
      ready: searchTime.key !== 'section',
    },
  );
  //处罚趋势时间段
  const { data: cfqsMonth, loading: trendLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-sjcxmrsl',
        params: {
          ...searchTime,
        },
      }),
    {
      refreshDeps: [searchTime],
      ready: searchTime.key === 'section',
    },
  );
  const qsList = useMemo(() => {
   
    if (searchTime.key === 'section') {
      return cfqsMonth?.data?.data?.records?.map((item) => ({
        name: item?.time || item?.month,
        value: item?.num,
      }));
    } else {
      return cfqsYear?.data?.data?.records?.map((item) => ({
        name: item?.time || item?.month,
        value: item?.num,
      }));
    }
  }, [cfqsYear, cfqsMonth, searchTime]);

  //高发时段
  const { data: timeData, loading: higtTimeLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-xssllb',
        params: {
          ...searchTime,
        },
      }),
    {
      refreshDeps: [searchTime],
    },
  );

  //高发类型
  const { data: typeTop, loading: higtLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-lxsltj',
        params: {
          ...searchTime,
          type: classType,
        },
      }),
    {
      refreshDeps: [searchTime, classType],
    },
  );

  const typeTop5list = useMemo(() => {
    const list = typeTop?.data?.data?.records?.slice(0, 5);
    const num = total?.data?.data?.records?.[0]?.num || 1;
    return list?.map((item) => ({
      ...item,
      percent: ((item?.num / num) * 100).toFixed(2),
    }));
  }, [typeTop, total]);

  //区域top5
  const { data: areaTop, loading: areaTopLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-qyfztj',
        params: {
          ...searchTime,
        },
      }),
    {
      refreshDeps: [searchTime],
    },
  );
  //区域top5
  const areaTopList = useMemo(() => {
    const num = total?.data?.data?.records?.[0]?.num || 1;
    let list;
    if (areaKey === 'all') {
      list = areaTop?.data?.data?.records?.slice(0, 5);
    }
    if (areaKey === 'zx') {
      list = qysl?.data?.data?.records
        ?.filter((item) => zxcq.includes(item?.ssqy))
        ?.slice(0, 5);
    }
    if (areaKey === 'xc') {
      list = areaTop?.data?.data?.records
        ?.filter((item) => csxq.includes(item?.ssqy))
        ?.slice(0, 5);
    }
    if (areaKey === 'jq') {
      list = areaTop?.data?.data?.records
        ?.filter((item) => jqxc.includes(item?.ssqy))
        ?.slice(0, 5);
    }

    return list?.map((item) => ({
      ...item,
      percent: ((item?.num / num) * 100).toFixed(2),
    }));
  }, [areaTop, areaKey, total]);
  //部门top5
  const { data: qysl, loading: bmTopLoading } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-rcxc-abmfztj',
        params: {
          ...searchTime,
        },
      }),
    {
      refreshDeps: [searchTime],
    },
  );

  //部门top5
  const baList = useMemo(() => {
    const num = total?.data?.data?.records?.[0]?.num || 1;
    let list;
    if (areaKey === 'all') {
      list = qysl?.data?.data?.records?.slice(0, 5);
    }
    if (areaKey === 'zx') {
      list = qysl?.data?.data?.records
        ?.filter((item) => zxcq.includes(item?.areaname))
        ?.slice(0, 5);
    }
    if (areaKey === 'xc') {
      list = qysl?.data?.data?.records
        ?.filter((item) => csxq.includes(item?.areaname))
        ?.slice(0, 5);
    }
    if (areaKey === 'jq') {
      list = qysl?.data?.data?.records
        ?.filter((item) => jqxc.includes(item?.areaname))
        ?.slice(0, 5);
    }
    return list?.map((item) => ({
      ...item,
      percent: ((item?.num / num) * 100).toFixed(2),
    }));
  }, [qysl, areaKey, total]);

  const tp3List = useMemo(() => {
    return [
      {
        key: '1',
        name: starData?.data?.data?.records?.[0]?.sbr,
        count: starData?.data?.data?.records?.[0]?.num,
        works: starData?.data?.data?.records?.[0]?.zd,
        bg: require('@/assets/images/administPunish/starBg1.png'),
        icon: require('@/assets/images/administPunish/star2.png'),
      },
      {
        key: '2',
        name: starData?.data?.data?.records?.[1]?.sbr,
        count: starData?.data?.data?.records?.[1]?.num,
        works: starData?.data?.data?.records?.[1]?.zd,
        bg: require('@/assets/images/administPunish/starBg2.png'),
        icon: require('@/assets/images/administPunish/star1.png'),
      },
      {
        key: '3',
        name: starData?.data?.data?.records?.[2]?.sbr,
        count: starData?.data?.data?.records?.[2]?.num,
        works: starData?.data?.data?.records?.[2]?.zd,
        bg: require('@/assets/images/administPunish/starBg3.png'),
        icon: require('@/assets/images/administPunish/star3.png'),
      },
    ];
  }, [starData]);

  const top5Items = [
    {
      key: '1',
      label: '区域排行榜TOP5',
    },
    {
      key: '2',
      label: '中队排行榜TOP5',
    },
  ];

  useEffect(() => {
    props.modalDispatch.setOptions({
      headerLeft: () => {
        return (
          <TopSarch
            items={[
              {
                key: 'day',
                label: '昨日',
              },
              {
                key: 'month',
                label: '本月',
              },
              {
                key: 'year',
                label: '本年',
              },
            ]}
            defaultKey={searchTime.key}
            onChange={(e) => {
              console.log(e);
              if (e.key == 'day') {
                setSearchTime({
                  key: 'day',
                  startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
                  endTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
                });
              } else {
                setSearchTime(e);
              }
            }}
          />
        );
      },
    });
  }, []);
  return (
    <div className={styles.container}>
      <div className={styles.leftWarp}>
        <div
          className={styles.dispose}
          onClick={() => {
            dispatch.push('DyaPatrolList', {
              title: '巡查处置列表',
              props: {
                searchTime,
              },
            });
          }}
          style={{ cursor: 'pointer' }}
        >
          <div className={styles.title}>
            <div className={styles.tLeft}>
              <span>巡查处置问题总数</span>
              <span className={styles.count}>
                {total?.data?.data?.records?.[0]?.num ?? '--'}
              </span>
              <span>件</span>
            </div>
            {/* <div className={styles.tRignt}>
              <span>环比</span>
              <span>
                <CaretUpOutlined style={{ color: 'rgb(29, 187, 138)' }} />
                <CaretDownOutlined style={{ color: 'red' }} />
              </span>
              <span className={styles.count}>0.25</span>
              <span>%</span>
            </div> */}
          </div>
          <Loading loading={yearLoading || trendLoading}>
            <>
              
              {qsList?.length ? (
                <LineCharts
                  data={qsList || []}
                  style={{ width: 525, height: 80 }}
                />
              ) : (
                <EmptySpace />
              )}
            </>
          </Loading>
        </div>

        <div className={styles.scoreType}>
          <div className={styles.title}>
            <span>高发类型TOP5</span>
            <Tabs
              style={{
                background: 'transparent',
                height: '30px',
                marginTop: 10,
              }}
              itemStyle={{
                borderRadius: '25px',
                background: 'rgba(7, 50, 93, 0.8)',
                fontSize: '16px',
                marginLeft: 8,
              }}
              onChange={(e) => {
                setClassType(e);
              }}
              itemkey={'key'}
              items={[
                {
                  key: '0',
                  label: '大类',
                },
                {
                  key: '1',
                  label: '小类',
                },
              ]}
            />
          </div>
          <Loading loading={higtLoading}>
            <>
              {typeTop5list?.length ? (
                <div className={styles.content} style={{ height: 322 }}>
                  {typeTop5list?.map((item, index) => {
                    return (
                      <div
                        className={styles.litsItem}
                        key={index}
                        onClick={() => {
                          const param =
                            classType === '0'
                              ? { wtdl: item?.name }
                              : { wtxl: item?.name };
                          dispatch.push('DyaPatrolList', {
                            title: '巡查处置列表',
                            props: {
                              search: param,
                              searchTime,
                            },
                          });
                        }}
                      >
                        <Flex justify="space-between">
                          <div className={styles.name}>{item.name}</div>
                          <Space size={10} className={styles.numBox}>
                            <div className={styles.num}>
                              <span>{item?.num}</span>
                              <span>件</span>
                            </div>
                            <div className={styles.num}>
                              <span>
                                {Number(item?.percent ?? 0).toFixed(2)}
                              </span>
                              <span>%</span>
                            </div>
                          </Space>
                        </Flex>

                        <Progress
                          size={{ height: 15 }}
                          percent={item?.percent}
                          showInfo={false}
                          strokeColor={{ from: '#79FFD1', to: '#00B9FF' }}
                          status="active"
                        />
                      </div>
                    );
                  })}
                </div>
              ) : (
                <EmptySpace />
              )}
            </>
          </Loading>
        </div>

        <div className={styles.timeFrame}>
          <div className={styles.title}>高发时段分析</div>
          <Loading loading={higtTimeLoading}>
            <>
              {timeData?.data?.data?.records?.length ? (
                <TimeLineCharts
                  data={timeData?.data?.data?.records?.map((item) => ({
                    name:  item?.sj + '时' ,
                    value: item?.num,
                  }))}
                  style={{ width: 525, height: 80 }}
                />
              ) : (
                <EmptySpace />
              )}
            </>
          </Loading>
        </div>
      </div>
      <div className={styles.rightWarp}>
        <div className={styles.top3}>
          <div className={styles.title}>工作之星</div>
          <Loading loading={starLoading}>
            <>
              {starData?.data?.data?.records?.length ? (
                <div className={styles.content}>
                  {tp3List?.map((item, index) => {
                    return (
                      <div
                        key={index}
                        className={styles.starItem}
                        style={{
                          backgroundImage: `url(${item.bg})`,
                          backgroundSize: '100% 100%',
                          cursor: 'pointer',
                        }}
                        onClick={() => {
                          dispatch.push('DyaPatrolList', {
                            title: '巡查处置列表',
                            props: {
                              sbr: item.name,
                              searchTime,
                            },
                          });
                        }}
                      >
                        <img src={item.icon} alt="" className={styles.img} />
                        <div className={styles.info}>
                          <span className={styles.name}>{item.name}</span>
                          <span className={styles.count}>{item.count}</span>
                          {item.count && (
                            <span className={styles.unit}>件</span>
                          )}
                        </div>
                        <div className={styles.works}>{item.works}</div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <EmptySpace />
              )}
            </>
          </Loading>
        </div>
        <div className={styles.areaTop5}>
          <div className={styles.tabs}>
            {top5Items?.map((item) => {
              return (
                <div
                  key={item.key}
                  onClick={() => {
                    setActiveKey(item.key);
                  }}
                  style={{
                    marginRight: 10,
                    color:
                      activeKey === item.key
                        ? 'rgb(255, 255, 255)'
                        : 'rgb(119, 168, 194)',
                  }}
                >
                  {item.label}
                </div>
              );
            })}
          </div>
          <Tabs
            style={{
              background: 'transparent',
              height: '30px',
              marginTop: 10,
            }}
            itemStyle={{
              borderRadius: '25px',
              background: 'rgba(7, 50, 93, 0.8)',
              fontSize: '16px',
              marginLeft: 8,
            }}
            onChange={(e) => {
              setAreaKey(e);
            }}
            itemkey={'key'}
            items={[
              {
                key: 'all',
                label: '全部',
              },

              {
                key: 'xc',
                label: '城市新区',
              },
              {
                key: 'zx',
                label: '中心城区',
              },
              {
                key: 'jq',
                label: '县市新城',
              },
            ]}
          />
          {activeKey === '1' ? (
            <div className={styles.tableWrap}>
              <Loading loading={areaTopLoading}>
                <BlueTable
                  onRow={(record, index) => {
                    return {
                      onClick: (event) => {
                        dispatch.push('DyaPatrolList', {
                          title: '巡查处置列表',
                          props: {
                            ssqy: record?.ssqy,
                            searchTime,
                          },
                        });
                      }, // 点击行时触发
                    };
                  }}
                  scroll={{ y: 350 }}
                  dataSource={areaTopList || []}
                  columns={[
                    {
                      title: '排名',
                      dataIndex: 'wh',
                      key: 'descgldw',
                      width: 100,
                      ellipsis: true,
                      render: (_: any, rows: any, index: number) => {
                        return (
                          <div className={styles.rankIng}>TOP{index + 1}</div>
                        );
                      },
                    },
                    {
                      title: '区域',
                      dataIndex: 'ssqy',
                      key: 'ssqy',
                      width: 150,
                      ellipsis: true,
                    },
                    {
                      title: '占比',
                      dataIndex: 'percent',
                      key: 'percent',
                      width: 90,
                      ellipsis: true,
                      render: (val: string) => {
                        return <div className={styles.proportion}>{val}%</div>;
                      },
                    },
                    {
                      title: '巡查处置问题数',
                      dataIndex: 'num',
                      key: 'num',
                      width: 200,
                      ellipsis: true,
                      render: (val) => {
                        return (
                          <div style={{ fontSize: 20, fontWeight: 700 }}>
                            {val}
                            <span className={styles.tableUnit}>件</span>
                          </div>
                        );
                      },
                    },
                  ]}
                  pagination={false}
                />
              </Loading>
            </div>
          ) : (
            <div className={styles.tableWrap}>
              <Loading loading={bmTopLoading}>
                <BlueTable
                  scroll={{ y: 350 }}
                  dataSource={baList || []}
                  onRow={(record, index) => {
                    return {
                      onClick: (event) => {
                        dispatch.push('DyaPatrolList', {
                          title: '巡查处置列表',
                          props: {
                            bm: record?.bm,
                            searchTime,
                          },
                        });
                      }, // 点击行时触发
                    };
                  }}
                  columns={[
                    {
                      title: '排名',
                      dataIndex: 'wh',
                      key: 'descgldw',
                      width: 100,
                      ellipsis: true,
                      render: (_: any, rows: any, index: number) => {
                        return (
                          <div className={styles.rankIng}>TOP{index + 1}</div>
                        );
                      },
                    },
                    {
                      title: '上报部门',
                      dataIndex: 'bm',
                      key: 'bm',
                      width: 150,
                      ellipsis: true,
                    },
                    {
                      title: '所属区域',
                      dataIndex: 'areaname',
                      key: 'areaname',
                      width: 150,
                      ellipsis: true,
                    },
                    {
                      title: '占比',
                      dataIndex: 'percent',
                      key: 'percent',
                      width: 90,
                      ellipsis: true,
                      render: (val) => {
                        return <div className={styles.proportion}>{val}%</div>;
                      },
                    },
                    {
                      title: '巡查处置问题数',
                      dataIndex: 'num',
                      key: 'num',
                      width: 100,
                      ellipsis: true,
                      render: (num: string) => {
                        return (
                          <div style={{ fontSize: 20, fontWeight: 700 }}>
                            {num}
                            <span className={styles.tableUnit}>件</span>
                          </div>
                        );
                      },
                    },
                  ]}
                  pagination={false}
                />
              </Loading>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
export default memo(DyaPatrol);
