import React, { useState, useEffect, useRef, useCallback } from 'react';
import styles from './index.less';
import commonStyles from '../common.less';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import AnSwitch from '../anSwitch';
import { getSocketHttp, setSocketHttp } from '@/services/sagacare_service/equipment';
import ControlButton from './controlButton';

const { socket_close, socket_open, expend_down, expend_up } = equipImageMap;

export default ({ spaceId, projectId }) => {
  const [isMore, setIsMore] = useState(false); // 可以展开
  const [flagSvg, setFlagSvg] = useState(false); // 箭头方向
  const [socketArr, setsocketArr] = useState([]); // 窗帘数据
  const [isOpen, setIsOpen] = useState(false); // 1 开， 10关
  const [isLoading, setIsLoading] = useState(false);
  let timer = useRef(null);
  let divBox = useRef(null);

  function handleExpend() {
    setFlagSvg(!flagSvg);
  }

  function changeSwitch(val, type, childItem) {
    let paramsArr = [];
    if (type === 'total') {
      setIsLoading(true);
      paramsArr = JSON.parse(JSON.stringify(socketArr));
      paramsArr.map((item) => {
        item.value = val ? 1 : 0;
        item.code = item.switchCode;
      });
    } else {
      paramsArr = [
        {
          value: val ? 1 : 0,
          code: childItem.switchCode,
          id: childItem.id,
        },
      ];
    }
    setSocketHttp(paramsArr).then((res) => {
      setIsLoading(false);
      timerGet();
    });
  }

  const getData = useCallback(() => {
    const params = {
      spaceId: spaceId,
      equipType: 'socket',
    };

    setIsLoading(false);
    getSocketHttp(params).then((res) => {
      if (!divBox.current) return;
      let arr = res.data.equipList || [];
      let flag = false;
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        // 有开 则总开
        if (item.runStatus) {
          setIsOpen(true);
          flag = true;
        }
      }
      if (arr.length > 1) {
        setIsMore(true);
      } else {
        setIsMore(false);
      }
      // 都没有开 则总关
      if (!flag) setIsOpen(false);
      setsocketArr(arr);
    });
  }, [spaceId]);

  function timerGet() {
    getData();
    clearInterval(timer.current);
    timer.current = null;
    timer.current = setInterval(() => {
      divBox.current && getData();
    }, 1000 * 8);
  }

  useEffect(() => {
    timerGet();
    return () => {
      clearInterval(timer.current);
      timer.current = null;
    };
  }, [spaceId]);

  return (
    <div className={commonStyles.box} ref={divBox}>
      <div className={commonStyles.content}>
        <div className={commonStyles.env}>
          <div className={commonStyles.envLeft}>
            <span className={commonStyles.eqTitle}>智能插座</span>
            <div className={`${commonStyles.eqStatus} ${commonStyles.pdt10}`}>
              <span>{isOpen ? '插座已开启' : '插座已关闭'}</span>
            </div>
            <div className={styles.controlButton}>
              {isMore && (
                <ControlButton changeIsAll={handleExpend} isAll={!flagSvg}></ControlButton>
              )}
            </div>
          </div>
          <div className={styles.imgPos}>
            <img className={styles.roomEqImg} src={isOpen ? socket_open : socket_close} />
          </div>
          {!flagSvg && (
            <div
              className={commonStyles.eqSocketBtn}
              onClick={() => {
                changeSwitch(!isOpen, 'total');
              }}
            >
              <AnSwitch isAir={true} isLoading={isLoading} isOpen={isOpen}></AnSwitch>
            </div>
          )}
        </div>
      </div>
      {socketArr.map((item, idx) => {
        if (flagSvg) {
          return (
            <div className={`${styles.lampChild} ${commonStyles.flexBetween}`} key={item.id}>
              <div className={commonStyles.eqTitle}>{item.localName}</div>
              <div
                className={commonStyles.dsflex}
                onClick={() => {
                  changeSwitch(!item.runStatus, 'child', item);
                }}
              >
                <AnSwitch isOpen={item.runStatus}></AnSwitch>
              </div>
            </div>
          );
        }
      })}
    </div>
  );
};
