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 {
  changeManualTempHttp,
  querySapceFloorHeating,
} from '@/services/sagacare_service/equipment';
import { setallLamps } from '@/pages/Equipment/checLampStatus.js';
import Request from 'umi-request';
import cx from 'classnames';
import Slider from '../Slider';
import HeatModal from './heatModal';
import HeatButton from './heatButton';
const { expend_down, expend_up, icon_adjust, heatopen, heatclose } = equipImageMap;

export default ({ spaceId }) => {
  const [isAll, setIsAll] = useState(true);
  const changeIsAll = () => {
    setIsAll(!isAll);
  };

  const [minValue, setMinValue] = useState();
  const [maxValue, setMaxValue] = useState();
  const [tempSet, setTempSet] = useState();
  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([]);

  let startLightsStatusTimer = useRef(null);
  let divBox = useRef(null);
  const CancelToken = Request.CancelToken;
  const { token, cancel } = CancelToken.source();
  const [startTime, setStartTime] = useState(0);

  const getHeat = () => {
    //'Sp1101080259308f5ed92e964bc1b029038dea962de4'
    querySapceFloorHeating({ spaceId: spaceId }).then(
      (res) => {
        const resData = res.data || {};

        if (!divBox.current) return;
        const arr = resData.equipList || [];
        arr.forEach((item) => {
          item.minTempSet = resData.minTempSet || 25;
          item.maxTempSet = resData.maxTempSet || 25;
        });
      
        setMinValue(resData.minTempSet || 25);
        setMaxValue(resData.maxTempSet || 36);
        setIsOpen(resData.runStatus == 1 ? true : false);
        setLampArr(arr);
        setTempSet(resData.tempSet); //todo

        // getLampTimer();
      },
      (e) => {
        if (Request.isCancel(e)) {
          console.log('Request canceled', e);
        }
        // getLampTimer();
      },
    );
  };

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

  useEffect(() => {
    getHeat();
    return () => {
      cancel && cancel();
      clearTimeout(startLightsStatusTimer.current);
    };
  }, [spaceId]);

  const [flagSvg, setFlagSvg] = useState(false);
  function handleExpend() {
    setFlagSvg(!flagSvg);
  }
  const changeSwitch = (val, type, hItem) => {
    //  开关操作
    clearTimeout(startLightsStatusTimer.current);
    let paramsArr = [];
    if (type == 'total') {
      setIsOpen(val); // 总开关
      lampArr.forEach((item) => {
        item.runStatus = val;
        paramsArr.push({
          id: item.id,
          code: item.switchCode,
          value: val ? 1 : 0,
        });
      });
    } else {
      var oneTrue = false;
      lampArr.forEach((item) => {
        if (item.id == hItem.id) {
          item.runStatus = val;
        }
        if (item.runStatus) {
          oneTrue = true;
        }
      });

      if (oneTrue) {
        setIsOpen(true); // 总开关
      } else {
        setIsOpen(false); // 总开关
      }

      paramsArr.push({ id: hItem.id, code: hItem.switchCode, value: val ? 1 : 0 });
    }

    setTimeout(() => {
      setLampArr([...lampArr]);
    }, 500);
    console.log('开关请求参数', paramsArr);
    // changeManualTempHttp(paramsArr).then((res) => {
    //   getHeat(); //todo
    // });
  };

  const showColourModal = useCallback((item) => {
    if (!item.runStatus) return;
    setColourFlag(true);
    setColourObj(item);
  }, []);
  const hideColour = useCallback(() => {
    setColourFlag(false);
  }, []);
  // 滑动
  const silderVal = (obj) => {
    console.log('silderval', obj);
    const endTime = Date.parse(new Date());
    const dx = endTime - startTime;
    if (dx === 1000) {
      setStartTime(endTime);
      setHeatOrder(obj);
    }
  };
  // 滑动开始
  const mouseStart = () => {
    let nowTime = Date.parse(new Date());
    setStartTime(nowTime);
  };
  // 滑动停止
  const mouseEnd = (obj) => {
    console.log('mouseEnd', obj);
    setHeatOrder(obj);
  };
  const setHeatOrder = (vobj) => {
    var paramsArr = [];
    lampArr.forEach((item) => {
      paramsArr.push({
        id: item.id,
        code: item.tempSetCode,
        value: vobj.value,
      });
    });
    console.log('温度请求参数', paramsArr);
    // changeManualTempHttp(paramsArr).then((res) => {
    //   getHeat(); //todo
    // });
  };
  return (
    <div className={commonStyles.box} ref={divBox}>
      <div className={cx(commonStyles.content, `heatContent`)}>
        <div className="env">
          <div className="envLeft">
            <div className="eqTitle">地暖</div>
            <div className="eqStatus">
              <span>
                {tempSet ? tempSet : '--'}
                <sup className="unite">℃</sup>
              </span>
            </div>
            {lampArr.length > 1 && (
              <div className="showAll">
                <HeatButton changeIsAll={changeIsAll} isAll={isAll}></HeatButton>
              </div>
            )}
          </div>
          <div className="envRight">
            <img className="roomEqImg" src={isOpen ? heatopen : heatclose} />
          </div>
          <div
            className="eqBtn"
            onClick={() => {
              changeSwitch(!isOpen, 'total');
            }}
          >
            <AnSwitch isOpen={isOpen} />
          </div>
        </div>
        {isAll && isOpen && (
          <div className="sliderBox">
            <Slider
              onlyLine={true}
              typeValue={tempSet || minValue}
              minValue={minValue}
              maxValue={maxValue}
              type={'underfloorHeat'}
              silderPercentValue={silderVal}
              silderMouseEnd={mouseEnd}
              silderMouseStart={mouseStart}
            ></Slider>
          </div>
        )}
        {!isAll && lampArr.length > 1 && (
          <div className="lamp-item">
            {lampArr.map((item, index) => {
              return (
                <div className="item-box" key={'lamp' + index}>
                  <div className="small-img-card">
                    <div className="value">
                      {item.tempSet ? item.tempSet : '--'}
                      <sup className="unite">℃</sup>
                    </div>
                    <div className="status">{item.runStatus == 1 ? '已开启' : '已关闭'}</div>
                  </div>
                  <div
                    className="small-sw-card"
                    onClick={() => {
                      changeSwitch(!item.runStatus, 'child', item);
                    }}
                  >
                    <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>
                    <div
                      className={`adjustBox ${item.runStatus ? 'adjustActive' : ''}`}
                      onClick={() => {
                        showColourModal(item);
                      }}
                    >
                      <img className="iconAdjust" src={icon_adjust} />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
      {colourFlag && <HeatModal hideColour={hideColour} colourObj={colourObj}></HeatModal>}
    </div>
  );
};
