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/image.js';
import AnSwitch from '../anSwitch';
import { getLampHttp, getStatusHttp } from '@/services/ant-design-pro/equipment';
const { lamp_open, lamp_close, expend_down, expend_up } = equipImageMap;
export default () => {
  const [isMore, setIsMore] = useState(false);
  const [isOpen, setIsOpen] = useState(false); // 12 开， 10关
  const [lampArr, setLampArr] = useState([]); // 12 开， 10关
  const startTime = null;
  const endTime = null;
  const startLightsStatusTimer = useRef(null);
  const getLamp = () => {
    // startLightsStatusTimer.current = setInterval(() => {
    getLampHttp('Sp1101080259c4434730d12144ba890fe11f796d3143').then((res) => {
      const arr = res.content;
      if (arr.length > 1) setIsMore(true);
      arr.forEach((item) => {
        if (item.runStatus) setIsOpen(true);
      });
      setLampArr(arr);
    });
    // }, 1000);
  };

  useEffect(() => {
    getLamp(); // 灯设备状态
  }, []);

  const [flagSvg, setFlagSvg] = useState(false);
  function handleExpend() {
    clearInterval(startLightsStatusTimer.current);
    setFlagSvg(!flagSvg);
  }
  // 定时调用 查询指令接口
  const checkChangeLightStatusSuccess = (paramsArr) => {
    if (endTime - startTime >= 5000) {
      //   wx.hideLoading();
      message.error('网络故障，请重试');
    } else {
      getStatusHttp(paramsArr).then((res) => {
        return judgeChangeResponeseSuccess(res);
      });
    }
  };
  //   检查开关指令下发状态
  const judgeChangeResponeseSuccess = (response) => {
    return new Promise((resolve, reject) => {
      let result = response.content[0];
      if (result.result === 'success') {
        if (result.state === 200 && result.exeResult === 'success') {
          resolve({ status: 'success', data: result });
        } else if (result.exeResult === 'processing:rcvd' || result.state === 202) {
          resolve({ status: 'processing', data: result });
        } else {
        }
      } else {
        console.log('judgeChangeResponeseSuccess-fail');
      }
    });
  };
  //  开关
  const changeSwitch = (val, type, id) => {
    let paramsArr = [];
    if (type == 'total') {
      lampArr.forEach((item) => {
        paramsArr.push({
          id: item.id,
          switch: val,
        });
      });
    } else {
      paramsArr.push({ id: id, switch: val });
    }
    console.log(paramsArr, 'paramsArr');
    setallLampHttp(paramsArr)
      .then((res) => {
        startTime = Date.now(); // 开始计时'
        clearInterval(startLightsStatusTimer.current); // 灯设备
        return judgeChangeResponeseSuccess(res, paramsArr);
      })
      .then(
        (res) => {
          switch (res.status) {
            case 'success':
              getLamp();
            case 'processing':
              // 继续查询
              //   wx.showLoading({
              //     title: '加载中...',
              //     mark: true,
              //   });
              endTime = Date.now();
              checkChangeLightStatusSuccess(paramsArr);
              break;
          }
        },
        () => {
          message.error('操作失败，请重试');
        },
      );
  };

  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>
  );
};
