import React, { useState, useEffect, useCallback, useRef } from 'react';
import PageHeader from '@/sagacare_components/PageHeader';
import Map from '@/sagacare_components/map';
import TopNavigator from '@/sagacare_components/topNavigator';
import RunNavRight from './components/topNavRight';
import { FormattedMessage, history, useModel } from 'umi';
import { Spin } from 'antd';
import { Popover } from 'antd';
import styles from './index.less';
import mapstyles from '@/sagacare_components/map/index.less';
import Icon from '@/tenants-ui/SgIcon';
import SearchInput from '@/sagacare_components/SearchInput';
import moment from 'moment';
import cx from 'classnames';
import { getMaxScale } from '@/hooks/useMap';

import { getMapList, queryDeviceTimeManage } from '@/services/sagacare_service/environment';

type runtimeNavType = {
  normalRun: any;
  overtimeWork: number;
  meetingBook: number;
};

const Runtime: React.FC = () => {
  // const { maptemp6 } = equipImageMap;
  const { changeLastFloorId } = useModel('sagacare_buildFloor');
  const { searchSpace } = useModel('sagacare_searchInfo');
  const { getSpaceFunc } = useModel('sagacare_spaceFunc');
  const [loading, setLoading] = useState<boolean>(false);
  const [runtimeNav, setRuntimeNav] = useState<runtimeNavType>({});
  const [mapList, setMapList] = useState<API.MapInfo[]>([]);
  const mapListCopy = useRef<any[]>();

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

  const [scale, setScale] = useState<number>(0.8);
  const [maxScale, setMaxScale] = useState<number>(1);
  const [transXInit, setTransXInit] = useState<number>(0);

  const [mapCombineList, setMapCombineList] = useState<any[]>([]);
  const [selFloorId, setSelFloorId] = useState<string>();
  const [selTime, setSelTime] = useState<string>(moment().format('YYYYMMDD'));
  const [spaceTimeList, setSpaceTimeList] = useState<any[]>([]);

  //楼层切换的回调
  const changeFloorId = (data: string) => {
    setSelFloorId(data);
  };
  const checkRecord = () => {
    history.push('/runtime/recordList');
    console.log('showR');
  };
  //时间切换的回调
  const changeTime = (time) => {
    var timeStr = time.format('YYYYMMDD');
    setSelTime(timeStr);
  };
  //获取地图 mapList
  useEffect(() => {
    if (selFloorId) {
      changeLastFloorId(selFloorId);
      setLoading(true);
      getMapList({
        floorId: selFloorId,
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
      })
        .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(
    (scale, moveWidth, moveHeight) => {
      setScale(scale);
      var mapListTemp = JSON.parse(JSON.stringify(mapListCopy.current));
      var mapListTemp2 = mapListTemp.map((item, index) => {
        if (index == 0) {
          console.log('mapListTemp', scale, item.width, item.width * scale);
        }
        item.width = item.width * scale;
        item.height = item.height * scale;
        item.left = item.left * scale - moveWidth;
        item.top = item.top * scale - moveHeight;
        return item;
      });
      setMapList(mapListTemp2);
    },
    [mapListCopy],
  );

  const getDeviceTime = () => {
    setLoading(true);
    queryDeviceTimeManage({
      floorId: selFloorId,
      //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
      date: selTime,
    })
      .then(function (res) {
        setLoading(false);
        if (!setTimer.current) return;

        var resdata = res || {};
        setRuntimeNav({
          normalRun: resdata.workTimeNum,
          overtimeWork: resdata.overTimeNum,
          meetingBook: resdata.meetTimeNum,
        });
        var resList = res.content || [];
        resList.forEach((ritem) => {
          ritem.runTimeStatus = ''; //正常工作
          ritem.hasWorkTime = false;
          var timeList = [];
          var allTimeArr = [];

          if (ritem.hasOwnProperty('workTimeStartTime')) {
            // var timeStrArr = [ritem.workTimeStartTime, ritem.workTimeEndTime];
            //timeList.push(timeStrArr);
            ritem.hasWorkTime = true;
            allTimeArr.push(ritem.workTimeStartTime, ritem.workTimeEndTime);
          }
          if (ritem.hasOwnProperty('meetTime')) {
            ritem.runTimeStatus = 'meetingBook'; //会议预约
            ritem.meetTime.forEach((meetitem) => {
              var timeStrArr = [meetitem.meetTimeStartTime, meetitem.meetTimeEndTime];
              timeList.push(timeStrArr);
              allTimeArr.push(meetitem.meetTimeStartTime, meetitem.meetTimeEndTime);
            });
          }
          if (ritem.hasOwnProperty('overTime')) {
            ritem.runTimeStatus = 'overtimeWork'; //加班
            ritem.overTime.forEach((overitem) => {
              var timeStrArr = [overitem.overTimeStartTime, overitem.overTimeEndTime];
              timeList.push(timeStrArr);
              allTimeArr.push(overitem.overTimeStartTime, overitem.overTimeEndTime);
            });
          }
          ritem.showTimeList = timeList;

          allTimeArr.sort((a, b) => {
            var a1 = Date.parse('2008-08-08 ' + a);
            var b1 = Date.parse('2008-08-08 ' + b);
            return a1 - b1;
          });

          ritem.showTimeStr =
            allTimeArr.length > 1 ? allTimeArr[0] + '-' + allTimeArr[allTimeArr.length - 1] : '';
        });

        setSpaceTimeList(resList);
      })
      .catch(() => {
        setLoading(false);
      });
  };
  let setTimer = useRef<Timer>(null);
  //获取时间列表 spaceTimeList
  useEffect(() => {
    if (selFloorId && selTime) {
      //setLoading(true);

      getDeviceTime(); //第一次执行

      if (setTimer.current) {
        clearInterval(setTimer.current);
        setTimer.current = null;
      }
      //循环调接口
      setTimer.current = setInterval(() => {
        //getDeviceTime();
      }, 10000);

      return () => {
        clearInterval(setTimer.current);
        setTimer.current = null;
      };
    }
  }, [selFloorId, selTime]);

  useEffect(() => {
    //mapList,spaceTimeList 这两个数据的结合
    //console.log('dfsd-------');
    // if (mapList && mapList.length > 0 && spaceTimeList && spaceTimeList.length > 0) {

    var combineList: any = [];
    mapList.map(function (mitem) {
      var spaceId = mitem.spaceId;
      var filterSpace = spaceTimeList.filter((ele) => {
        return ele.id == spaceId;
      });

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

    setMapCombineList(combineList);
    //  }
  }, [mapList, spaceTimeList]);

  return (
    <div className={styles.sagawrap}>
      <PageHeader
        title={<FormattedMessage id="menu.runtime" />}
        action={
          //   <div className={styles.headerRight}>
          //     <div className={styles.check} onClick={checkRecord} style={{ display: 'none' }}>
          //       <Icon className="" style={{ marginRight: 6 }} type="document" />
          //       <span>查看加班记录</span>
          //     </div>
          //   </div>
          <SearchInput />
        }
      />
      <TopNavigator
        type={'runtime'}
        action={<RunNavRight runtimeNav={runtimeNav} changeTime={changeTime}></RunNavRight>}
        changeFloorId={changeFloorId}
      ></TopNavigator>
      <div className={styles.maptop}>
        <div className={styles.right}></div>
      </div>
      {/* <div className={styles.map}>
            <div className={styles.specialRoom}></div>
            <img src={mapImg}></img>
          </div> */}
      {/* <div
              className={mapstyles.house}
              style={{
                width: 180,
                height: 100,
              }}
            >
              <div className={mapstyles.allTime}>08:00-23:00</div>
              <div className={mapstyles.content}>
                <Icon className="" type="office" style={{ fontSize: 20 }}></Icon>
                <div className={mapstyles.name}>Jozy Zone</div>
              </div>
            </div> */}
      <Spin spinning={loading} wrapperClassName={mapstyles.spinnclass}>
        <Map
          mapList={mapCombineList}
          maxscale={maxScale}
          transXInit={transXInit}
          changeMapList={changeMapList}
          mapSize={mapSize}
          selFloorId={selFloorId}
          type={'runtime'}
          render={(item, index) => {
            return (
              <div
                className={mapstyles.houseWrap}
                key={index + 'house'}
                style={{
                  left: item.left,
                  top: item.top,
                  width: item.width,
                  height: item.height,
                }}
              >
                <div
                  key={index + 'house'}
                  className={cx(mapstyles.house, {
                    [mapstyles.notclick]: !item.roomFuncType,
                    [mapstyles.searchSel]: item.spaceId && item.spaceId === searchSpace.spaceId,
                  })}
                  style={{
                    background: item.roomFuncType
                      ? item.runTimeStatus == 'meetingBook'
                        ? 'rgba(0, 220, 35, 0.2)'
                        : item.runTimeStatus == 'overtimeWork'
                        ? 'rgba(94, 139, 207, 0.2)'
                        : 'rgba(196, 196, 196, 0.2)'
                      : '',
                  }}
                >
                  <div className={mapstyles.allTime}>
                    {/* {(item.timeList || []).map(function (titem: string, tindex: number) {
                  return <span key={tindex + 'time'}>{titem},</span>;
                })} */}
                    {item.showTimeList && item.showTimeList.length > 0 && (
                      <Popover
                        content={
                          <div>
                            {item.hasWorkTime && (
                              <>
                                <div className={styles.popTitle}>工作时间:</div>
                                <div>
                                  {item.workTimeStartTime}-{item.workTimeEndTime}
                                </div>
                              </>
                            )}
                            <div className={styles.popTitle}>
                              {item.runTimeStatus == 'overtimeWork' ? '加班时间' : '会议时间'}:
                            </div>
                            {(item.showTimeList || []).map((timeItem, index) => {
                              // if (index > 0) {
                              return (
                                <div key={'time' + index}>
                                  {timeItem[0]}-{timeItem[1]}
                                </div>
                              );
                              // }
                            })}
                          </div>
                        }
                        trigger="hover"
                        style={{ color: 'none' }}
                      >
                        <span
                          className={cx({
                            [mapstyles.overworkTime]: item.runTimeStatus == 'overtimeWork',
                            [mapstyles.meetTime]: item.runTimeStatus == 'meetingBook',
                          })}
                        >
                          {item.showTimeStr}
                        </span>
                      </Popover>
                    )}
                    {item.showTimeList && item.showTimeList.length == 0 && (
                      <span title={item.showTimeStr}>{item.showTimeStr}</span>
                    )}
                  </div>
                  <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>
    </div>
  );
};
export default Runtime;
