import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Row, Col } from 'antd';
import Draggable from 'react-draggable';
import Icon from '@/tenants-ui/SgIcon';
import styles from './index.less';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import AirEq from './airEq';
import AirEqHand from './airEqHand';
import LampEq from './lampEq';
import SocketEq from './socketEq';
import CurtainEq from './curtainEq';
import UnderfloorHeat from './underfloorHeat';

import { getSpaceAdjustList } from '@/services/sagacare_service/equipment';
import { useRef } from 'react';
import { useModel } from 'umi';
import { projectObj } from '@/config/api.js';

export default ({ onClose, showSpace, inTime }) => {
  const envArr = [
    {
      name: '温度',
      id: 'temperature',
      num: '0',
      describe: '--',
    },
    {
      name: 'CO₂',
      id: 'co2',
      num: '0',
      describe: '--',
    },
    {
      name: 'PM2.5',
      id: 'pm25',
      num: '0',
      describe: '--',
    },
    {
      name: '甲醛',
      id: 'hcho',
      num: '0',
      describe: '--',
    },
    {
      name: '湿度',
      id: 'humidity',
      num: '0',
      unit: '%',
      describe: '--',
    },
  ];
  const checkLevel = (value, name) => {
    if (value || value == 0) {
      let objList = {
        temperature: {
          range: [20, 24],
          text: ['偏冷', '舒适', '偏热'],
        },
        humidity: {
          range: [30, 70],
          text: ['干燥', '健康', '潮湿'],
        },
        co2: {
          range: [800, 1000, 1500],
          text: ['健康', '达标', '略高', '超标'],
        },
        pm25: {
          range: [35, 75, 115, 150, 250],
          text: ['健康', '良', '轻度污染', '中度污染', '重度污染', '严重污染'],
        },
        hcho: {
          range: [0.1],
          text: ['健康', '超标'],
        },
      };
      let sortArr = [value, ...objList[name].range].sort((a, b) => {
        return a - b;
      });

      let level = sortArr.findIndex((item) => item === value);
      let levelTxt = objList[name].text[level];
      return { level, levelTxt };
    } else {
      return { level: '--', levelTxt: '--' };
    }
  };
  const { officeImg } = equipImageMap;
  const [currentType, setCurrentType] = useState('3s');
  const [spaceName, setSpaceName] = useState('');
  const [paramList, setParamList] = useState([]);
  const [timeArr, setTimeArr] = useState([]);
  const [controlMode, setControlMode] = useState(0);

  let timer = useRef(null);
  function showEqCard(type) {
    let flag = false;
    showSpace.equipList &&
      showSpace.equipList.forEach((item) => {
        if (item.equipType === type) return (flag = true);
      });
    return flag;
  }

  const getData = () => {
    if (!showSpace.spaceId) return;
    const paramsObj = {
      criteria: {
        spaceId: showSpace.spaceId,
        projectId: projectObj.projectId,
      },
    };
    getSpaceAdjustList(paramsObj)
      .then((res) => {
        res.content &&
          res.content.forEach((item, idx) => {
            envArr.forEach((jtem, jdx) => {
              jtem.describe = checkLevel(item[jtem.id], jtem.id).levelTxt;
              if (!item[jtem.id] && item[jtem.id] != 0) {
                jtem.num = '--';
                return;
              }
              if (jtem.id == 'humidity') {
                jtem.num = item[jtem.id].toFixed(0);
              } else if (jtem.id == 'hcho') {
                jtem.num = item[jtem.id].toFixed(2);
              } else if (jtem.id == 'temperature') {
                jtem.num = item[jtem.id].toFixed(1);
              } else {
                jtem.num = item[jtem.id];
              }
            });

            setControlMode(item.controlMode);
            setParamList(envArr);
          });
      })
      .catch((err) => {});
  };

  const operateTime = useMemo(() => {
    // 使用时间
    let timeArr = [];

    // if (showSpace.meetTime && showSpace.workTimeStartTime) {
    //   let arr = [];
    //   const meetingArr = JSON.parse(JSON.stringify(showSpace.meetTime));

    //   let startBetween = false; // 会议时间是否跨在 工作头部
    //   let endBetween = false; // 会议时间是否跨在 工作尾部
    //   let workTimeStartTime = showSpace.workTimeStartTime; // 工作开始时间
    //   let workTimeEndTime = showSpace.workTimeEndTime; // 工作开始时间
    //   workTimeStartTime = workTimeStartTime.replace(':', '');
    //   workTimeEndTime = workTimeEndTime.replace(':', '');
    //   for (let i = meetingArr.length - 1; i >= 0; i--) {
    //     let element = meetingArr[i];
    //     let elementStartTime = element.meetTimeStartTime.replace(':', '');
    //     let elementEndTime = element.meetTimeEndTime.replace(':', '');
    //     if (elementEndTime > workTimeEndTime) {
    //       // 比较工作时间的尾巴
    //       if (elementStartTime > workTimeEndTime) {
    //         arr.unshift(elementEndTime);
    //         arr.unshift(elementStartTime);
    //       } else {
    //         arr.unshift(elementEndTime);
    //         endBetween = true;
    //       }
    //     }

    //     if (elementStartTime < workTimeStartTime) {
    //       // 比较工作时间的头
    //       if (elementEndTime < workTimeStartTime) {
    //         arr.unshift(elementEndTime);
    //         arr.unshift(elementStartTime);
    //       } else {
    //         arr.unshift(elementStartTime);
    //         startBetween = true;
    //       }
    //     }
    //   }
    //   if (!startBetween && endBetween) {
    //     // 尾巴交集
    //     arr.push(workTimeStartTime);
    //   }
    //   if (startBetween && !endBetween) {
    //     // 头部交集
    //     arr.push(workTimeEndTime);
    //   }
    //   if (!startBetween && !endBetween) {
    //     //无交集
    //     arr.push(workTimeStartTime);
    //     arr.push(workTimeEndTime);
    //   }
    //   arr = [...new Set(arr)].sort();
    //   for (let j = 0; j < arr.length; j += 2) {
    //     const element = arr[j].slice(0, 2) + ':' + arr[j].slice(2);
    //     const elemNext = arr[j + 1].slice(0, 2) + ':' + arr[j + 1].slice(2);
    //     timeArr.push(`${element}-${elemNext}`);
    //   }
    // }
    var runTimeStatus = '';
    // 会议时间
    showSpace.meetTime &&
      showSpace.meetTime.length > 0 &&
      (runTimeStatus = 'meetingBook') &&
      showSpace.meetTime.forEach((item) => {
        timeArr.push(`${item.meetTimeStartTime}-${item.meetTimeEndTime}`);
      });
    var workTime = '--';
    // 工作时间
    showSpace.workTimeStartTime &&
      (workTime = `${showSpace.workTimeStartTime}-${showSpace.workTimeEndTime}`);

    // 加班时间
    showSpace.overTime &&
      showSpace.overTime.length > 0 &&
      (runTimeStatus = 'overtimeWork') &&
      showSpace.overTime.forEach((item) => {
        timeArr.push(`${item.overTimeStartTime}-${item.overTimeEndTime}`);
      });

    //if (timeArr.length == 0) timeArr = ['--'];
    //debugger;
    return { workTime: workTime, runTimeStatus: runTimeStatus, timeArr: timeArr };
  }, [showSpace]);

  let divBox = useRef(null);
  useEffect(() => {
    getData();
    timer.current = setInterval(() => {
      divBox.current && getData();
    }, 1000 * 60 * 5);
    return () => {
      clearInterval(timer.current);
    };
  }, [showSpace]);
  //   拖拽
  const [disabled, setDisabled] = useState(false);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const draggleRef = useRef(null);

  const changeDrag = (data) => {
    console.log('xxx');
    setDisabled(data);
  };

  const onStart = (_event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();

    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
  return (
    <>
      <Modal
        width={810}
        open
        style={{
          width: '100%',
          cursor: 'move',
        }}
        maskClosable={false}
        closable={false}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
        footer={null}
      >
        <div
          className={styles.main}
          onClick={(event) => {
            event.stopPropagation();
            event.preventDefault();
          }}
          onMouseDown={(event) => {
            event.stopPropagation();
            event.preventDefault();
          }}
          ref={divBox}
        >
          <div className={styles.header}>
            <div className={styles.show}>
              <div className={styles.tileline}>
                <img src={officeImg} className={styles.titleIcon}></img>
                <span>{showSpace.localName}</span>
                {showSpace.isPassengerPass == true && (
                  <span className={styles.hasPerson}>
                    <Icon
                      className=""
                      type="youren"
                      style={{ color: '#CE9F27', marginRight: '2px', fontSize: '9px' }}
                    ></Icon>
                    有人
                  </span>
                )}
                {showSpace.isPassengerPass == false && (
                  <span className={styles.hasPerson}>
                    <Icon
                      className=""
                      type="wuren"
                      style={{ color: '#8B949E', marginRight: '2px', fontSize: '9px' }}
                    ></Icon>
                    无人
                  </span>
                )}
              </div>
              <div className={styles.timeLine}>
                <span className={styles.pdr10}>工作时间：{operateTime.workTime}</span>
                {operateTime.runTimeStatus == 'meetingBook'
                  ? '会议时间：'
                  : operateTime.runTimeStatus == 'overtimeWork'
                  ? '加班时间：'
                  : ''}
                {operateTime.timeArr.map((item, idx) => {
                  return (
                    <span className={styles.pdr10} key={idx}>
                      {item}
                    </span>
                  );
                })}
              </div>
            </div>
            <div className={styles.close} onClick={onClose}>
              <Icon type="close" />
            </div>
          </div>
          <div className={styles.content}>
            <div className={styles.infoList}>
              {paramList.map((item, index) => {
                return (
                  <div className={styles.item} key={'navc' + item.id}>
                    <div className={styles.title}>{item.name}</div>
                    <div className={styles.num}>
                      {item.num}
                      {item.unit}
                    </div>
                    <div className={styles.describe}>{item.describe}</div>
                  </div>
                );
              })}
            </div>
            <div className={styles.devices}>
              <Row gutter={[12, 18]}>
                {showEqCard('airConditioner') && controlMode == 0 && (
                  <Col span={12}>
                    <AirEq
                      spaceId={showSpace.spaceId}
                      projectId={projectObj.projectId}
                      inTime={inTime}
                    ></AirEq>
                  </Col>
                )}
                {showEqCard('airConditioner') && controlMode == 1 && (
                  <Col span={12}>
                    <AirEqHand
                      spaceId={showSpace.spaceId}
                      projectId={projectObj.projectId}
                      inTime={inTime}
                    ></AirEqHand>
                  </Col>
                )}
                {showEqCard('light') && (
                  <Col span={12}>
                    <LampEq spaceId={showSpace.spaceId} projectId={projectObj.projectId}></LampEq>
                  </Col>
                )}
                {showEqCard('floorHeating') && (
                  <Col span={12}>
                    <UnderfloorHeat
                      spaceId={showSpace.spaceId}
                      projectId={projectObj.projectId}
                    ></UnderfloorHeat>
                  </Col>
                )}
                {showEqCard('curtain') && (
                  <Col span={12}>
                    <CurtainEq
                      spaceId={showSpace.spaceId}
                      projectId={projectObj.projectId}
                    ></CurtainEq>
                  </Col>
                )}
                {showEqCard('socket') && (
                  <Col span={12}>
                    <SocketEq
                      spaceId={showSpace.spaceId}
                      projectId={projectObj.projectId}
                    ></SocketEq>
                  </Col>
                )}
              </Row>
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};
