import React, { useState, useEffect } from 'react';
import { FormattedMessage, useModel, useRequest } from 'umi';
import PageHeader from '@/components/PageHeader';
import Map from '@/components/map';
import SearchInput from '@/components/SearchInput';
import TopNavigator from '@/components/topNavigator';
import ChartModal from './components/chartModal';
import moment from 'moment';
import { getMapList, queryEnvironmentParam } from '@/services/ant-design-pro/environment';
import { equipImageMap } from '@/config/image.js';
import { Spin } from 'antd';
import Icon from '@/tenants-ui/Icon';

import styles from './index.less';
import mapstyles from '@/assets/css/map.less';

export type navigatorItem = {
  name: string;
  id: string;
  src: any;
  unit?: string;
  num?: number;
  color: string;
  colorStr: string;
  opacity?: number;
  indicator?: number[];
  [key: string]: any;
};
const Environment: React.FC = () => {
  const { projectId } = useModel('spaceFunc');
  const { envir_temperature, envir_wet, envir_co2, envir_pm25, envir_jiaquan } = equipImageMap;

  const [searchText, setSearchText] = useState<{ text: any }>();
  const [showChart, setShowChart] = useState(false);
  const [selFloorId, setSelFloorId] = useState<string>();
  const [selBuildId, setSelBuildId] = useState<string>();
  const [showSpace, setShowSpace] = useState<API.MapInfo>({}); //当前弹框选中的空间
  const [navigatorList] = useState<navigatorItem[]>([
    {
      name: '温度',
      id: 'Tdb',
      src: envir_temperature,
      unit: '℃',
      color: '#E5574F',
      colorStr: '229,87,79,',
      opacity: 0.2, //透明度基数
      indicator: [18, 21, 24, 27, 30],
      fixed: 1,
    },
    {
      name: '湿度',
      id: 'RH',
      src: envir_wet,
      unit: '%',
      color: '#9FB7CD',
      colorStr: '159,183,205,',
      opacity: 0.2,
      indicator: [25, 35, 45, 55, 65],
      fixed: 1,
    },
    {
      name: 'CO₂',
      id: 'CO2',
      src: envir_co2,
      unit: 'ppm',
      color: '#00DC23',
      colorStr: '0,220,35,',
      opacity: 0.2,
      indicator: [500, 700, 1000, 2000, 3000],
      fixed: 0,
    },
    {
      name: 'PM2.5',
      id: 'PM2d5',
      src: envir_pm25,
      unit: 'ug/m³',
      color: '#E89E32',
      colorStr: '232,158,50,',
      opacity: 0.2,
      indicator: [15, 25, 35, 75, 90],
      fixed: 1,
    },
    {
      name: '甲醛',
      id: 'HCHO',
      src: envir_jiaquan,
      unit: 'mg/m³',
      color: '#140050',
      colorStr: '20,0,80,',
      opacity: 0.25,
      indicator: [0.02, 0.05, 0.1, 0.15], //指标梯度
      fixed: 2,
    },
  ]);
  const [loading, setLoading] = useState<boolean>(false);
  const [selNav, setSelNav] = useState<navigatorItem>(navigatorList[0]);
  const [selNavId, setSelNavId] = useState<string>(navigatorList[0].id);
  const [mapList, setMapList] = useState<API.MapInfo[]>([]);
  const [mapSize, setMapSize] = useState<any>({});

  const [envirMapList, setEnvirMapList] = useState<API.MapInfo[]>([]);
  const [mapCombineList, setMapCombineList] = useState<any[]>([]);
  const { getSpaceFunc } = useModel('spaceFunc');

  const changeFloorId = (data: string) => {
    setSelFloorId(data);
  };
  const changeBuildId = (data: string) => {
    setSelBuildId(data);
  };
  //导航切换时
  const navigatorChange = (item: navigatorItem) => {
    setSelNav(item);
    setSelNavId(item.id);
  };

  //根据指标的值  得到不同的透明度等级 第一级0.2 第二级0.4 依次往后
  const getColorOpacity = (value: number): number => {
    var indicator: number[] = selNav.indicator || []; //指标梯度
    var number = indicator.length;
    var res = 1;
    for (var i = 0; i < number; i++) {
      if (value >= indicator[i] && value < indicator[i + 1]) {
        res = i + 1;
        break;
      }
    }
    return res;
  };
  //   const { data, loading } = useRequest(
  //     () => {
  //       return getMapList({
  //         floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
  //       });
  //     },
  //     {
  //       refreshDeps: [selFloorId],
  //     },
  //   );

  //获取地图 mapList
  useEffect(() => {
    if (selFloorId) {
      setLoading(true);
      getMapList({
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        floorId: selFloorId,
      })
        .then((res) => {
          setLoading(false);
          var data: API.MapInfo[] = (res.data || {}).spaceList || [];
          var mapSize = {
            width: (res.data || {}).width,
            height: (res.data || {}).height,
          };
          setMapSize(mapSize);
          setMapList(data);
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      setMapList([]);
    }
  }, [selFloorId]);
  //请求环境数据
  useEffect(() => {
    if (selNavId && selFloorId) {
      //setLoading(true);
      var floorParams = [{ id: selFloorId, projectId: projectId }];
      var endTime = moment();
      var startTime = moment().subtract(30, 'minutes');
      var startStr = startTime.format('YYYYMMDDHHmmss');
      var endStr = endTime.format('YYYYMMDDHHmmss');

      queryEnvironmentParam(floorParams, {
        endTime: endStr,
        startTime: startStr,
        param: selNavId,
      })
        .then((res) => {
          //setLoading(false);
          var avgValues = (res.data || {}).avgValues;
          avgValues = avgValues ? avgValues.toFixed(selNav.fixed) : avgValues;
          var navTemp = { ...selNav, avgValues: avgValues };
          setSelNav(navTemp);
          //空间环境数据
          var dataSpaces = ((res.data || {}).floors[0] || {}).dataSpaces || [];
          setEnvirMapList(dataSpaces);
        })
        .catch(() => {
          // setLoading(false);
        });
    }
  }, [selNavId, selFloorId]);
  //合并空间环境数据 和 空间数据
  useEffect(() => {
    var combineList: any = [];
    mapList.map(function (mitem) {
      var spaceId = mitem.spaceId;
      var filterSpace = envirMapList.filter((ele) => {
        return ele.id == spaceId;
      });

      var combine = Object.assign({}, mitem, filterSpace[0]);
      combineList.push(combine);
    });
    setMapCombineList(combineList);
  }, [envirMapList, mapList]);

  const showChartModal = (item) => {
    if (!item.roomFuncType) return;
    setShowChart(true);
    setShowSpace(item);
  };
  let firtTime: number = 0;
  let lastTime: number = 0;
  return (
    <>
      <PageHeader
        title={<FormattedMessage id="menu.environment" />}
        action={
          <SearchInput mapList={mapList} />

          //   <Input.Search
          //     size="large"
          //     allowClear
          //     style={{ width: '230px' }}
          //     placeholder={'搜索空间'}
          //     onSearch={(s) => {
          //       setSearchText(s);
          //     }}
          //   />
        }
      />

      <TopNavigator
        navigatorList={navigatorList}
        type={'enviroment'}
        navigatorChange={navigatorChange}
        changeFloorId={changeFloorId}
        changeBuildId={changeBuildId}
        selParamObj={selNav}
      ></TopNavigator>
      <div className={styles.maptop}>
        <div className={styles.right}>
          {(selNav.indicator || []).map((item, index) => {
            return (
              <div className={styles.indicatorBox} key={index + 'indicator'}>
                <div className={styles.text}>{item}</div>
                <div
                  className={styles.color}
                  style={{
                    backgroundColor:
                      'rgba(' + selNav.colorStr + (selNav.opacity as number) * (index + 1) + ')',
                  }}
                ></div>
              </div>
            );
          })}
        </div>
      </div>
      <Spin spinning={loading}>
        <Map
          type={'enviroment'}
          mapList={mapCombineList}
          mapSize={mapSize}
          render={(item: API.MapInfo, index: number) => {
            return (
              <div
                key={index + 'house'}
                className={mapstyles.house}
                style={{
                  left: item.left,
                  top: item.top,
                  width: item.width,
                  height: item.height,
                  background: item.roomFuncType
                    ? 'rgba(' +
                      selNav.colorStr +
                      (selNav.opacity as number) * getColorOpacity(item.avgValues) +
                      ')'
                    : 'repeating-linear-gradient(45deg, rgb(226 226 226), #ffffff 8px)',
                }}
                onClick={(event) => {
                  event.stopPropagation();
                  if (lastTime - firtTime < 200) {
                    showChartModal(item);
                  }
                }}
                onMouseDown={(event) => {
                  //event.stopPropagation();
                  firtTime = new Date().getTime();
                }}
                onMouseUp={(event) => {
                  //event.stopPropagation();
                  lastTime = new Date().getTime();
                }}
              >
                <div className={mapstyles.content}>
                  <Icon
                    className=""
                    type={getSpaceFunc(item.roomFuncType)}
                    style={{ fontSize: 20 }}
                  ></Icon>
                  <div className={mapstyles.name}>{item.localName}</div>
                </div>
              </div>
            );
          }}
        ></Map>
      </Spin>
      {/* {mapList.map(function (item, index) {
              return (
                <div
                  key={index + 'house'}
                  className={mapstyles.house}
                  style={{
                    left: item.left,
                    top: item.top,
                    width: item.width,
                    height: item.height,
                    backgroundColor:
                      'rgba(' +
                      selNav.colorStr +
                      (selNav.opacity as number) * getColorOpacity(item.value) +
                      ')',
                  }}
                >
                  <div className={mapstyles.content}>
                    <Icon className="" type={item.type} style={{ fontSize: 20 }}></Icon>
                    <div className={mapstyles.name}>{item.name}</div>
                  </div>
                </div>
              );
            })} */}

      {showChart && (
        <ChartModal
          showSpace={showSpace}
          selNav={selNav}
          onClose={() => {
            setShowChart(false);
          }}
        ></ChartModal>
      )}
    </>
  );
};

export default Environment;
