import livingGarbageIcon from '@/assets/images/livingGarbage.png';
import locationIcon from '@/assets/images/location.png';
import openIcon from '@/assets/images/openIcon.png';
import packUpIcon from '@/assets/images/packUpIcon.png';
import CooglMap from '@/components/CooglMap';
import services from '@/services';
import { convertUnits } from '@/utils/ui';
import { RightOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Progress, Tree } from 'antd';
import dayjs from 'dayjs';
import React, { useMemo, useRef, useState } from 'react';
import styles from './index.less';
import PopoverCard from './PopoverCard';

const LivingGarbage: React.FC = () => {
  const [isListVisible, setIsListVisible] = useState(true);
  const mapRef = useRef<any>();
  const [expand, setExpand] = useState<string>();
  const [areaSelectd, setAreaSelectd] = useState<any>(undefined);
  const [checkedKeys, setCheckedKeys] = useState([
    '生活垃圾焚烧发电厂',
    '生活垃圾填埋场',
    '渗滤液处理厂',
    '厨余垃圾处理厂',
  ]);
  let isUsingValue = true;

  const searchTime = {
    startTime: dayjs().startOf('month').format('YYYY-MM-DD'),
    endTime: dayjs().endOf('month').format('YYYY-MM-DD'),
  };

  const { data: infoData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-shlj-czzl',
      params: {
        ...searchTime,
      },
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records?.[0];
      }
      throw new Error('获取数据失败');
    }),
  );

  const { data: burnData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-shlj-gfscczl',
      params: {
        ...searchTime,
      },
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );

  const { data: typeData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-shlj-ljclslb',
      params: {
        ...searchTime,
      },
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );

  const { data: pointData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-shlj-ljcfylb',
      params: {
        pageNo: 0,
        pageSize: 50,
        ...searchTime,
      },
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records?.[0]?.list;
      }
      throw new Error('获取数据失败');
    }),
  );
  //查询详情
  const { runAsync: getDetails } = useRequest(
    services.DataBase.getSjdzInfoData,
    { manual: true },
  );

  const list = [
    {
      title: '环保发电厂',
      key: '生活垃圾焚烧发电厂',
      icon: require('@/assets/images/clc1.png'),
    },
    {
      title: '填埋场',
      key: '生活垃圾填埋场',
      icon: require('@/assets/images/clc2.png'),
    },
    {
      title: '渗滤液厂',
      key: '渗滤液处理厂',
      icon: require('@/assets/images/clc3.png'),
    },
    {
      title: '餐厨厂',
      key: '厨余垃圾处理厂',
      icon: require('@/assets/images/clc4.png'),
    },
  ];

  const treeData = useMemo(() => {
    return [
      {
        title: '生活固体废弃物末端处置设施',
        key: '生活固体废弃物末端处置设施',

        children: list?.map((item) => ({
          title: (
            <div className={styles.treeTitle}>
              <img src={item?.icon} alt=""></img>
              {item?.title}
            </div>
          ),
          key: item?.key,
        })),
      },
    ];
  }, []);

  const leftList = useMemo(() => {
    return list?.map((item) => ({
      ...item,
      children: pointData?.filter((it: any) => item?.key === it.czclx),
    }));
  }, [pointData]);
  

  // 定位功能
  const handleLocation = async (location: { x: number; y: number }) => {
    try {
      const res = await getDetails({
        typeCode: 'zzcc-shlj-ljcfylb',
        params: {
          czcid: location?.czcid,
          ...searchTime,
        },
      });
      const res1 = await getDetails({
        typeCode: 'zzcc-shlj-byczl',
        params: {
          name: location?.czcmc,
          ...searchTime,
        },
      });

      mapRef?.current?.flyTo({
        destination: {
          x: Number(location?.longitude),
          y: Number(location?.latitude) + 0.03,
          z: 23961,
        },
      });

      setAreaSelectd({
        ...res?.data?.data?.records?.[0]?.list?.[0],
        ...res1?.data?.data?.records?.[0],
      });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.leftContent}>
        {/* 生活垃圾处置情况 */}
        <div className={styles.disposalStatus}>
          <div className={styles.title}>生活垃圾处置情况</div>
          <div className={styles.date}>{dayjs().format('YYYY年MM月')}</div>

          <div className={styles.totalDisposal}>
            <img src={livingGarbageIcon} alt="垃圾处理" />
            <span className={styles.label}>处置总量</span>
            <span className={styles.value}>{infoData?.total ?? '--'}</span>
            <span className={styles.unit}>万吨</span>
          </div>

          <div className={styles.subItems}>
            <div className={styles.item}>
              <div className={styles.label}>焚烧量</div>
              <div className={styles.value}>{infoData?.fsl ?? '--'}</div>
              <span className={styles.unit}>万吨</span>
            </div>
            <div className={styles.item}>
              <div className={styles.label}>填埋量</div>
              <div className={styles.value}>{infoData?.tml ?? '--'}</div>
              <span className={styles.unit}>万吨</span>
            </div>
          </div>

          <div className={styles.disposalList}>
            <div className={styles.listTitle}>
              环保发电厂处置量
              <span className={styles.unit}>单位：万吨</span>
            </div>
            <div className={styles.listContent}>
              {burnData?.map((item: any, index: number) => (
                <div key={index} className={styles.listItem}>
                  <span className={styles.name} title={item?.name}>
                    {item?.name}
                  </span>
                  <Progress
                    size={{ height: 15 }}
                    percent={
                      (Number(convertUnits(item?.czl)?.num) /
                        Number(infoData?.fsl)) *
                      100
                    }
                    showInfo={false}
                    trailColor="rgba(144, 205, 229, 0.22)"
                    strokeColor={{ from: '#79FFD1', to: '#00B9FF' }}
                    className={styles.progress}
                  />
                  <span className={styles.value}>
                    {convertUnits(item?.czl)?.num}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className={styles.rightContent}>
        <div
          className={styles.mapContainer}
          style={{ width: 1500, height: 900 }}
        >
          <CooglMap.MapView
            ref={mapRef}
            // {...mapConfig}
            zoom={8}
            center={{ x: 103.96, y: 30.658842 }}
            mode="3D"
          >
            {pointData
              ?.filter((it) => checkedKeys?.includes(it.czclx))
              ?.map((item, index) => {
                return (
                  <CooglMap.CustomOverlay
                    key={index}
                    position={[Number(item?.longitude), Number(item?.latitude)]}
                    onClick={async () => {
                      try {
                        const res = await getDetails({
                          typeCode: 'zzcc-shlj-ljcfylb',
                          params: {
                            czcid: item.czcid,
                            ...searchTime,
                          },
                        });
                        console.log(res);
                        const res1 = await getDetails({
                          typeCode: 'zzcc-shlj-byczl',
                          params: {
                            name: location?.czcmc,
                            ...searchTime,
                          },
                        });
                        setAreaSelectd({
                          ...res?.data?.data?.records?.[0]?.list?.[0],
                          ...res1?.data?.data?.records?.[0],
                        });
                      } catch (error) {
                        console.log(error);
                      }
                    }}
                  >
                    <div className={styles.markWrap}>
                      <div className={styles.name} title={item?.czcmc}>
                        {item?.czcmc}
                      </div>
                      <div className={styles.iconWrap}>
                        <img
                          src={
                            list?.find((it) => it?.key === item?.czclx)?.icon
                          }
                          alt=""
                        />
                      </div>
                    </div>
                  </CooglMap.CustomOverlay>
                );
              })}

            {areaSelectd && (
              <CooglMap.CustomOverlay
                position={[
                  Number(areaSelectd.longitude),
                  Number(areaSelectd.latitude),
                ]}
                offset={{
                  top: -50,
                }}
                onClose={() => {
                  setAreaSelectd(undefined);
                }}
              >
                <div className={styles.window} style={{ width: 382 }}>
                  <PopoverCard data={areaSelectd}></PopoverCard>
                </div>
              </CooglMap.CustomOverlay>
            )}

            {/* 地图标题 - 移到地图内部 */}
            <div className={styles.mapTitle}>
              生活固体废弃物末端处置设施分布
            </div>

            <div className={styles.legend}>
              <div className={styles.legendTitle}>图层图例</div>

              {typeData?.length ? (
                <Tree
                  checkable
                  defaultExpandAll
                  onCheck={(e: any) => {
                    setCheckedKeys(e);
                  }}
                  checkedKeys={checkedKeys}
                  treeData={treeData}
                />
              ) : null}
            </div>

            {/* 右侧列表 */}
            {/* 收起按钮独立放置 */}
            <div
              className={`${styles.collapseBtn} ${
                !isListVisible ? styles.collapsed : ''
              }`}
              onClick={() => setIsListVisible(!isListVisible)}
            >
              {isListVisible && (
                <div className={styles.btnText}>
                  <span>收</span>
                  <span>起</span>
                </div>
              )}
              {!isListVisible && (
                <div className={styles.btnText}>
                  <span>展</span>
                  <span>开</span>
                </div>
              )}
              <RightOutlined className={styles.collapseIcon} />
            </div>

            <div
              className={`${styles.listContainer} ${
                !isListVisible ? styles.collapsed : ''
              }`}
            >
              <div className={styles.listHeader}>
                <div className={styles.listTitle}>
                  <span> 生活废弃物末端处置设施列表</span>
                </div>
              </div>

              <div className={styles.listContent}>
                {leftList?.map((item, index) => {
                  return (
                    <div key={index}>
                      <div
                        className={styles.listItem}
                        onClick={() => {
                          if (expand === item?.title) {
                            setExpand(undefined);
                            return;
                          }

                          setExpand(item?.title);
                        }}
                      >
                        <span className={styles.name}>
                          {item?.title}
                          {`(${item?.children?.length ?? 0})`}
                        </span>
                        <img
                          src={expand === item?.czclx ? packUpIcon : openIcon}
                          className={styles.locationIcon}
                          alt="定位"
                        />
                      </div>
                      {expand === item?.title && (
                        <div className={styles.itemWrap}>
                          {item?.children?.map((it, idx) => (
                            <div
                              key={idx}
                              className={styles.item}
                              onClick={() => handleLocation(it)}
                            >
                              <span className={styles.name} title={it?.czcmc}>
                                {it?.czcmc}
                              </span>
                              <img
                                src={locationIcon}
                                className={styles.locationIcon}
                                alt="定位"
                              />
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </CooglMap.MapView>
        </div>
      </div>
    </div>
  );
};

export default LivingGarbage;
