import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Row, Col } from 'antd';
import Icon from '@/tenants-ui/Icon';
import styles from './index.less';
import { equipImageMap } from '@/config/image.js';
import AirEq from './airEq';
import LampEq from './lampEq';
import CurtainEq from './curtainEq';
import { getSpaceAdjustList } from '@/services/ant-design-pro/equipment';
import { useRef } from 'react';

export default ({ onClose, showSpace }) => {
  const projectId = 'Pj1101080259';
  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, 1500],
          text: ['适宜', '偏高', '超标'],
        },
        pm25: {
          range: [35, 75],
          text: ['优', '良', '差'],
        },
        hcho: {
          range: [0.08, 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([]);
  let timer = useRef(null);
  console.log(showSpace, 'showSpace');
  function showEqCard(type) {
    let flag = false;
    showSpace.equipList.forEach((item) => {
      if (item.equipType === type) return (flag = true);
    });
    return flag;
  }

  const getData = () => {
    const paramsObj = {
      criteria: {
        spaceId: showSpace.id,
        projectId: projectId,
      },
      pubname: 'sagacareAndtenantslink',
      openid: '9a1ecfbacb6b4f249bf2dd3ec7793ead', // userId
    };
    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]) {
              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 {
              jtem.num = item[jtem.id];
            }
          });
          setParamList(envArr);
        });
    });
  };

  const operateTime = () => {
    // 使用时间
    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}`);
      }
    } else {
      // 会议时间
      showSpace.meetTime &&
        showSpace.meetTime.forEach((item) => {
          timeArr.push(`${item.meetTimeStartTime}-${item.meetTimeEndTime}`);
        });
      // 工作时间
      showSpace.workTimeStartTime &&
        timeArr.push(`${showSpace.workTimeStartTime}-${showSpace.workTimeEndTime}`);
    }

    // 加班时间
    showSpace.overTimeStartTime &&
      timeArr.push(`${showSpace.overTimeStartTime}-${showSpace.overTimeEndTime}`);

    if (timeArr.length == 0) timeArr = ['--'];
    return timeArr;
  };

  useEffect(() => {
    timer = setInterval(() => {
      getData();
    }, 1000 * 60 * 5);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <>
      <Modal width={810} visible maskClosable={false} closable={false} footer={null}>
        <div className={styles.main}>
          <div className={styles.header}>
            <div className={styles.show}>
              <div className={styles.tileline}>
                <img src={officeImg} className={styles.titleIcon}></img>
                <span>{showSpace.localName}</span>
              </div>
              <div className={styles.timeLine}>
                使用时间：
                {operateTime().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') && (
                  <Col span={12}>
                    <AirEq spaceId={showSpace.id} projectId={projectId}></AirEq>
                  </Col>
                )}
                {showEqCard('light') && (
                  <Col span={12}>
                    <LampEq spaceId={showSpace.id} projectId={projectId}></LampEq>
                  </Col>
                )}
                {showEqCard('curtain') && (
                  <Col span={12}>
                    <CurtainEq spaceId={showSpace.id} projectId={projectId}></CurtainEq>
                  </Col>
                )}
              </Row>
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};
