import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Row, Col } from 'antd';
import Icon from '@/tenants-ui/SgIcon';
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/sgservice/equipment';
import { useRef } from 'react';
import { useModel } from 'umi';
import { projectObj } from '@/config/api.js';

export default ({ onClose, showSpace }) => {
  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([]);
  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 = () => {
    const paramsObj = {
      criteria: {
        spaceId: showSpace.id,
        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];
            }
          });
          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(() => {
    getData();
    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={projectObj.projectId}></AirEq>
                  </Col>
                )}
                {showEqCard('light') && (
                  <Col span={12}>
                    <LampEq spaceId={showSpace.id} projectId={projectObj.projectId}></LampEq>
                  </Col>
                )}
                {showEqCard('curtain') && (
                  <Col span={12}>
                    <CurtainEq spaceId={showSpace.id} projectId={projectObj.projectId}></CurtainEq>
                  </Col>
                )}
              </Row>
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};
