import React, { useState, useEffect, useRef, useCallback } from 'react';
import { message, Spin } from 'antd';
import styles from './index.less';
import commonStyles from '../common.less';
import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import AnSwitch from '../anSwitch';
import { getFeedbackDocumentsHttp, changeAirHttp } from '@/services/sagacare_service/equipment';
import { LoadingOutlined } from '@ant-design/icons';

export default ({ spaceId, projectId }) => {
  const {
    airOpen,
    airClose,
    temp_down,
    temp_up,
    temp_keep,
    arrow_down,
    arrow_up,
    wind_up,
    wind_down,
  } = equipImageMap;
  const hasAir = true;
  let isNowAirStatus = useRef('');
  let firstLoading = useRef(true);
  let [isOpen, setIsOpen] = useState(false);
  let [isLoading, setIsLoading] = useState(false);
  const [imgSrc, setImgSrc] = useState(null);
  let timer = useRef(null);
  let airLoadingTimer = useRef(null);
  const [spaceStatus, setStatusText] = useState('null');
  let [changeLoading, setChangeLoading] = useState({ 4: false, 2: false, 5: false, 6: false });

  const airExpend = [
    {
      title: '温度调节',
      type: 'temp',
      downType: 4,
      upType: 2,
      leftImg: arrow_down,
      rightImg: arrow_up,
    },
    {
      title: '风量调节',
      type: 'wind',
      downType: 5,
      upType: 6,
      leftImg: wind_down,
      rightImg: wind_up,
    },
  ];
  const statusImg = (icon) => {
    switch (icon) {
      case 1:
        return setImgSrc(temp_keep);
        break;
      case 2:
        return setImgSrc(temp_down);
        break;
      case 3:
        return setImgSrc(temp_up);
        break;

      default:
        break;
    }
  };

  function timerGetAirInfo(timeLong) {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      getAirInfo(); // 获取空调状态
    }, timeLong);
  }

  function changeSwitch(val) {
    if (!isLoading) {
      setIsLoading(true);
      changeIsLoading(val);
      const itemIdSum = val ? 12 : 10; // 10关闭 12开启¬
      changeAir(itemIdSum);
    }
  }

  const changeIsLoading = (val) => {
    let countTimer = 0;
    airLoadingTimer.current = setInterval(() => {
      if (countTimer >= 30 || isNowAirStatus.current === val) {
        // setIsOpen(isNowAirStatus.current); // 开关
        setIsLoading(false);
        clearInterval(airLoadingTimer.current);
      } else {
        countTimer++;
      }
    }, 1000);
  };

  const getAirInfo = useCallback(() => {
    const paramsObj = {
      objectId: spaceId,
      projectId: projectId,
    };
    getFeedbackDocumentsHttp(paramsObj)
      .then((res) => {
        const val = res.icon == 7 ? false : true;
        if (firstLoading.current) {
          setIsLoading(false);
        }
        isNowAirStatus.current = val;
        setIsOpen(val); // 开关
        firstLoading.current = false;
        // setFirstLoading(false)
        timerGetAirInfo(3000);
        setStatusText(res.spaceStatus); // 状态文案
        statusImg(res.icon); // icon
      })
      .catch(() => {
        timerGetAirInfo(3000);
        firstLoading.current = false;
        // setIsLoading(false);
      });
  }, []);

  const changeAir = useCallback(
    (itemId) => {
      if (changeLoading[itemId]) {
        return;
      }
      const paramsObj = {
        objectId: spaceId, // 空间id
        valueType: 1, // 固定为1
        itemId: itemId,
      };

      // console.log('changeLoading', changeLoading);
      setChangeLoading({ ...changeLoading, [itemId]: true });
      changeAirHttp(paramsObj)
        .then((res) => {
          setChangeLoading({ ...changeLoading, [itemId]: false });
          if (res.result == 'success') {
            message.success('指令下发成功');
            // getAirInfo();
            // timerGetAirInfo(2000);
          } else {
            message.error('操作失败，请重试');
          }
        })
        .catch((err) => {
          setChangeLoading({ ...changeLoading, [itemId]: false });
        });
    },
    [changeLoading],
  );

  useEffect(() => {
    getAirInfo(); // 获取空调状态
    //timerGetAirInfo(2000);
    return () => {
      clearTimeout(timer.current);
    };
  }, []);

  return (
    <div className={styles.box}>
      <div className={styles.content}>
        <div className={styles.env}>
          <div className={styles.envLeft}>
            <span className={commonStyles.eqTitle}>空调</span>
            <div className={styles.airStatus}>
              <span className={styles.airStatusText}>{isOpen ? '空调已开启' : '空调已关闭'}</span>
              {isOpen && (
                <div className={styles.airStatusbox}>
                  <img className={styles.airStatusImg} src={imgSrc} />
                  <span className={styles.statusText}>{spaceStatus}</span>
                </div>
              )}
            </div>
          </div>
          <div className={styles.envRight}>
            <img className={styles.roomAirImg} src={isOpen ? airOpen : airClose} />
          </div>

          <div
            onClick={() => {
              changeSwitch(!isOpen);
            }}
            className={commonStyles.eqBtn}
          >
            <AnSwitch isOpen={isOpen} isAir={true} isLoading={isLoading} />
            {/*<Switch loading isOpen />*/}
          </div>
        </div>
      </div>
      {isOpen && (
        <div className={styles.expend}>
          {airExpend.map((items, idx) => {
            return (
              <div className={styles.item} key={idx}>
                <div>{items.title}</div>
                <div className={styles.itemRight}>
                  <div
                    className={styles.itemBg}
                    onClick={(e) => {
                      changeAir(items.downType);
                    }}
                  >
                    {changeLoading[items.downType] ? (
                      <Spin indicator={<LoadingOutlined style={{ fontSize: 20 }} spin />} />
                    ) : (
                      <img className={styles.itemImg} src={items.leftImg} />
                    )}
                  </div>
                  <div className={styles.itemBg} onClick={() => changeAir(items.upType)}>
                    {changeLoading[items.upType] ? (
                      <Spin indicator={<LoadingOutlined style={{ fontSize: 20 }} spin />} />
                    ) : (
                      <img className={styles.itemImg} src={items.rightImg} />
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};
