import React, { useState, useEffect, useCallback, useRef } from 'react';
import commonStyles from '../common.less';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import { setEquipeHttp } from '@/services/sagacare_service/equipment';

const { curtain_close_icon_row, curtain_open_icon_row } = equipImageMap;

export default ({
  id,
  isTotal,
  preTime,
  changePreTime,
  changeCurtainTex,
  curtainArr,
  projectId,
}) => {
  const [downFlag, setDownFlag] = useState(false);
  const [upFlag, setUpFlag] = useState(false);
  const [count, setCount] = useState();
  let setTimer = useRef(null);
  const sendData = (setType, id) => {
    let arr = [];
    if (isTotal) {
      curtainArr.forEach((item) => {
        arr.push({
          equipmentCategory: 'CFSSES',
          infoCode: setType,
          value: 1,
          objectId: item.id,
        });
      });
    } else {
      const params = {
        projectId: projectId,
        objectId: id, // 设备ID/窗帘组ID
        equipmentCategory: 'CFSSES', // 设备编码 窗帘：CFSSES
        infoCode: setType, // 窗帘开设定：EquipOnSet 窗帘关设定：EquipOffSet
        value: 1, // 窗帘 1 移动/停止
      };
      arr.push(params);
    }
    return arr;
  };
  const handleCurtain = (setType, id, index) => {
    const nowTime = Date.now();
    if (nowTime - preTime <= 2000) return; // 请求间隔 2秒
    changePreTime(Date.now());
    const paramsArr = sendData(setType, id);
    setEquipeHttp(paramsArr);
    if (setType == 'EquipOffSet') {
      setDownFlag(true);
      setUpFlag(false);
    } else {
      setUpFlag(true);
      setDownFlag(false);
    }
    setCount(2);
    setTimer.current = setInterval(() => {
      setCount((count) => {
        return count - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    if (count == 2) changeCurtainTex('指令下发中…');
    if (count == 1) changeCurtainTex('再次点击停止窗帘');
    if (count === 0) {
      changeCurtainTex('');
      setDownFlag(false);
      setUpFlag(false);
      clearInterval(setTimer.current);
    }
  }, [count]);
  return (
    <>
      <div
        onClick={() => {
          handleCurtain('EquipOffSet', id, 1);
        }}
        className={`${commonStyles.circulBtn} ${commonStyles.mgr20} ${
          downFlag ? commonStyles.yell : ''
        }`}
      >
        {downFlag && <div>{count}</div>}
        {!downFlag && <img className={commonStyles.btnIcon} src={curtain_close_icon_row}></img>}
      </div>

      <div
        onClick={() => {
          handleCurtain('EquipOnSet', id, 2);
        }}
        className={`${commonStyles.circulBtn}  ${upFlag ? commonStyles.yell : ''}`}
      >
        {upFlag && <div>{count}</div>}
        {!upFlag && <img className={commonStyles.btnIcon} src={curtain_open_icon_row}></img>}
      </div>
    </>
  );
};
