import { CSSProperties, Fragment, useEffect, useRef, useState } from 'react';
// import { CustomOverlay, Polygon } from 'react-bmapgl';
import blueBg from '@/assets/images/SecurityServiceOverview/right/blueBg.png';
import orangeBg from '@/assets/images/SecurityServiceOverview/right/orangeBg.png';
import redBg from '@/assets/images/SecurityServiceOverview/right/redBg.png';
import yellowBg from '@/assets/images/SecurityServiceOverview/right/yellowBg.png';
import risk1 from '@/assets/images/urbanSituation/risk1.svg';
import risk2 from '@/assets/images/urbanSituation/risk2.svg';
import risk3 from '@/assets/images/urbanSituation/risk3.svg';
import risk4 from '@/assets/images/urbanSituation/risk4.svg';
import CooglMap from '@/components/CooglMap';
import Modal from '@/components/HncyModal';
import { qlZwUrl } from '@/constants';
import services from '@/services';
import { useModel, useRequest } from '@umijs/max';
import { useInterval } from 'ahooks';
import { Descriptions, Flex, Spin } from 'antd';
import classNames from 'classnames';
import BaseInfo from '../components/BaseInfo';
import CheckboxGroup from './CheckboxGroup';
import styles from './index.less';
import PopoverCardKnotty from './PopoverCardKnotty';
export const colorConfig: Record<
  string,
  {
    color: CSSProperties['color'];
    bg: string;
    icon: string;
    tag?: string;
  }
