import React, { useState, useEffect, useRef, useCallback } from 'react';
import { message, Spin, notification, Button } 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';
import { projectObj } from '@/config/api.js';

export default ({ spaceId, projectId, inTime }) => {
  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 });
  let divBox = useRef(null);

  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(() => {
      divBox.current && 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) => {
        if (!divBox.current) return;
        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;
      });
  }, [spaceId]);
  const key = 'warnnotification2';
  const btn = (
    <Button type="default" size="middle" onClick={() => notification.close(key)}>
      隐藏
    </Button>
  );
  const changeAir = useCallback(
    (itemId) => {
      if (!inTime && itemId == 12 && projectObj.projectId == 'Pj1101020007') {
        //开启
        setIsLoading(false);
        notification.warning({
          placement: 'top',
          key,
          message: '空调无法开启',
          description: '如需开启空调，请移步至环境控制小程序。选择空间”预约时间“后可开启空调。',
          top: 200,
          duration: 5,
          style: {
            width: 310,
          },
          maxCount: 2,
          btn,
          // rtl: true,
        });
        return;
      }
      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);
    };
  }, [spaceId]);

  return (
    <div className={styles.box} ref={divBox}>
      <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>
  );
};
