import React, { useState, useEffect, useRef, useCallback } from 'react';
import { message, Spin } 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 './index.less';

export default ({ spaceId, projectId, changeDrag }) => {
  const {
    up_Arrow,
    down_Arrow,
    openair,
    air_close,
    wind_small,
    wind_big,
    airsunred,
    airsunblack,
    aircoldblue,
    aircoldblack,
    aircloudgreen,
    aircloudblack,
  } = 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 [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);

  function doTimeout() {
    clearInterval(infoTimer.current); // 定时器先清理 再设定
    infoTimer.current = setInterval(() => {
      getAirInfo();
    }, 20000);
  }
  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;
    var pageX = e.pageX;
    setStartX(pageX);
    setMovesign(true);
  }
  function cbarclick(e) {
    if (!airData.isOpen) 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);
    console.log('touchend');
  }

  function eachAirOpen(aindex) {
    //this.allDevices[aindex].open = !this.allDevices[aindex].open;
    var itemClone = { ...allDevices[aindex] };
    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 arrowDownClick(aindex, mindex, sel) {
    //console.log('sel', sel);
    var devicesClone = JSON.parse(JSON.stringify(allDevices));
    var nowDevice = devicesClone[aindex];
    var nowModel = devicesClone[aindex].allModel[mindex];
    if (!nowDevice.open) return;
    if (sel == 0) return;

    if (nowModel.id == 'gear' && sel == 1) return;
    if (sel < 0) {
      nowModel.sel = 0;
    } else {
      nowModel.sel--;
    }
    setAllDevices(devicesClone);

    if (nowModel.id == 'mode') {
      var value = nowModel.refer[nowModel.sel].mid;
      console.log('nowModel.refer', nowModel.refer, nowModel.refer[nowModel.sel].mid);
    } else if (nowModel.id == 'gear') {
      var selval = nowModel.selectArr[nowModel.sel];
      var value = selval == 'AUTO' ? 4 : selval;
      console.log('nowModel.refer2', selval, value);
    } else {
      var value = nowModel.selectArr[nowModel.sel];
      console.log('nowModel.refer3', value);
    }
    debounce(nowDevice.id, nowModel.code, value);

    //console.log("arrowup", aindex, mindex, sel)
  }

  const debounceTimer = useRef(null);
  function debounce(id, code, value) {
    clearTimeout(debounceTimer.current);

    debounceTimer.current = setTimeout(function () {
      changeOneAir(id, code, value);
    }, 500);
  }
  function arrowUpClick(aindex, mindex, sel) {
    var devicesClone = JSON.parse(JSON.stringify(allDevices));
    var nowDevice = devicesClone[aindex];
    var nowModel = devicesClone[aindex].allModel[mindex];

    if (!nowDevice.open) return;
    var selectArr = nowModel.selectArr;
    if (sel == selectArr.length - 1) return;
    //console.log('sel', sel);
    if (sel > selectArr.length - 1) {
      nowModel.sel = selectArr.length - 1;
    } else {
      nowModel.sel++;
    }

    setAllDevices(devicesClone);

    if (nowModel.id == 'mode') {
      var value = nowModel.refer[nowModel.sel].mid;
      console.log('nowModel.refer', nowModel.refer, nowModel.refer[nowModel.sel].mid);
    } else if (nowModel.id == 'gear') {
      var selval = nowModel.selectArr[nowModel.sel];
      var value = selval == 'AUTO' ? 4 : selval;
    } else {
      var value = nowModel.selectArr[nowModel.sel];
    }

    debounce(nowDevice.id, nowModel.code, value);
  }
  // function querySeasonType() {
  //     const params = {
  //         projectId: projectId,
  //         date: moment().format('YYYYMMDD') // 当天日期
  //     }
  //     if (!this.seasonType) {
  //         getSeasonType(params).then(res => {
  //             this.seasonType = res.data || '';
  //         }).catch(() => {
  //         })
  //     }
  // }
  // function showDetail(funcid) {
  //     this.$emit('showDetail', { funcid: funcid });
  //     wx.uma.trackEvent('officeHome_changeAir_temperature', { key: 'roomTemperature' });
  // }

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

    querySpaceConditioners(paramObj)
      .then((res) => {
        var data = res.data || {};
        console.log('getAirInfo', data);
        data.tempSet = data.tempSet;
        setAirTemp(data.tempSet);
        setNowTemp(data.tempSet);

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

        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;

          var allModel = JSON.parse(JSON.stringify(baseMode));
          //console.log('allModel', allModel);
          allModel.forEach((mitem) => {
            if (mitem.id == 'temp') {
              mitem.code = eitem.tempSetCode;
              //mitem.value = eitem.tempSet;
              var index = mitem.selectArr.findIndex((ele) => {
                return ele == eitem.tempSet;
              });
              //console.log('index1', index, eitem.tempSet);
              mitem.sel = index == -1 ? 0 : index;
            }
            if (mitem.id == 'gear') {
              mitem.code = eitem.gearCode;
              //mitem.value = eitem.gear;
              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;
              //mitem.value = eitem.workMode;
              var filterObj = mitem.refer.find((ele) => {
                return ele.mid == eitem.workMode;
              });
              mitem.sel = (filterObj || {}).sindex || 0;
              //  console.log('index3', filterObj, eitem.workMode);
            }
          });
          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 (!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);
        }
      });
    });
    //console.log('this.nowTemp222', value, nowTemp);
    //wx.showLoading();

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

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

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

  return (
    <div className="air-adjust office-card g-fl">
      <div className="air-content">
        <div className="air-adjust-env">
          <div className="air-text">
            <span className="envname">空调</span>
            <div className="envnum">
              {airTemp ? airTemp : '--'}
              <span className="unit">℃</span>
            </div>
          </div>
          <div className="air-show-all">
            {allDevices.length > 1 && (
              <div
                className="air-show-all-cont"
                onClick={() => {
                  allAirClick();
                }}
              >
                <img className="air-arrow" src={allAirShow ? up_Arrow : down_Arrow} />
                <span className="text">{allAirShow ? '收起全部' : '查看全部'}</span>
              </div>
            )}
          </div>
        </div>
        <div className="air-adjust-btn">
          <img className="airImg" src={airData.isOpen ? openair : air_close} />
        </div>
        {!allAirShow && (
          <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,
        }}
      >
        <div
          className="air-control-item temp-item"
          onMouseDown={(event) => {
            event.stopPropagation();
          }}
          onMouseUp={(event) => {
            cmouseup(event);
          }}
          onMouseMove={(event) => {
            cmousemove(event);
          }}
        >
          <div className="temp-wrap">
            <div className="minVal">{startTemp}℃</div>
            <div
              className="tempBar"
              ref={tempRef}
              onClick={(event) => {
                event.stopPropagation();
                cbarclick(event);
              }}
            >
              <div className="eachBlock"></div>
              <div className="eachBlock"></div>
              <div className="eachBlock"></div>
              <div className="eachBlock"></div>
              <div className="eachBlock"></div>
              {airData.isOpen && (
                <div
                  className="circle"
                  onMouseDown={(event) => {
                    event.stopPropagation();
                    cmousedown(event);
                  }}
                  style={{ transform: 'translateX(' + transX + 'px)' }}
                >
                  <span className="tvalue">{nowTemp}℃</span>
                </div>
              )}
            </div>
            <div className="maxVal">{endTemp}℃</div>
          </div>
          <div className="air-common-text change-text">温度设定</div>
        </div>

        <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');
              }}
            >
              AUTO
            </div>
          </div>
        </div>
        <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 == 2 ? 'yell' : ''} ${
                !airData.isOpen ? 'disabled' : ''
              }`}
              onClick={() => {
                changeZongAir('mode', 2);
              }}
            >
              <img src={airMode == 2 ? airsunred : airsunblack} />
            </div>
            <div
              className={`switch ${airMode == 1 ? 'yell' : ''} ${
                !airData.isOpen ? 'disabled' : ''
              }`}
              onClick={() => {
                changeZongAir('mode', 1);
              }}
            >
              <img src={airMode == 1 ? aircoldblue : aircoldblack} />
            </div>
            <div
              className={`switch ${airMode == 3 ? 'yell' : ''} ${
                !airData.isOpen ? 'disabled' : ''
              }`}
              onClick={() => {
                changeZongAir('mode', 3);
              }}
            >
              <img src={airMode == 3 ? aircloudgreen : aircloudblack} />
            </div>
          </div>
        </div>
      </div>

      {allAirShow && (
        <div className="allAir">
          {allDevices.map(function (item, aindex) {
            return (
              <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>
      )}
    </div>
  );
};