> = {
  红色预警: {
    //红色风险
    color: 'rgb(255, 227, 227)',
    bg: redBg,
    icon: risk1,
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag1.png'),
  },
  橙色预警: {
    //橙色风险
    color: 'rgb(255, 249, 246)',
    bg: orangeBg,
    icon: risk2,
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag2.png'),
  },
  黄色预警: {
    //黄色风险
    color: 'rgb(255, 250, 233)',
    bg: yellowBg,
    icon: risk3,
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag3.png'),
  },
  一般预警: {
    //一般风险
    color: 'rgb(220, 241, 255)',
    bg: blueBg,
    icon: risk4,
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag4.png'),
  },
};
const SafetyMap = () => {
  const MapRef = useRef<any>();
  const [count, setCount] = useState(0);
  const { selectAreaId, industryModalData, setIndustryModalData } =
    useModel('safetyAreaId');

  useInterval(() => {
    if (count < 11) {
      setCount(count + 1);
    }
  }, 1000);
  const [searchParams, setSearchParams] = useState({
    parentTypeCode: undefined,
    lat: 30.680193,
    lon: 104.075555,
    distance: 1000,
    page: 1,
    count: 100,
  });
  // 事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<any>({
    open: false,
    title: '',
    eventId: '',
  });

  //预警点位
  const { data: earlyData } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-aq-yjxx',
        params: {
          regionCode: selectAreaId,
          pageNo: 1,
          pageSize: 50,
        },
      }),
    {
      refreshDeps: [selectAreaId],
    },
  );
  //设施点位
  const { data: facility } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-aq-qlmxlb',
        params: {
          regionCode: selectAreaId,
          pageNo: 1,
          pageSize: 50,
        },
      }),
    {
      refreshDeps: [selectAreaId],
    },
  );

  //行业点位详情
  const { data, loading: dqLoading } = useRequest(
    () =>
      services.CityRiskApi.safetyMonitoringObjectInfo({
        id: industryModalData?.id,
      }),
    {
      ready: !!industryModalData?.open && !!industryModalData?.id,
      refreshDeps: [industryModalData],
    },
  );

  //桥梁设施点位检测详情
  const { data: qlJcDet } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-aq-qljcxx',
        data: {
          id: industryModalData?.id,
          pageNo: 1,
          pageSize: 10,
        },
      }),
    {
      ready: !!industryModalData?.open && !!industryModalData?.id,
      refreshDeps: [industryModalData],
    },
  );

  //桥梁设施点位详情
  const { data: qlDet } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-aq-qlxx',
        params: {
          id: industryModalData?.id,
        },
      }),
    {
      ready: !!industryModalData?.open && !!industryModalData?.id,
      refreshDeps: [industryModalData],
    },
  );
  useEffect(() => {
    if (MapRef?.current) {
      MapRef.current.scene.globe.depthTestAgainstTerrain = false;
      MapRef.current.graphics.clustering.enabled = true;
    }
  });
  useEffect(() => {
    if (industryModalData?.open) {
      MapRef?.current?.flyTo({
        destination: {
          x: Number(industryModalData?.longitude),
          y: Number(industryModalData?.latitude),

          z: 239,
        },

        // orientation: {
        //   heading: 6.283185307179586,
        //   pitch: -1.568627330287271,
        //   roll: 0,
        // },
      });
    }
  }, [industryModalData]);
  /** 标题渲染 */
  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>
    );
  };
  const getMap = (data: string) => {
    try {
      return JSON.parse(data);
    } catch (error) {
      console.log(error);

      return {};
    }
  };

  return (
    <div className={styles.container}>
      <div style={{ width: '100%', height: '100%' }}>
        <CooglMap.MapView
          zoom={9}
          ref={MapRef}
          center={{ x: 103.95, y: 30.7 }}
          showCustomComponent={true}
        >
          <Fragment>
            {facility?.data?.records?.map((item: any, index: number) => {
              const point = [Number(item?.longitude), Number(item?.latitude)];

              return (
                <CooglMap.Marker
                  key={index}
                  onClick={() => {
                    try {
                      console.log(item);

                      setIndustryModalData({
                        open: true,
                        title: item?.parentData?.typeName,
                        parentCode: item?.parentTypeCode,
                        typeCode: item?.parentTypeCode,
                        ...item,
                      });
                    } catch (error) {
                      console.log(error);
                    }
                  }}
                  position={point}
                  icon={require('@/assets/images/SecurityServiceOverview/mapGroup/icon1.png')}
                ></CooglMap.Marker>
              );
              // return (
              //   <CooglMap.CustomOverlay
              //     key={index}
              //     position={point}
              //     onSet1={() => {
              //       try {
              //         console.log(item);

              //         setIndustryModalData({
              //           open: true,
              //           title: item?.parentData?.typeName,
              //           parentCode: item?.parentTypeCode,
              //           typeCode: item?.parentTypeCode,
              //           ...item,
              //         });
              //         // getqlJcDet({
              //         //   typeCode: 'zzcc-aq-qljcxx',
              //         //   data: {
              //         //     id: item.id,
              //         //     pageNo: 1,
              //         //     pageSize: 10,
              //         //   },
              //         // });
              //         // getqlDet({
              //         //   typeCode: 'zzcc-aq-qlxx',
              //         //   params: {
              //         //     id: item.id,
              //         //   },
              //         // });
              //         // run({ id: item?.id });
              //       } catch (error) {
              //         console.log(error);
              //       }
              //     }}
              //   >
              //     <img
              //       data-event-key="set1"
              //       src={
              //         items?.find(
              //           (it) => it.typeCode === searchParams.parentTypeCode,
              //         )?.icon ??
              //         require('@/assets/images/SecurityServiceOverview/mapGroup/icon1.png')
              //       }
              //       alt=""
              //       style={{ width: 52, height: 52, zIndex: 999 }}
              //     />
              //   </CooglMap.CustomOverlay>
              // );
            })}
            {earlyData?.data?.records?.map((item: any, index: number) => {
              const point = [Number(item?.longitude), Number(item?.latitude)];
              // return (
              //   <CooglMap.Marker
              //     key={index}
              //     onClick={() => {}}
              //     position={point}
              //     icon={colorConfig[item?.risklevel]?.icon}
              //   ></CooglMap.Marker>
              // );
              return (
                <CooglMap.CustomOverlay
                  key={index}
                  position={point}
                  onSet={() => {
                    setDetailModalOpt({
                      open: true,
                      eventId: item?.riskId,
                      ...item,
                    });
                  }}
                >
                  <div
                    className={classNames({
                      [styles.newWarn]: index === 0 && count < 10,
                    })}
                    data-event-key="set"
                  >
                    <img
                      src={colorConfig[item?.risklevel]?.icon}
                      alt=""
                      style={
                        index === 0 && count < 10
                          ? { width: 91, height: 91, zIndex: 999 }
                          : { width: 52, height: 52, zIndex: 999 }
                      }
                    />
                  </div>
                </CooglMap.CustomOverlay>
              );
            })}
            {industryModalData?.open && (
              <CooglMap.CustomOverlay
                position={[
                  Number(industryModalData?.longitude),
                  Number(industryModalData?.latitude),
                ]}
                offset={{
                  top: -50,
                }}
                onClose={(e) => {
                  setIndustryModalData({ open: false, title: '' });
                }}
              >
                <div className={styles.window}>
                  <PopoverCardKnotty
                    data={qlDet?.data?.records?.[0]}
                    projectList={data?.projectList}
                  ></PopoverCardKnotty>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </Fragment>
        </CooglMap.MapView>
      </div>

      <div className={styles.checkBox}>
        <CheckboxGroup
          onCheck={(e) => {
            console.log(e);

            setSearchParams({
              ...searchParams,
              parentTypeCode:
                e === searchParams?.parentTypeCode ? undefined : e,
            });
          }}
          checkCode={searchParams.parentTypeCode}
        />
      </div>
      {/* 事件详情 */}
      <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>
      {/**道路桥梁情况 */}
      <Modal
        open={false}
        title={qlDet?.data?.records?.[0]?.name}
        // onCancel={() => setWayModalOpt({ open: false, title: '' })}
        width={650}
        height={846}
      >
        {dqLoading ? (
          <div
            style={{
              width: '100%',
              height: '100%',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Spin></Spin>
          </div>
        ) : (
          <div className={styles.detCon}>
            <div className={styles.detTitleWarp}>
              <img
                src={`${qlZwUrl}${qlDet?.data?.records?.[0]?.photos}`}
                alt=""
                className={styles.img}
              />
              <div>
                {qlDet?.data?.records?.[0]?.name}
                <div className={styles.tag}>
                  {qlDet?.data?.records?.[0]?.dictgnlxName}
                </div>
              </div>
            </div>
            <Descriptions column={1}>
              <Descriptions.Item label="所属区域">
                {qlDet?.data?.records?.[0]?.regionName}
              </Descriptions.Item>
              <Descriptions.Item label="设施位置">
                {qlDet?.data?.records?.[0]?.descroad}
              </Descriptions.Item>
              <Descriptions.Item label="责任单位">
                {qlDet?.data?.records?.[0]?.descgldw}
              </Descriptions.Item>
            </Descriptions>
            <div className={styles.content}>
              <div>{data?.status}</div>
              <div className={styles.warp}>
                {data?.projectList?.map((item: any, index: number) => {
                  return (
                    <div style={{ marginBottom: 15 }} key={index}>
                      <div style={{ marginBottom: 10, fontSize: 20 }}>
                        {item?.projectName}
                      </div>
                      <div className={styles.pw}>
                        {item?.reportObjectList?.map((i: any, idx: number) => {
                          return (
                            <div className={styles.item} key={idx}>
                              <div style={{ color: 'rgb(202, 223, 252)' }}>
                                {i?.reportObject}
                                <span
                                  className={styles.tag}
                                  style={{
                                    color:
                                      i.normalFlag === '0' ? '#47ffa0' : 'red',
                                  }}
                                >
                                  {i.normalFlag === '0' ? '正常' : '异常'}
                                </span>
                              </div>
                              <div style={{ marginTop: 3 }}>
                                {Object.entries(
                                  getMap(i?.monitoringValue),
                                )?.map((it: any) => {
                                  return (
                                    <div>
                                      {it[0]}:{it[1]}
                                    </div>
                                  );
                                })}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default SafetyMap;
