import { Flex, Space } from 'antd';
import styles from './index.less';

import Modal from '@/components/HncyModal';
import Tabs from '@/components/Tabs';
import BaseCard from '@/pages/Common/components/BaseCard';
import ProcessCard from '@/pages/Common/components/ProcessCard';
import BaseInfo from '@/pages/SecurityServiceOverview/components/BaseInfo';
import EventPicList from '@/pages/SecurityServiceOverview/components/EventPicList';
import { colorConfig } from '@/pages/SecurityServiceOverview/SecurityState/RightLayout/RiskNotice';
import services from '@/services';
import { history } from '@umijs/max';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { useMemo, useRef, useState } from 'react';
import LineCharts from './LineCharts';
interface RiskEventsProps {
  statisticsData: any;
  defaultCategory: string;
}
const map = {
  一般风险: 1,
  黄色风险: 2,
  橙色风险: 4,
  红色风险: 3,
};
const RiskEvents = (props: RiskEventsProps) => {
  const { statisticsData, defaultCategory } = props;
  console.log(statisticsData);

  const ref = useRef();
  // 事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<{
    open: boolean;
    title: string;
    eventId: string;
  }>({
    open: false,
    title: '',
    eventId: '',
  });
  const params = {
    pageNo: 0,
    pageSize: 10,
    risklevelid: map[defaultCategory],
  };

  const [listData, setListData] = useState<any>({
    items: [],
    loading: true,
    total: 0,
    page: 1,
    hasNext: false,
  });
  const [fetchParams, setFetchParams] = useState<any>(params);
  const { data } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-aq-yjxx',
        data: {
          ...fetchParams,
        },
      }),
    {
      refreshDeps: [fetchParams],
      onSuccess: (res) => {
        console.log(res?.data?.data);
        const data = res?.data?.data;
        const list = [
          ...listData?.items,
          ...data?.records?.map((item: any) => ({
            ...item,
            standardEventTitle: item?.riskdescription,
            caseStatusText: item?.status,
            reportTime: item?.risktime,
            collectionModeName: item?.sourceType,
            position: item?.region_name + item?.name,
          })),
        ];

        setListData({
          hasNext: list?.length < data?.page?.total,
          items: list,
        });
      },
    },
  );
  const categoryTab = useMemo(() => {
    return [
      {
        key: 'all',
        label: `全部风险 ${statisticsData?.count?.[0]?.num ?? '--'} 个`,
      },
      {
        key: '红色风险',
        label: `红色风险 ${
          statisticsData?.stat?.find((item) => item?.risklevel === '红色预警')
            ?.num || '--'
        } 个`,
      },
      {
        key: '橙色风险',
        label: `橙色风险 ${
          statisticsData?.stat?.find((item) => item?.risklevel === '橙色预警')
            ?.num || '--'
        } 个`,
      },
      {
        key: '黄色风险',
        label: `黄色风险 ${
          statisticsData?.stat?.find((item) => item?.risklevel === '黄色预警')
            ?.num || '--'
        } 个`,
      },
      {
        key: '一般风险',
        label: `一般风险 ${
          statisticsData?.stat?.find((item) => item?.risklevel === '一般预警')
            ?.num || '--'
        } 个`,
      },
    ];
  }, [statisticsData]);
  //风险趋势
  const { data: fxqsData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-aq-yjdjqs',
      params: {
        startTime: dayjs().format('YYYY-MM-DD'),
        endTime:  dayjs().subtract(30,'d').format('YYYY-MM-DD'),
      },
    }),
  );
  //行业风险数
  const { data: hyfxData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-aq-yjhytj',
    }),
  );
  //高发区域
  const { data: gfqyData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-aq-yjqxtj',
    }),
  );

  const onChangeCategory = (e) => {
    console.log(e);

    setListData({
      items: [],
      loading: true,
      total: 0,
      page: 1,
      hasNext: false,
    });
    ref?.current?.resPage();
    setFetchParams({
      ...fetchParams,
      pageNo: 0,
      risklevelid: e !== 'all' ? map[e] : undefined,
    });
  };

  /** 标题渲染 */
  const titleRender = () => {
    return (
      <Flex align="center" className={styles.modalTitle}>
        <div className={styles.title}>{detailModalOpt?.riskdescription}</div>
        <img
          src={colorConfig[detailModalOpt?.riskLevelName!]?.tag}
          alt=""
          style={{ width: 136, height: 30, marginLeft: 36, marginRight: 13 }}
        />

        <span className={styles.type}>
          {detailModalOpt?.industry_name_dl}-{detailModalOpt?.name}
        </span>
      </Flex>
    );
  };
  return (
    <Flex gap={30} className={styles.wrap}>
      <div
        className={styles.more}
        onClick={() => {
          history.push('/securityServiceOverview');
        }}
      >
        进入“安全一张图”查看更多
      </div>

      <Space direction="vertical" size={25} className={styles.left}>
        <BaseCard
          title="风险预警趋势(近30天)"
          style={{
            height: 304,
            paddingTop: 20,
          }}
        >
          <div style={{ padding: '15px' }}>
            <LineCharts
              data={
                fxqsData?.data?.data?.records?.[0]?.red?.map((item) => ({
                  name: item?.sj,
                  value: item?.num,
                })) || []
              }
              orangeData={
                fxqsData?.data?.data?.records?.[0]?.orange?.map((item) => ({
                  name: item?.sj,
                  value: item?.num,
                })) || []
              }
              yellowData={
                fxqsData?.data?.data?.records?.[0]?.yellow?.map((item) => ({
                  name: item?.sj,
                  value: item?.num,
                })) || []
              }
            />
          </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={(e) => {
          //       getTypeData({ type: e });
          //     }}
          //     itemkey={'key'}
          //     items={[
          //       {
          //         key: '0',
          //         label: '大类',
          //       },
          //       {
          //         key: '1',
          //         label: '小类',
          //       },
          //       {
          //         key: '2',
          //         label: '细类',
          //       },
          //     ]}
          //   />
          // }
          data={
            hyfxData?.data?.data?.records?.[0]?.stat?.map((item) => {
              return {
                ...item,
                percent: (
                  (Number(item?.num) /
                    Number(
                      hyfxData?.data?.data?.records?.[0]?.count?.[0]?.num,
                    )) *
                  100
                )?.toFixed(2),
                name: item?.industryNameDl,
                value: item?.num,
              };
            }) || []
          }
          strokeColor={{
            '0%': '#38F2E3',
            '100%': '#3DC3FF',
          }}
        />

        <ProcessCard
          title="高发区域"
          data={
            gfqyData?.data?.data?.records?.[0]?.stat?.map((item) => ({
              ...item,
              name: item?.regionName,
              percent: (
                (Number(item?.num) /
                  Number(gfqyData?.data?.data?.records?.[0]?.count)) *
                100
              )?.toFixed(2),
              value: item?.num,
            })) || []
          }
          strokeColor={{
            '0%': '#FFCCCC',
            '100%': '#EEFFEB',
          }}
        />
      </Space>
      <div className={styles.right}>
        <div style={{ marginBottom: 20 }}>
          <Tabs
            style={{
              background: 'transparent',
              height: '50px',
            }}
            itemStyle={{
              borderRadius: '25px',
              background: 'rgba(7, 50, 93, 0.8)',
              fontSize: '20px',
              marginLeft: 8,
            }}
            onChange={onChangeCategory}
            itemkey={'key'}
            defaultValue={defaultCategory}
            items={categoryTab}
          />
        </div>
        <EventPicList
          ref={ref}
          listData={listData}
          listHeight={630}
          setParams={(data) => {
            console.log(data);

            setFetchParams({ ...fetchParams, pageNo: data.current.page });
          }}
          handleDetail={(details) => {
            setDetailModalOpt({
              open: true,
              eventId: details?.asriskId,
              ...details,
            });
          }}
        />
        {/* 事件详情 */}
        <Modal
          open={detailModalOpt?.open}
          titleRender={titleRender}
          onCancel={() => {
            setDetailModalOpt({
              open: false,
              title: '事件详情',
              eventId: '',
            });
          }}
          width={2650}
          height={900}
        >
          {detailModalOpt?.open && (
            <BaseInfo
              eventId={detailModalOpt?.eventId}
              detail={detailModalOpt}
              onChangeOpt={(val) => {
                console.log(val);
                setDetailModalOpt({
                  ...detailModalOpt,
                  position: val?.region_name,
                  riskLevelName: val?.risklevel,
                });
              }}
            />
          )}
        </Modal>
      </div>
    </Flex>
  );
};

export default RiskEvents;
