import React, { useState, useEffect, useRef, useCallback } from 'react';
import { message, Spin, notification, Space, Button } from 'antd';
// import styles from './index.less';
// import cx from 'classnames';

import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import AnSwitch from '../anSwitch';
import {
  changeManualTempHttp,
  querySpaceConditioners,
} from '@/services/sagacare_service/equipment';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { projectObj } from '@/config/api.js';
import './index.less';
import Slider from '../Slider';
import AirModal from './airModal';
import ControlButton from './controlButton';

export default ({ spaceId, projectId, inTime }) => {
  const {
    up_Arrow,
    down_Arrow,
    openair,
    air_close,
    wind_small,
    wind_big,
    wind_auto,
    airsunred,
    airsunblack,
    aircoldblue,
    aircoldblack,
    aircloudgreen,
    aircloudblack,
    icon_adjust,
  } = equipImageMap;

  let [airTemp, setAirTemp] = useState();
  let [allAirShow, setAllAirShow] = useState(false);
  let baseMode = [
    {
      name: '温度',
      id: 'temp',
      selectArr: [],
      //sel: 0,
      //value: 25
    },
    {
      name: '档位',
      id: 'gear',
      selectArr: [0, 1, 2, 3, 'AUTO'],
    },
    {
      name: '模式',
      id: 'mode',
      selectArr: ['制冷', '制热', '通风'],
      refer: [
        { mid: 1, value: '制冷', sindex: 0 },
        { mid: 2, value: '制热', sindex: 1 },
        { mid: 3, value: '通风', sindex: 2 },
      ],
    },
  ];
  const windGearArr = [0, 1, 2, 3]; // 风量3/5个档位
  const [allDevices, setAllDevices] = useState([]);
  const [eqTitle, setEqTitle] = useState('空调');
  const [nowTemp, setNowTemp] = useState(18);
  const [allBoundPoint, setAllBoundPoint] = useState({});
  const [airMode, setAirMode] = useState(2); // 空调模式 总的  1=cold；2=hot 3=wind
  const [airGear, setAirGear] = useState(1); // 风量档位 总的
  const [isAutoGear, setIsAutoGear] = useState(0);
  const [airData, setAirData] = useState({ isOpen: false });

  const [movesign, setMovesign] = useState(false);
  const [startX, setStartX] = useState(0);
  const [transX, setTransX] = useState(0);
  const [tempBarWidth, setTempBarWidth] = useState(0);
  const [startTemp, setStartTemp] = useState(18);
  const [endTemp, setEndTemp] = useState(26);
  const infoTimer = useRef(null);
  let divBox = useRef(null);
  const [deviceObj, setDeviceObj] = useState({});
  const [modalFlag, setModalFlag] = useState(false); // 箭头方向

  function doTimeout() {
    clearInterval(infoTimer.current); // 定时器先清理 再设定
    infoTimer.current = setInterval(() => {
      divBox.current && getAirInfo();
    }, 15000);
  }

  // const doTransX = useCallback(
  //   (newVal) => {
  //     var tempNum = (endTemp - startTemp) * 2;
  //     var eachUnit = tempBarWidth / tempNum; //0.5度的长度
  //     var moveNum = Math.floor(newVal / eachUnit);
  //     var nowTemp2 = moveNum * 0.5 + startTemp;
  //     setNowTemp(nowTemp2);
  //     //console.log("this.nowTemp111",nowTemp2);
  //     return nowTemp2;
  //     // if (typeof this.nowTemp === 'number' && this.nowTemp % 1 === 0) {
  //     // this.vibrateShort();
  //     // }
  //   },
  //   [endTemp, startTemp, tempBarWidth],
  // );

  const barWidth = 17;
  var tempRef = useRef();
  function doTemp(newVal, maxTempSet, minTempSet) {
    //处理温度
    if (!newVal) return;
    var tBarWidth = (tempRef.current || {}).clientWidth || 0;
    var tBarHeight = (tempRef.current || {}).clientHeight || 0;

    tBarWidth = tBarWidth ? tBarWidth - barWidth : tBarWidth;
    var tempNum = (maxTempSet - minTempSet) * 2;

    var eachUnit = tBarWidth / tempNum; //0.5度的长度
    var changeNum = (newVal - minTempSet) * 2;

    var transX = eachUnit * changeNum;
    if (transX < 0) {
      // transX只能是正的
      transX = 0;
    }
    if (transX > tBarWidth) {
      transX = tBarWidth;
    }

    // console.log('tBarWidth', tBarWidth, newVal, maxTempSet, minTempSet);
    setTransX(transX);
    setTempBarWidth(tBarWidth);
  }

  function allAirClick() {
    getAirInfo();
    setAllAirShow(!allAirShow);
  }
  // function cmousedown(e) {
  //   if (!airData.isOpen) return;
  //   // if (!inTime) {
  //   //   showNotification();
  //   //   return;
  //   // }
  //   var pageX = e.pageX;
  //   setStartX(pageX);
  //   setMovesign(true);
  // }
  const key = 'warnnotification';
  const btn = (
    <Button type="default" size="middle" onClick={() => notification.close(key)}>
      隐藏
    </Button>
  );
  function showNotification() {
    notification.warning({
      placement: 'top',
      key,
      message: '空调无法开启',
      description: '如需开启空调，请移步至环境控制小程序。选择空间”预约时间“后可开启空调。',
      top: 200,
      duration: 5,
      style: {
        width: 310,
      },
      maxCount: 1,
      btn,
      // rtl: true,
    });
  }
  // function cbarclick(e) {
  //   if (!airData.isOpen) return;
  //   // if (!inTime) {
  //   //   showNotification();
  //   //   return;
  //   // }
  //   var pageX = Number(e.pageX); // 页面触点Y坐标
  //   var tempRefCurrent = tempRef.current || {};
  //   var tempDomLeft = tempRefCurrent.getBoundingClientRect().left || 0;
  //   var moveX = pageX - tempDomLeft - 8;

  //   var transX2 = moveX;

  //   if (transX2 < 0) {
  //     // transX只能是正的
  //     transX2 = 0;
  //   }
  //   if (transX2 > tempBarWidth) {
  //     transX2 = tempBarWidth;
  //   }

  //   setTransX(transX2);
  //   var tempVal = doTransX(transX2);
  //   changeZongAir('temp', tempVal);
  // }

  // function cmousemove(e) {
  //   if (!airData.isOpen || !movesign) return;
  //   var pageX = Number(e.pageX); // 页面触点Y坐标

  //   var moveX = pageX - startX;
  //   setStartX(pageX);

  //   var transX2 = transX + moveX;

  //   if (transX2 < 0) {
  //     // transX只能是正的
  //     transX2 = 0;
  //   }
  //   if (transX2 > tempBarWidth) {
  //     transX2 = tempBarWidth;
  //   }

  //   // console.log('touchmove', startX, transX2, tempBarWidth);
  //   setTransX(transX2);
  //   doTransX(transX2);
  // }

  // function cmouseup(e) {
  //   if (!airData.isOpen || !movesign) return;
  //   // 挪动到一定区域 则可以自己到固定位置
  //   setMovesign(false);
  //   changeZongAir('temp', nowTemp);
  // }

  function eachAirOpen(aindex) {
    var itemClone = { ...allDevices[aindex] };
    if (!inTime && !itemClone.open && projectObj.projectId == 'Pj1101020007') {
      //开启时
      showNotification();
      return;
    }
    //this.allDevices[aindex].open = !this.allDevices[aindex].open;

    itemClone.open = !itemClone.open;

    var value = itemClone.open ? 1 : 0;
    var devicesClone = [...allDevices];
    devicesClone[aindex] = itemClone;

    setAllDevices(devicesClone);
    changeOneAir(allDevices[aindex].id, allDevices[aindex].switchCode, value); //todo
  }

  function changeOneAir(id, code, value) {
    const paramArr = [
      {
        id: id,
        code: code,
        value: value,
      },
    ];
    //wx.showLoading();
    //  下达指令
    changeManualTempHttp(paramArr)
      .then((res) => {
        doTimeout();
      })
      .catch(() => {
        //wx.hideLoading();
      });
  }
  const debounceTimer = useRef(null);

  // function debounce(id, code, value) {
  //   clearTimeout(debounceTimer.current);

  //   debounceTimer.current = setTimeout(function () {
  //     changeOneAir(id, code, value);
  //   }, 500);
  // }

  // 空调信息airTemp
  function getAirInfo() {
    const paramObj = {
      projectId: projectId, //'Pj1101080255'
      spaceId: spaceId, //'Sp110108025564f438d7fef64eea8202a6462f1bbcce' //空间id
    };

    querySpaceConditioners(paramObj)
      .then((res) => {
        if (!divBox.current) return;
        var data = res.data || {};
        data.tempSet = data.tempSet;
        setAirTemp(data.tempSet);
        setNowTemp(data.tempSet);

        setAirMode(data.workMode);
        setAirGear(data.gear || 0);
        setIsAutoGear(data.isAutoGear);
        setAirData({ isOpen: data.runStatus ? true : false });
        setAllBoundPoint(data.boundPoint || {});

        var maxTempSet = data.maxTempSet;
        setEndTemp(data.maxTempSet);
        var minTempSet = data.minTempSet;
        setStartTemp(data.minTempSet);

        var tempArr = [];
        for (var i = minTempSet; i <= maxTempSet; i = i + 0.5) {
          tempArr.push(i);
        }

        baseMode[0].selectArr = tempArr;
        doTemp(data.tempSet, maxTempSet, minTempSet);
        var deviceArr = [];
        (data?.equipList || []).forEach((eitem) => {
          var deviceObj = {};
          deviceObj.id = eitem.id;
          deviceObj.name = eitem.localName;
          deviceObj.open = eitem.runStatus == 1 ? true : false;
          deviceObj.switchCode = eitem.switchCode;
          deviceObj.boundPoint = eitem.boundPoint || {};

          var allModel = JSON.parse(JSON.stringify(baseMode));
          //console.log('allModel', allModel);
          allModel.forEach((mitem) => {
            if (mitem.id == 'temp') {
              mitem.code = eitem.tempSetCode;
              deviceObj.nowTemp2 = eitem.tempSet;
              deviceObj.tempSet2 = eitem.tempSet;
              // var index = mitem.selectArr.findIndex((ele) => {
              //   return ele == eitem.tempSet;
              // });
              // mitem.sel = index == -1 ? 0 : index;
            }
            if (mitem.id == 'gear') {
              mitem.code = eitem.gearCode;
              deviceObj.airGear2 = eitem.gear || 0;
              deviceObj.isAutoGear2 = eitem.isAutoGear;

              // var index = mitem.selectArr.findIndex((ele) => {
              //   if (eitem.isAutoGear == 1) {
              //     return ele == 'AUTO';
              //   } else {
              //     return ele == eitem.gear;
              //   }
              // });
              // mitem.sel = index == -1 ? 0 : index;
            }
            if (mitem.id == 'mode') {
              mitem.code = eitem.modeSetCode;
              deviceObj.airMode2 = eitem.workMode;

              // var filterObj = mitem.refer.find((ele) => {
              //   return ele.mid == eitem.workMode;
              // });
              // mitem.sel = (filterObj || {}).sindex || 0;
            }
          });

          deviceObj.allModel = allModel;
          deviceArr.push(deviceObj);
        });

        setAllDevices(deviceArr);
      })
      .catch(() => {});
  }

  // function vibrateLong() {
  //     if (wx.canIUse('vibrateLong')) {
  //         wx.vibrateLong();
  //     } else {
  //         wx.vibrateShort();
  //     }
  // }
  // function vibrateShort() {
  //     if (wx.canIUse('vibrateShort')) {
  //         wx.vibrateShort();
  //     } else {
  //         wx.vibrateLong();
  //     }
  // }

  // checkAirCanOpen(itemId) { // 判断空调是否能开启
  //     if (!this.roomHasScene && !this.isNowTime) {
  //         wx.showToast({
  //             title: '大厦该时段无空调提供',
  //             icon: 'info',
  //             duration: 1000
  //         })
  //         return false;
  //     }
  //     if (itemId === 12) { // 12表示开空调
  //         console.log(this.isNowTime, 'this.isNowTime');
  //         if (this.roomHasScene && !this.isNowTime) {
  //             this.$emit('component-open-workTimePop');
  //             return false;
  //         }
  //     }
  //     return true;
  // }
  function changeZongAir(btnType, value) {
    if (!inTime && btnType == 'sw' && !airData.isOpen && projectObj.projectId == 'Pj1101020007') {
      showNotification();
      return;
    }
    if (!airData.isOpen && btnType != 'sw') return;

    // 如果是过渡季 并且ACATVA 空调  则不能调节温度 不能开
    // if (btnType == 'temp' && this.isACATVA && this.seasonType == 'Transition') {
    //     setTimeout(() => {
    //         wx.showToast({
    //             title: '目前为过渡季节，大厦无冷热水供应，空调无法调节',
    //             duration: 2600,
    //             icon: 'none'
    //         })
    //     }, 0);
    //     return;
    // }

    // 如果不是开关空调 显示弹窗
    // if (btnType != 'sw') {
    //     this.$emit('airShowVisible', {
    //         'toWhere': btnTypeDetail,
    //         'designTemperature': 0                    }
    //     );
    // }

    var nowairGear = airGear;
    var nowAutoGear = isAutoGear;
    if (btnType == 'gear' && value == 'windLow') {
      //降挡
      if (nowairGear > 1) {
        nowairGear = nowairGear - 1;
        setAirGear(nowairGear);
        nowAutoGear = 0;
        setIsAutoGear(nowAutoGear);
      } else {
        return;
      }
    }
    if (btnType == 'gear' && value == 'windUp') {
      //升档
      if (nowairGear < 3) {
        nowairGear = nowairGear + 1;
        setAirGear(nowairGear);
        nowAutoGear = 0;
        setIsAutoGear(nowAutoGear);
      } else {
        return;
      }
    }

    if (btnType == 'gear' && value == 'auto') {
      nowAutoGear = isAutoGear == 1 ? 0 : 1;
      setIsAutoGear(nowAutoGear);
    }
    if (btnType == 'mode') {
      setAirMode(value);
    }
    var nowOpen = airData.isOpen;
    if (btnType == 'sw') {
      nowOpen = !nowOpen;
      setAirData({ isOpen: nowOpen });
    }

    let paramArr = [];
    allDevices.forEach((dele) => {
      if (btnType == 'sw') {
        let paramObj = {
          id: dele.id,
          code: dele.switchCode,
          value: nowOpen ? 1 : 0,
        };
        paramArr.push(paramObj);
      }

      dele.allModel.forEach((mele) => {
        if (mele.id == 'temp') {
          var rval = value;
        } else if (mele.id == 'gear') {
          var rval = nowAutoGear == 1 ? 4 : nowairGear;
        } else if (mele.id == 'mode') {
          var rval = value;
        }
        if (mele.id == btnType) {
          let paramObj = {
            id: dele.id,
            code: mele.code,
            value: rval,
          };
          paramArr.push(paramObj);
        }
      });
    });

    //wx.showLoading();

    //  下达指令
    changeManualTempHttp(paramArr)
      .then((res) => {
        if (btnType == 'temp') {
          //_this.airTemp = _this.nowTemp;
          setAirTemp(value);
        }
        doTimeout();
      })
      .catch(() => {
        //wx.hideLoading();
      });
  }

  useEffect(() => {
    doTimeout();
    getAirInfo();
    return () => {
      clearInterval(infoTimer.current);
    };
  }, [spaceId]);

  // 滑动停止
  const mouseEnd = (obj) => {
    //debugger;
    changeZongAir('temp', obj.value);
  };
  const showModal = useCallback((item) => {
    if (!item.open) return;
    setModalFlag(true);
    setDeviceObj(item || {});
  }, []);

  const changeDeviceObj = (item) => {
    setDeviceObj(item);

    var devicesClone = [...allDevices];
    var aindex = devicesClone.findIndex((ele) => {
      return ele.id == item.id;
    });

    devicesClone[aindex] = item;
    setAllDevices(devicesClone);
  };
  const hideModal = useCallback(() => {
    setModalFlag(false);
  }, []);
  return (
    <div className="air-adjust office-card g-fl" ref={divBox}>
      <div className="air-content">
        <div className="air-adjust-env">
          <div className="air-text">
            <span className="envname">空调</span>
            <div className="envnum">
              {airTemp ? airTemp : '--'}
              <sup className="unit">℃</sup>
            </div>
          </div>
          <div className="air-show-all">
            {allDevices.length > 1 && (
              <ControlButton changeIsAll={allAirClick} isAll={!allAirShow}></ControlButton>
            )}
          </div>
        </div>
        <div className="air-adjust-btn">
          <img className="airImg" src={airData.isOpen ? openair : air_close} />
        </div>
        {!allAirShow && allBoundPoint.switchSetBound && (
          <div
            className="air-switch"
            onClick={() => {
              changeZongAir('sw');
            }}
          >
            <AnSwitch isOpen={airData.isOpen} isAir={true} />
          </div>
        )}
      </div>

      <div
        style={{
          visibility: !allAirShow && airData.isOpen ? 'visible' : 'hidden',
          height: !allAirShow && airData.isOpen ? 'auto' : 0,
        }}
      >
        {allBoundPoint.tempSetBound && (
          <div className="air-slider">
            <Slider
              onlyLine={true}
              typeValue={nowTemp || startTemp}
              minValue={startTemp}
              maxValue={endTemp}
              type={'air'}
              silderMouseEnd={mouseEnd}
            ></Slider>
          </div>
        )}
        {allBoundPoint.gearSetBound && (
          <div className="air-control-item item-flex ">
            <div className="air-control-item-box">
              <div className="envnum-common air-envnum-comon">
                {windGearArr.map(function (item, index) {
                  return (
                    <span
                      className={`envnum-common-wind ${item == airGear ? 'windBlack' : ''}`}
                      key={index + 'wind'}
                    >
                      {item}
                    </span>
                  );
                })}
              </div>
              <div className="air-common-text change-text">风量调节</div>
            </div>
            <div className="air-common-switch">
              <div
                className={`switch  ${airGear <= 1 || !airData.isOpen ? 'disabled' : ''}`}
                onClick={() => {
                  changeZongAir('gear', 'windLow');
                }}
              >
                <img className="wimg" src={wind_small} />
              </div>
              <div
                className={`switch ${airGear >= 3 || !airData.isOpen ? 'disabled' : ''}`}
                onClick={() => {
                  changeZongAir('gear', 'windUp');
                }}
              >
                <img className="wimg" src={wind_big} />
              </div>
              <div
                className={`switch ${isAutoGear == 1 ? 'yell' : ''} ${
                  !airData.isOpen ? 'disabled' : ''
                }`}
                onClick={() => {
                  changeZongAir('gear', 'auto');
                }}
              >
                <img className="wimg" src={wind_auto} />
              </div>
            </div>
          </div>
        )}
        {allBoundPoint.modeSetBound && (
          <div className="air-control-item item-flex">
            <div className="air-control-item-box">
              <div className="envnum-common air-envnum-comon">
                {airMode == 2 ? '制热' : airMode == 1 ? '制冷' : '通风'}
              </div>
              <div className="air-common-text change-text">模式设定</div>
            </div>
            <div className="air-common-switch">
              <div
                className={`switch ${airMode == 1 ? 'yell' : ''} ${
                  !airData.isOpen ? 'disabled' : ''
                }`}
                onClick={() => {
                  changeZongAir('mode', 1);
                }}
              >
                <img className="wimg" src={aircoldblack} />
              </div>
              <div
                className={`switch ${airMode == 2 ? 'yell' : ''} ${
                  !airData.isOpen ? 'disabled' : ''
                }`}
                onClick={() => {
                  changeZongAir('mode', 2);
                }}
              >
                <img className="wimg" src={airsunblack} />
              </div>
              <div
                className={`switch ${airMode == 3 ? 'yell' : ''} ${
                  !airData.isOpen ? 'disabled' : ''
                }`}
                onClick={() => {
                  changeZongAir('mode', 3);
                }}
              >
                <img className="wimg" src={aircloudblack} />
              </div>
            </div>
          </div>
        )}
      </div>

      {allAirShow && (
        <div className="allAir lamp-item">
          {allDevices.map(function (item, aindex) {
            return (
              <div className="item-box" key={'lamp' + aindex}>
                <div className="small-img-card">
                  <div className="value">
                    {item.tempSet2 ? item.tempSet2 : '--'}
                    <sup className="unite">℃</sup>
                  </div>
                  {item?.boundPoint?.modeSetBound && (
                    <div className="status">
                      <img
                        src={
                          item.airMode2 == 1
                            ? aircoldblack
                            : item.airMode2 == 2
                            ? airsunblack
                            : aircloudblack
                        }
                      />
                      {item.airMode2 == 2 ? '制热' : item.airMode2 == 1 ? '制冷' : '通风'}
                    </div>
                  )}
                </div>
                {item?.boundPoint?.switchSetBound && (
                  <div
                    className="small-sw-card"
                    onClick={() => {
                      eachAirOpen(aindex);
                    }}
                  >
                    <AnSwitch isOpen={item.open} isSmall={true}></AnSwitch>
                  </div>
                )}

                <div className="dplCenter" style={{ paddingRight: '14px', paddingLeft: '16px' }}>
                  <div className="lamp-basic-name">
                    <span>{item.name}</span>
                  </div>
                  {(item?.boundPoint?.tempSetBound ||
                    item?.boundPoint?.gearSetBound ||
                    item?.boundPoint?.modeSetBound) && (
                    <div
                      className={`adjustBox ${item.open ? 'adjustActive' : ''}`}
                      onClick={() => {
                        showModal(item);
                      }}
                    >
                      <img className="iconAdjust" src={icon_adjust} />
                    </div>
                  )}
                </div>
              </div>
              // <div
              //   className={`eachAir ${!item.open ? 'closeAir' : ''} ${
              //     allDevices.length == 1 ? 'oneAir' : ''
              //   }`}
              //   key={aindex + 'device'}
              // >
              //   <div className="airName">{item.name}</div>
              //   <div
              //     className={`openButton ${item.open ? 'open' : ''}`}
              //     onClick={() => {
              //       eachAirOpen(aindex);
              //     }}
              //   >
              //     <div className="openBack"></div>
              //     <div className="openCircle">
              //       {/* <van-loading
              //                 size="8"
              //                 :style="{display:item.loading?'block':'none'}"
              //                 wrapperClassName="openCircle"  />*/}
              //     </div>
              //   </div>
              //   <div className="airBox">
              //     {item.allModel.map(function (mitem, mindex) {
              //       return (
              //         <div
              //           className={`adjustBox ${!item.open ? 'disable' : ''}`}
              //           key={mindex + 'model'}
              //         >
              //           <div
              //             className={`arrow ${
              //               mitem.sel == mitem.selectArr.length - 1 ? 'disable' : ''
              //             }`}
              //             onClick={() => {
              //               arrowUpClick(aindex, mindex, mitem.sel);
              //             }}
              //           >
              //             <UpOutlined />
              //           </div>
              //           <div className="valueBox">
              //             <div
              //               className="valueWrap"
              //               style={{ transform: 'translateY(' + mitem.sel * -50 + 'px)' }}
              //             >
              //               {mitem.selectArr.map(function (sitem, sindex) {
              //                 return (
              //                   <div className="value" key={sindex + 'val'}>
              //                     {sitem}
              //                   </div>
              //                 );
              //               })}
              //             </div>
              //           </div>
              //           <div
              //             className={`arrow ${
              //               mitem.sel == 0 || (mitem.sel == 1 && mitem.id == 'gear')
              //                 ? 'disable'
              //                 : ''
              //             }`}
              //             onClick={() => {
              //               arrowDownClick(aindex, mindex, mitem.sel);
              //             }}
              //           >
              //             <DownOutlined />
              //           </div>
              //           <div className="adjustName">{mitem.name}</div>
              //         </div>
              //       );
              //     })}
              //   </div>
              // </div>
            );
          })}
        </div>
      )}

      {modalFlag && (
        <AirModal
          hideModal={hideModal}
          changeDeviceObj={changeDeviceObj}
          deviceObj={deviceObj}
          minValue={startTemp}
          maxValue={endTemp}
        ></AirModal>
      )}
    </div>
  );
};
