import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { message, Modal } from 'antd';
import './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';
import LampColour from './lampColour';
import Request from 'umi-request';
import cx from 'classnames';

const {
  lamp_open,
  lamp_close,
  expend_down,
  expend_up,
  icon_adjust,
  lamp_small_open,
  atmLamp_small_close,
  atmLamp_small_open,
  lamp_small_close,
} = equipImageMap;

export default ({ spaceId }) => {
  const [isMore, setIsMore] = useState(false);
  const [isOpen, setIsOpen] = useState(false); // 12 开， 10关
  const [showLamps, setShowLamps] = useState(false);
  const [colourFlag, setColourFlag] = useState(false); //打开色温调节弹窗
  const [colourObj, setColourObj] = useState({});
  const [lampArr, setLampArr] = useState([]);
  //const [lampShowList, setlampShowList] = useState([]);
  let startLightsStatusTimer = useRef(null);
  let divBox = useRef(null);
  const CancelToken = Request.CancelToken;
  const { token, cancel } = CancelToken.source();

  const getLamp = () => {
    //console.log('spaceId111', spaceIdParam, spaceId, spaceIdRef.current);
    getLampHttp({ token: token, spaceId: spaceId }).then(
      (res) => {
        // if (res.result != 'success' && waitSetResultFlag.current) return;
        if (!divBox.current) return;
        //console.log('spaceId2222', spaceIdParam, spaceId, spaceIdRef.current);
        const arr = res.content || [];
        if (arr.length > 1) {
          setIsMore(true);
        }
        let totalIsOpen = false;
        arr.forEach((item) => {
          if (item.runStatus) {
            totalIsOpen = true;
          }
          if (item.lightType === 1) {
            if (item.runStatus) {
              item.lampImg = lamp_small_open;
            } else {
              item.lampImg = lamp_small_close;
            }
          } else {
            if (item.runStatus) {
              item.lampImg = atmLamp_small_open;
            } else {
              item.lampImg = atmLamp_small_close;
            }
          }
        });
        setIsOpen(totalIsOpen);
        setLampArr(arr);
        getLampTimer();
      },
      (e) => {
        if (Request.isCancel(e)) {
          console.log('Request canceled', e);
        }
        getLampTimer();
      },
    );
  };

  function getLampTimer() {
    clearTimeout(startLightsStatusTimer.current);
    startLightsStatusTimer.current = setTimeout(() => {
      divBox.current && getLamp(); // 灯设备状态
    }, 3000);
  }

  useEffect(() => {
    //console.log('spaceId33333', spaceId);
    //setLampArr([]);
    getLamp();
    return () => {
      //setLampArr([]);
      cancel && cancel();
      clearTimeout(startLightsStatusTimer.current);
    };
  }, [spaceId]);

  const [flagSvg, setFlagSvg] = useState(false);
  function handleExpend() {
    setFlagSvg(!flagSvg);
  }
  const changeSwitch = (val, type, id) => {
    //  开关操作
    clearTimeout(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) => {
      getLamp(); //todo
    });
  };

  const handleShow = () => {
    if (!lampArr.length) return;
    setShowLamps(!showLamps);
  };

  const lampShowList = useMemo(() => {
    let arr = [];
    const len = lampArr.length;
    if (len < 3) {
      arr = lampArr;
    } else {
      if (!showLamps) {
        arr.push(lampArr[0]);
        arr.push(lampArr[1]);
      } else {
        arr = lampArr;
      }
    }
    return arr;
  }, [showLamps, lampArr]);

  const showColourModal = useCallback((item) => {
    if (item?.runStatus) {
      setColourFlag(true);
      setColourObj(item);
    }
  }, []);
  const hideColour = useCallback(() => {
    setColourFlag(false);
  }, []);
  return (
    <div className={commonStyles.box} ref={divBox}>
      <div className={cx(commonStyles.content, `lampContent`)}>
        {lampArr.length == 1 && (
          <div className={commonStyles.env}>
            <div className={commonStyles.envLeft}>
              <span className={commonStyles.eqTitle}>{lampArr[0]?.localName}</span>
              <div className={`${commonStyles.eqStatus} ${commonStyles.pdt10}`}>
                <span>{isOpen ? '照明已开启' : '照明已关闭'}</span>
              </div>
              <div className="showAll">
                {(lampArr[0]?.bright || lampArr[0]?.colorTemperature) && (
                  <div
                    className={`adjustBox  bg ${lampArr[0]?.runStatus ? 'adjustActive' : ''}`}
                    style={{}}
                    onClick={() => {
                      showColourModal(lampArr[0]);
                    }}
                  >
                    <img className="iconAdjust" src={icon_adjust} />
                  </div>
                )}
              </div>
            </div>
            <div className={commonStyles.envRight}>
              <img className={commonStyles.roomEqImg} src={isOpen ? lamp_open : lamp_close} />
            </div>
            <div
              className={commonStyles.eqBtn}
              onClick={() => {
                changeSwitch(!isOpen, 'child', lampArr[0]?.id);
              }}
            >
              <AnSwitch isOpen={isOpen} />
            </div>
          </div>
        )}
        {lampArr.length > 1 && (
          <div className="lamp-basic">
            <div className="dplCenter" style={{ marginLeft: '30px', marginRight: '16px' }}>
              <div>
                <span className="lamp-basic-name">光照</span>
                <div className="lamp-status lamp-status-padding">
                  {isOpen ? '照明已开启' : '照明已关闭'}
                </div>
              </div>
              <div className="dplCenter">
                <div
                  className="all-btn"
                  onClick={() => {
                    changeSwitch(true, 'total');
                  }}
                >
                  <span className="btn-text">全开</span>
                </div>
                <div
                  className="all-btn"
                  onClick={() => {
                    changeSwitch(false, 'total');
                  }}
                >
                  <span className="btn-text">全关</span>
                </div>
              </div>
            </div>
            <div className="lamp-item">
              {lampShowList.map((item, index) => {
                return (
                  <div className="item-box" key={'lamp' + index}>
                    <div className="small-img-card">
                      <img
                        className="small-lamp-img"
                        src={
                          item.lightType === 1
                            ? item.runStatus
                              ? lamp_small_open
                              : lamp_small_close
                            : item.runStatus
                            ? atmLamp_small_open
                            : atmLamp_small_close
                        }
                      />
                    </div>
                    <div
                      className="small-sw-card"
                      onClick={() => {
                        changeSwitch(!item.runStatus, 'child', item.id);
                      }}
                    >
                      <AnSwitch isOpen={item.runStatus} isSmall={true}></AnSwitch>
                    </div>
                    <div
                      className="dplCenter"
                      style={{ paddingRight: '14px', paddingLeft: '16px' }}
                    >
                      <div className="lamp-basic-name">
                        <span>{item.localName}</span>
                      </div>
                      {(item.bright || item.colorTemperature) && (
                        <div
                          className={`adjustBox ${item.runStatus ? 'adjustActive' : ''}`}
                          onClick={() => {
                            showColourModal(item);
                          }}
                        >
                          <img className="iconAdjust" src={icon_adjust} />
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
            {lampArr.length > 2 && (
              <div
                className="lamp-spread"
                onClick={() => {
                  handleShow();
                }}
              >
                <img className="lamp-basic-allow" src={showLamps ? expend_up : expend_down} />
                <span className="lamp-status">{showLamps ? '收起' : '展开'}更多</span>
              </div>
            )}
          </div>
        )}
      </div>
      {colourFlag && <LampColour hideColour={hideColour} colourObj={colourObj}></LampColour>}
    </div>
  );
};
