import React, { useState, useEffect, useCallback } from 'react';
import { FormattedMessage, useModel } from 'umi';

import SearchInput from '@/components/SearchInput';
import PageHeader from '@/components/PageHeader';
import Map from '@/components/map';
import TopNavigator from '@/components/topNavigator';
import TopNavRight from './components/topNavRight';
import DeviceModal from './components/deviceModal';

import styles from './index.less';
import mapstyles from '@/assets/css/map.less';
import { Spin, Modal, message } from 'antd';
import moment from 'moment';

import { ExclamationCircleOutlined } from '@ant-design/icons';
import { equipImageMap } from '@/config/image.js';
import Icon from '@/tenants-ui/Icon';
import type { navigatorItem } from '@/pages/Environment/index';
import {
  getMapList,
  queryEquipStatistics,
  queryDeviceTimeManage,
} from '@/services/ant-design-pro/environment';
import { getFeedbackDocumentsHttp, changeAirHttp } from '@/services/ant-design-pro/equipment';

//设备状态
type equipStatus = {
  equipType: string;
  status: number;
};
//设备开启数量
type statistics = {
  equipType: string;
  runCount: number;
};
const Environment: React.FC = () => {
  const { getSpaceFunc, projectId } = useModel('spaceFunc');
  const { changeSearchFloorId } = useModel('buildFloor');
  const { envir_all, equip_air, equip_lamp, envir_curtain } = equipImageMap;

  const [searchText, setSearchText] = useState<{ text: any }>();
  //const [searchSpace, setSearchSpace] = useState<{}>();
  //   const [searchFloorId, setSearchFloorId] = useState<{}>();
  //   const [searchBuildId, setSearchBuildId] = useState<{}>();
  const [showModal, setShowModal] = useState<boolean>(false);
  const [showSpace, setShowSpace] = useState<API.MapInfo>({}); //当前弹框选中的空间
  const [navigatorList, setNavigatorList] = useState<navigatorItem[]>([
    {
      name: '全部设备',
      id: 'all',
      src: envir_all,
      //color: '#E5574F',
      color: '#E89E32',
      colorStr: '',
    },
    {
      name: '空调',
      id: 'airConditioner',
      src: equip_air,
      num: 0,
      color: '#5E8BCF',
      colorStr: '94,139,207,',
    },
    {
      name: '照明',
      id: 'light',
      src: equip_lamp,
      num: 0,
      color: '#FFE823',
      colorStr: '255,232,35,',
    },
    {
      name: '窗帘',
      id: 'curtain',
      src: envir_curtain,
      num: 0,
      color: '#E89E32',
      colorStr: '232, 158, 50,',
    },
  ]);
  const [mapList, setMapList] = useState<API.MapInfo[]>([]);
  const [equipMapList, setEquipMapList] = useState<any[]>([]);
  const [timeMapList, setTimeMapList] = useState<any[]>([]);
  const [selNav, setSelNav] = useState<navigatorItem>(navigatorList[0]);
  const [selFloorId, setSelFloorId] = useState<string>();
  const [mapCombineList, setMapCombineList] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const changeFloorId = (data: string) => {
    //debugger;
    setSelFloorId(data);
  };
  //导航条切换
  const navigatorChange = (item: navigatorItem) => {
    //debugger;
    setSelNav(item);
  };
  const showModalClick = (item) => {
    console.log('showChart');
    setShowModal(true);
    setShowSpace(item);
  };

  //当前设备的状态 all全部开启 part部分开启 close全都关闭  还有类型type 包括airConditioner light curtain
  //根据设备状态返回不同的 颜色
  const getColorOpacity = (value: number, type?: string): string => {
    //debugger;
    let colorStr = '';
    if (selNav.id == 'all') {
      //全部设备时 colorStr赋值
      var filterRes = navigatorList.filter(function (item) {
        return item.id == type;
      });
      colorStr = (filterRes[0] || {}).colorStr;
    } else {
      colorStr = selNav.colorStr;
    }
    if (value == 2) {
      //2 是部分开启
      return 'rgba(' + colorStr + '0.4)';
    } else if (value == 1) {
      //1 是开启
      return 'rgba(' + colorStr + '1)';
    } else {
      //0是关闭
      return 'rgba(196, 196, 196, 0.6)';
    }
  };
  const { confirm } = Modal;
  //空调的调节      0是关闭 1 是开启  2 是部分开启
  //这是存在疑惑 部分开启怎么办
  const changeAir = (sitem, index: number) => {
    const itemId = sitem.airConditioner === 0 ? 12 : 10; // 10关闭 12开启
    const paramsObj = {
      objectId: sitem.id, // 空间id
      valueType: 1, // 固定为1 1
      itemId: itemId,
    };
    changeAirHttp(paramsObj).then((res) => {
      if (res.result == 'success') {
        message.success('指令下发成功');
        // sitem.airConditioner = res.isClose ? 0 : 1; //改变某空间空调的状态
        //mapCombineList[index]['airConditioner'] = res.isClose ? 0 : 1;
        var mapCopy = JSON.parse(JSON.stringify(mapCombineList));
        mapCopy[index]['airConditioner'] = res.isClose ? 0 : 1;
        setMapCombineList(mapCopy);
      } else {
        message.error('操作失败，请重试');
      }
    });
  };

  //单个空间的点击事情
  const spaceControl = (item, index: number) => {
    if (selNav.id == 'all' || !item.roomFuncType) return;
    var status = item[selNav.id] === 0 ? '打开' : '关闭';
    confirm({
      title: '请确认',
      icon: <ExclamationCircleOutlined />,
      content: `确认${status}该${selNav.name}吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        //如果是空调
        if (selNav.id == 'airConditioner') {
          changeAir(item, index);
        }
        if (selNav.id == 'light') {
        }
        if (selNav.id == 'curtain') {
        }
        debugger;
      },
      onCancel() {
        //console.log('Cancel');
      },
    });
  };
  //获取地图 mapList
  useEffect(() => {
    //changeSearchFloorId('');
    if (selFloorId) {
      debugger;
      setLoading(true);
      getMapList({
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        floorId: selFloorId,
      })
        .then((res) => {
          //debugger;
          setLoading(false);
          var data: API.MapInfo[] = (res.data || {}).spaceList || [];
          setMapList(data);
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      setMapList([]);
    }
  }, [selFloorId]);
  //获取设备状态 设备种类
  useEffect(() => {
    if (selFloorId) {
      //setLoading(true);
      queryEquipStatistics({
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        floorId: selFloorId,
        projectId: projectId,
      })
        .then((res) => {
          debugger;
          // setLoading(false);
          var statistics = res.data.statistics || [];
          //赋值 运行中的设备数量
          navigatorList.forEach(function (nItem) {
            var fres = statistics.filter((sItem: statistics) => {
              return sItem.equipType == nItem.id;
            });
            nItem.num = (fres[0] || {}).runCount;
          });

          setNavigatorList(navigatorList);

          //设备空间信息
          var spaceList = res.data.spaceList || [];
          spaceList.forEach((item: any) => {
            //debugger;
            (item.equipStatusList || []).forEach((eItem: equipStatus) => {
              //debugger;
              item[eItem.equipType] = eItem.status;
            });
          });

          setEquipMapList(spaceList);
        })
        .catch(() => {
          // setLoading(false);
        });
    }
  }, [selFloorId]);

  //获取时间列表 spaceTimeList
  useEffect(() => {
    if (selFloorId) {
      //setLoading(true);
      queryDeviceTimeManage({
        floorId: selFloorId,
        //floorId: 'Fl11010802593241ec348ecb4148806b9034c8957454',
        date: moment().format('YYYYMMDD'),
      })
        .then(function (res) {
          //  setLoading(false);
          var resList = res.content || [];
          setTimeMapList(resList);
        })
        .catch(() => {
          // setLoading(false);
        });
    }
  }, [selFloorId]);

  //合并空间环境数据 和 空间数据
  useEffect(() => {
    var combineList: any = [];
    mapList.map(function (mitem) {
      var spaceId = mitem.spaceId;
      var filterSpace1 = equipMapList.filter((ele) => {
        return ele.id == spaceId;
      });
      var filterSpace2 = timeMapList.filter((ele) => {
        return ele.id == spaceId;
      });
      var combine = Object.assign({}, mitem, filterSpace1[0], filterSpace2[0]);

      combineList.push(combine);
    });
    //debugger;
    setMapCombineList(combineList);
    console.log('combine');
  }, [equipMapList, mapList, timeMapList]);

  let firtTime: number = 0;
  let lastTime: number = 0;
  return (
    <>
      <PageHeader
        title={<FormattedMessage id="menu.equipment" />}
        action={
          <SearchInput
            mapList={mapList}
            callbackSearch={(s) => {
              //触发了搜索 如果楼层改变 重新更新地图
              debugger;
              //setSelFloorId(s.floorId); //一个建筑 搜索其他楼层
              setSearchText({ text: s.localName });
            }}
          />
        }
      />
      <TopNavigator
        navigatorList={navigatorList}
        type={'equipment'}
        navigatorChange={navigatorChange}
        action={
          <TopNavRight
            selNavObj={selNav}
            navigatorList={navigatorList}
            mapList={mapCombineList}
          ></TopNavRight>
        }
        changeFloorId={changeFloorId}
        selParamObj={selNav}
      ></TopNavigator>
      <div className={styles.maptop}>
        {selNav.id !== 'all' && (
          <div className={styles.right}>
            <div>
              <span
                className={styles.circle}
                style={{ backgroundColor: 'rgba(' + selNav.colorStr + '1)' }}
              ></span>
              <span>开启</span>
            </div>
            <div>
              <span
                className={styles.circle}
                style={{ backgroundColor: 'rgba(' + selNav.colorStr + '0.4)' }}
              ></span>
              <span>部分开启</span>
            </div>
            <div>
              <span
                className={styles.circle}
                style={{ backgroundColor: 'rgba(196, 196, 196, 0.6)' }}
              ></span>
              <span>关闭</span>
            </div>
          </div>
        )}
      </div>
      <Spin spinning={loading}>
        {mapCombineList.length > 0 && (
          <Map
            searchText={searchText}
            mapList={mapCombineList}
            type={'equipment'}
            render={(item, index) => {
              return (
                <div
                  key={index + item.id}
                  className={mapstyles.house}
                  style={{
                    left: item.left,
                    top: item.top,
                    width: item.width,
                    height: item.height,
                    background: item.roomFuncType
                      ? selNav.id == 'all'
                        ? 'rgba(196, 196, 196, 0.2)'
                        : getColorOpacity(item[selNav.id])
                      : 'repeating-linear-gradient(45deg, rgb(226 226 226), #ffffff 8px)',
                  }}
                  onClick={(event) => {
                    event.stopPropagation();
                    if (lastTime - firtTime < 300) {
                      spaceControl(item, index);
                    }
                  }}
                  onMouseDown={(event) => {
                    //event.stopPropagation();
                    firtTime = new Date().getTime();
                  }}
                  onMouseUp={(event) => {
                    //event.stopPropagation();
                    lastTime = new Date().getTime();
                  }}
                >
                  {selNav.id == 'all' && (
                    <div className={mapstyles.allDevice}>
                      {/* 所有设备的图标列表 */}
                      {(item.equipStatusList || []).map((ditem: equipStatus, dindex: number) => {
                        return (
                          <div
                            key={dindex + 'device'}
                            className={mapstyles.icon}
                            style={{
                              backgroundColor: getColorOpacity(ditem.status, ditem.equipType),
                            }}
                          >
                            <Icon
                              className=""
                              type={ditem.equipType}
                              style={{ color: '#ffffff', fontWeight: 'bold' }}
                            ></Icon>
                          </div>
                        );
                      })}
                    </div>
                  )}
                  {item.roomFuncType && (
                    <div
                      className={mapstyles.showModal}
                      onClick={(event) => {
                        event.stopPropagation();
                        if (lastTime - firtTime < 300) {
                          showModalClick(item);
                        }
                      }}
                      onMouseDown={(event) => {
                        //event.stopPropagation();
                        firtTime = new Date().getTime();
                      }}
                      onMouseUp={(event) => {
                        //event.stopPropagation();
                        lastTime = new Date().getTime();
                      }}
                    >
                      <Icon className="" type="hover"></Icon>
                    </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>
      {showModal && (
        <DeviceModal
          showSpace={showSpace}
          onClose={() => {
            setShowModal(true);
          }}
        ></DeviceModal>
      )}
    </>
  );
};

export default Environment;
