import React, { useState, useEffect, useCallback, useRef } from 'react';
import { message } from 'antd';
import styles from './index.less';
import commonStyles from '../common.less';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import AnSwitch from '../anSwitch';
import { getLampHttp, getStatusHttp, setallLampHttp } from '@/services/sagacare_service/equipment';
import { setallLamps } from '@/pages/Equipment/checLampStatus.js';
const { lamp_open, lamp_close, expend_down, expend_up } = equipImageMap;
export default ({ spaceId }) => {
  const [isMore, setIsMore] = useState(false);
  const [isOpen, setIsOpen] = useState(false); // 12 开， 10关
  const [lampArr, setLampArr] = useState([]);
  let startLightsStatusTimer = useRef(null);
  //   let waitSetResultFlag = useRef(false); // 等待开关接口
  const getLamp = useCallback(() => {
    getLampHttp(spaceId).then(
      (res) => {
        // if (res.result != 'success' && waitSetResultFlag.current) return;
        const arr = res.content || [];
        if (arr.length > 1) {
          setIsMore(true);
          let totalIsOpen = false;
          arr.forEach((item) => {
            if (item.runStatus) {
              totalIsOpen = true;
            }
          });
          setIsOpen(totalIsOpen);
        } else {
          arr.forEach((item) => {
            if (item.runStatus) {
              setIsOpen(true);
            } else {
              setIsOpen(false);
            }
          });
        }
        setLampArr(arr);
      },
      (e) => {},
    );
  }, []);

  function getLampTimer() {
    clearInterval(startLightsStatusTimer.current);
    startLightsStatusTimer.current = setInterval(() => {
      getLamp(); // 灯设备状态
    }, 3000);
  }

  useEffect(() => {
    getLamp();
    getLampTimer();
    return () => {
      clearInterval(startLightsStatusTimer.current);
    };
  }, []);

  const [flagSvg, setFlagSvg] = useState(false);
  function handleExpend() {
    setFlagSvg(!flagSvg);
  }
  const changeSwitch = (val, type, id) => {
    //  开关操作
    clearInterval(startLightsStatusTimer.current);
    let paramsArr = [];
    if (type == 'total') {
      lampArr.forEach((item) => {
        item.runStatus = val;
        paramsArr.push({
          id: item.id,
          switch: val,
        });
      });
    } else {
      lampArr.forEach((item) => {
        if (item.id == id) {
          item.runStatus = val;
        }
      });
      paramsArr.push({ id: id, switch: val });
    }
    lampArr.forEach((item) => {
      setIsOpen(item.runStatus); // 总开关
    });
    // waitSetResultFlag.current = true;
    setTimeout(() => {
      setLampArr([...lampArr]);
    }, 500);
    setallLampHttp(paramsArr).then((res) => {
      getLampTimer();
    });
    // setallLamps(paramsArr, getLamp, waitSetResultFlag);
  };
  return (
    <div className={commonStyles.box}>
      <div className={commonStyles.content}>
        <div className={commonStyles.env}>
          <div className={commonStyles.envLeft}>
            <span className={commonStyles.eqTitle}>{isMore ? '光照' : lampArr[0]?.localName}</span>
            <div className={`${commonStyles.eqStatus} ${commonStyles.pdt10}`}>
              <span>{isOpen ? '照明已开启' : '照明已关闭'}</span>
            </div>
            {isMore && (
              <div className={commonStyles.showAll} onClick={handleExpend}>
                <img className={commonStyles.showImg} src={flagSvg ? expend_up : expend_down}></img>
                <div className={commonStyles.showAllText}>显示全部</div>
              </div>
            )}
          </div>
          <div className={commonStyles.envRight}>
            <img className={commonStyles.roomEqImg} src={isOpen ? lamp_open : lamp_close} />
          </div>
          {!flagSvg && (
            <div
              className={commonStyles.eqBtn}
              onClick={() => {
                changeSwitch(!isOpen, 'total');
              }}
            >
              <AnSwitch isOpen={isOpen} />
            </div>
          )}
        </div>
      </div>
      {lampArr.map((item, idx) => {
        if (flagSvg) {
          return (
            <div className={`${styles.lampChild} ${commonStyles.flexBetween}`} key={item.id}>
              <div className={commonStyles.eqTitle}>{item.localName}</div>
              <div
                onClick={() => {
                  changeSwitch(!item.runStatus, 'child', item.id);
                }}
              >
                <AnSwitch isOpen={item.runStatus}></AnSwitch>
              </div>
            </div>
          );
        }
      })}
    </div>
  );
};
