import React, { useState, useEffect, useCallback } from 'react';
import PageHeader from '@/components/PageHeader';
import Map from '@/components/map';
import TopNavigator from '@/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 '@/assets/css/map.less';
import Icon from '@/tenants-ui/Icon';
import SearchInput from '@/components/SearchInput';
import moment from 'moment';
import cx from 'classnames';

import { getMapList, queryDeviceTimeManage } from '@/services/ant-design-pro/environment';

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

const Runtime: React.FC = () => {
  // const { maptemp6 } = equipImageMap;
  const { getSpaceFunc } = useModel('spaceFunc');
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<{ text: any }>();
  const [runtimeNav, setRuntimeNav] = useState<runtimeNavType>({});
  const [mapList, setMapList] = useState<API.MapInfo[]>([]);
  const [mapSize, setMapSize] = useState<any>({});
  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) {
      setLoading(true);
      getMapList({
        floorId: selFloorId,
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        projectId: '',
      })
        .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]);

  //获取时间列表 spaceTimeList
  useEffect(() => {
    if (selFloorId && selTime) {
      //setLoading(true);
      queryDeviceTimeManage({
        floorId: selFloorId,
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        //date: selTime,
        date: 20220212,
      })
        .then(function (res) {
          //setLoading(false);
          var resdata = res || {};
          setRuntimeNav({
            normalRun: resdata.workTimeNum,
            overtimeWork: resdata.overTimeNum,
            meetingBook: resdata.meetTimeNum,
          });
          var resList = res.content || [];
          resList.forEach((ritem) => {
            ritem.runTimeStatus = 'normalRun'; //正常工作
            var timeList = [];
            if (ritem.hasOwnProperty('workTimeStartTime')) {
              var timeStrArr = [ritem.workTimeStartTime, ritem.workTimeEndTime];
              timeList.push(timeStrArr);
            }
            if (ritem.hasOwnProperty('meetTime')) {
              ritem.runTimeStatus = 'meetingBook'; //会议预约
              ritem.meetTime.forEach((meetitem) => {
                var timeStrArr = [meetitem.meetTimeStartTime, meetitem.meetTimeEndTime];
                timeList.push(timeStrArr);
              });
            }
            if (ritem.hasOwnProperty('overTimeStartTime')) {
              var timeStrArr = [ritem.overTimeStartTime, ritem.overTimeEndTime];
              timeList.push(timeStrArr);
              ritem.runTimeStatus = 'overtimeWork'; //加班
            }
            ritem.showTimeList = timeList;
            ritem.showTimeStr =
              timeList.length > 0 ? timeList[0][0] + '-' + timeList[timeList.length - 1][1] : '';
          });
          setSpaceTimeList(resList);
        })
        .catch(() => {
          //setLoading(false);
        });
    }
  }, [selFloorId, selTime]);

  useEffect(() => {
    //mapList,spaceTimeList 这两个数据的结合
    console.log('dfsd-------', mapList, spaceTimeList);
    // 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({}, mitem, filterSpace[0]);
      combineList.push(combine);
    });
    setMapCombineList(combineList);
    //  }
  }, [mapList, spaceTimeList]);

  return (
    <>
      <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 mapList={mapList} />
        }
      />
      <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}>
        <Map
          mapList={mapCombineList}
          mapSize={mapSize}
          type={'runtime'}
          render={(item, index) => {
            return (
              <div
                key={index + 'house'}
                className={mapstyles.house}
                style={{
                  left: item.left,
                  top: item.top,
                  width: item.width,
                  height: item.height,
                  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)'
                    : 'repeating-linear-gradient(45deg, rgb(226 226 226), #ffffff 8px)',
                }}
              >
                <div className={mapstyles.allTime}>
                  {/* {(item.timeList || []).map(function (titem: string, tindex: number) {
                  return <span key={tindex + 'time'}>{titem},</span>;
                })} */}
                  {item.showTimeList && item.showTimeList.length > 1 && (
                    <Popover
                      content={(item.showTimeList || []).map((timeItem, index) => {
                        return (
                          <div key={'time' + index}>
                            {timeItem[0]}-{timeItem[1]}
                          </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 == 1 && (
                    <span>{item.showTimeStr}</span>
                  )}
                </div>
                <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>
    </>
  );
};
export default Runtime;
