import React, { useState, useEffect, useRef, useCallback } from 'react';
import { FormattedMessage, useModel, useRequest } from 'umi';
import PageHeader from '@/sagacare_components/PageHeader';
import Map from '@/sagacare_components/map';
import SearchInput from '@/sagacare_components/SearchInput';
import TopNavigator from '@/sagacare_components/topNavigator';
import ChartModal from './components/chartModal';
import moment from 'moment';
import {
  getMapList,
  queryEnvironmentParam,
  getSeasonType,
} from '@/services/sagacare_service/environment';
import { projectObj } from '@/config/api.js';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import { Spin } from 'antd';
import Icon from '@/tenants-ui/SgIcon';
import { getMaxScale } from '@/hooks/useMap';

import cx from 'classnames';
import styles from './index.less';
import mapstyles from '@/sagacare_components/map/index.less';

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

  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: ['#5E8BCF', '#C9E5FF', '#F3F3F3', '#FFB6A7', '#EE6D66'],
      opacity: 1, //透明度基数
      indicator: [0, 18, 22, 26, 30],
      fixed: 1,
    },
    {
      name: '湿度',
      id: 'RH',
      src: envir_wet,
      unit: '%',
      color: '#9FB7CD',
      colorStr: [
        'rgba(255, 232, 35, 0.4)',
        ' rgba(255, 232, 35, 0.2)',
        'rgba(159, 183, 205, 0.2)',
        'rgba(94, 139, 207, 0.4)',
        'rgba(94, 139, 207, 0.8)',
      ],
      opacity: 1,
      indicator: [0, 20, 40, 60, 80],
      fixed: 1,
    },
    {
      name: 'CO₂',
      id: 'CO2',
      src: envir_co2,
      unit: 'ppm',
      color: '#00DC23',
      colorStr: '0,220,35,',
      opacity: 0.2,
      indicator: [0, 500, 1000, 1500, 2000],
      fixed: 0,
    },
    {
      name: 'PM2.5',
      id: 'PM2d5',
      src: envir_pm25,
      unit: 'ug/m³',
      color: '#E89E32',
      colorStr: '232,158,50,',
      opacity: 0.2,
      indicator: [0, 20, 80, 140, 200],
      fixed: 1,
    },
    {
      name: '甲醛',
      id: 'HCHO',
      src: envir_jiaquan,
      unit: 'mg/m³',
      color: '#140050',
      colorStr: '20,0,80,',
      opacity: 0.15,
      indicator: [0, 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 [seasonType, setSeasonType] = useState<any>('Cooling');
  const [scale, setScale] = useState<number>(0.8);
  const [maxScale, setMaxScale] = useState<number>(1);
  const [transXInit, setTransXInit] = useState<number>(0);

  const [mapSize, setMapSize] = useState<any>({});
  const mapListCopy = useRef<any[]>([]);

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

  const changeFloorId = (data: string) => {
    setSelFloorId(data);
  };
  const changeBuildId = (data: string) => {
    setSelBuildId(data);
  };
  //导航切换时
  const navigatorChange = (item: navigatorItem) => {
    //在切了参数导航之后 把空间的平均值 设置为空
    mapCombineList.forEach((item, index) => {
      item.avgValues = null;
    });
    setMapCombineList(mapCombineList);

    setSelNav(item);
    setSelNavId(item.id);
  };

  //根据指标的值  得到不同的透明度等级 第一级0.2 第二级0.4 依次往后
  const getColorOpacity = (value: number): number => {
    var indicator: number[] = selNav.indicator || []; //指标梯度

    var res = 1;

    let indicatorArr = [value, ...indicator].sort((a, b) => {
      return a - b;
    });
    res = indicatorArr.findIndex((item) => item === value);

    //console.log('getColorOpacity-value', value, indicator, res);
    return res;
  };

  //获取地图 mapList
  useEffect(() => {
    if (selFloorId) {
      changeLastFloorId(selFloorId);
      setLoading(true);
      getMapList({
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        floorId: selFloorId,
      })
        .then((res) => {
          setLoading(false);
          var data: API.MapInfo[] = (res.data || {}).spaceList || [];

          var bodyWidth = document.body.offsetWidth;
          var mapWidth = (res.data || {}).width || 800;
          if (mapWidth < bodyWidth) {
            var mscale = 1;
            setTransXInit((bodyWidth - mapWidth) / 2);
          } else {
            var mscale = Number((bodyWidth / mapWidth).toFixed(4));
            setTransXInit(0);
          }

          var mapSize: any = {
            width: mapWidth * mscale,
            height: (res.data || {}).height * mscale,
          };

          setMapSize(mapSize);

          data.forEach((item, index) => {
            item.width = item.width * mscale;
            item.height = item.height * mscale;
            item.left = item.left * mscale;
            item.top = item.top * mscale;
          });

          var maxScaleTemp = getMaxScale(data);
          setMaxScale(maxScaleTemp);

          setMapList(data);
          mapListCopy.current = data;
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      setMapList([]);
    }
  }, [selFloorId]);

  const changeMapList = useCallback(
    (mscale, moveWidth, moveHeight) => {
      setScale(mscale);
      var mapListTemp = JSON.parse(JSON.stringify(mapListCopy.current));
      var mapListTemp2 = mapListTemp.map((item, index) => {
        if (index == 0) {
          //console.log('mapListTemp', mscale, item.width, item.width * mscale);
        }
        item.width = item.width * mscale;
        item.height = item.height * mscale;
        item.left = item.left * mscale - moveWidth;
        item.top = item.top * mscale - moveHeight;
        return item;
      });
      setMapList(mapListTemp2);
    },
    [mapListCopy],
  );

  //请求环境数据
  useEffect(() => {
    if (selNavId && selFloorId) {
      //setLoading(true);

      var p1 = getSeasonType({
        projectId: projectObj.projectId,
        date: moment().format('YYYYMMDD'),
      });
      var floorParams = [{ id: selFloorId, projectId: projectObj.projectId }];
      var endTime = moment();
      var startTime = moment().subtract(30, 'minutes');
      var startStr = startTime.format('YYYYMMDDHHmmss');
      var endStr = endTime.format('YYYYMMDDHHmmss');

      var p2 = queryEnvironmentParam(floorParams, {
        endTime: endStr,
        startTime: startStr,
        param: selNavId,
      });
      //console.log('mapCombineList', mapCombineList);

      Promise.all([p1, p2])
        .then(function (result) {
          var season = (result[0] && result[0].data) || 'Cooling';
          setSeasonType(season);
          var environment = (result[1] && result[1].data) || {};
          var avgValues = environment.avgValues;
          avgValues = avgValues ? avgValues.toFixed(selNav.fixed) : avgValues;
          var navTemp = { ...selNav, avgValues: avgValues };
          setSelNav(navTemp);
          //空间环境数据
          var dataSpaces = (environment.floors[0] || {}).dataSpaces || [];
          setEnvirMapList(dataSpaces);
        })
        .catch(function (err) {});
    }
  }, [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({}, filterSpace[0], mitem);
      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 (
    <div className={styles.sagawrap}>
      <PageHeader
        title={<FormattedMessage id="menu.environment" />}
        action={
          <SearchInput />

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

      <TopNavigator
        navigatorList={navigatorList}
        type={'enviroment'}
        seasonType={seasonType}
        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={cx(styles.indicatorBox, styles.tdbIndicator)}
                key={index + 'indicator'}
              >
                <div className={styles.text}>{item == 0 ? '' : item}</div>
                <div
                  className={styles.color}
                  style={{
                    backgroundColor:
                      selNav.id == 'Tdb' || selNav.id == 'RH'
                        ? selNav.colorStr[index]
                        : 'rgba(' +
                          selNav.colorStr +
                          (selNav.opacity as number) * (index + 1) +
                          ')',
                  }}
                ></div>
              </div>
            );
          })}
        </div>
      </div>
      <Spin spinning={loading} wrapperClassName={mapstyles.spinnclass}>
        <Map
          type={'enviroment'}
          maxscale={maxScale}
          transXInit={transXInit}
          mapList={mapCombineList}
          changeMapList={changeMapList}
          mapSize={mapSize}
          selFloorId={selFloorId}
          render={(item: API.MapInfo, index: number) => {
            return (
              <div
                className={cx(mapstyles.houseWrap)}
                key={index + 'house'}
                style={{
                  left: item.left,
                  top: item.top,
                  width: item.width,
                  height: item.height,
                }}
              >
                <div
                  className={cx(mapstyles.house, {
                    [mapstyles.notclick]:
                      !item.roomFuncType || (!item.avgValues && item.avgValues != 0),
                    [mapstyles.searchSel]: item.spaceId && item.spaceId === searchSpace.spaceId,
                  })}
                  style={{
                    background: item.roomFuncType
                      ? item.avgValues || item.avgValues == 0
                        ? selNav.id == 'Tdb' || selNav.id == 'RH'
                          ? item.avgValues
                            ? selNav.colorStr[getColorOpacity(item.avgValues) - 1]
                            : ''
                          : 'rgba(' +
                            selNav.colorStr +
                            (selNav.opacity as number) * getColorOpacity(item.avgValues) +
                            ')'
                        : ''
                      : '',
                  }}
                  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: 18,
                        display: item.width > 28 && item.height > 50 ? 'block' : 'none',
                      }}
                    ></Icon>
                    <div
                      className={mapstyles.name}
                      style={{
                        display:
                          (item.width > 64 && item.height > 80) ||
                          item.height > 140 ||
                          item.width > 120 ||
                          scale == maxScale
                            ? 'block'
                            : 'none',
                      }}
                    >
                      {item.localName}
                    </div>
                    {(getSpaceFunc(item.roomFuncType) || item.localName) &&
                      !(
                        (getSpaceFunc(item.roomFuncType) && item.width > 28 && item.height > 50) ||
                        (item.localName &&
                          ((item.width > 64 && item.height > 80) ||
                            item.height > 140 ||
                            item.width > 120 ||
                            scale == maxScale))
                      ) && <div className={mapstyles.pointer}>.</div>}
                  </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>
      )}
    </div>
  );
};

export default Environment;
