// 播放器右侧功能窗口： 云台控制、步长、3D控制、灯光、雨刷
import React, { Component, useMemo } from 'react';
import { Popover, message, Switch } from 'antd';
import PropTypes from 'prop-types';
import CustomSlider from './CustomSlider';
import { useBarStatus } from '../utils';
import '../style/function-window.less';
import { BaseStore } from '@zenview/micro-basic-library';
import IconFont from '../../../themeComponents/IconFont'
import Service from '../service';

const functionType = {
    // 变倍
    doubling: {
      add: {
          dataType: "zoomin",
          ref: "zoomin"
      },
      reduce: {
          dataType: "zoomout",
          ref: "zoomout"
      },
      mousedown: "zoomAction",
      mouseup: "cancleControl"
    },
    // 聚焦
    focusing:  {
      add: {
          dataType: "near",
          ref: "focusin"
      },
      reduce: {
          dataType: "far",
          ref: "focuout"
      },
      mousedown: "focusAction",
      mouseup: "cancleFocus"
    },
    // 光圈
    aperture:  {
      add:{
          dataType: "aperturein",
          ref: "aperturein"
      },
      reduce:{
          dataType: "apertureout",
          ref: "apertureout"
      },
      mousedown: "apertureAction",
      mouseup: "cancleAperture"
    }
}

const user = BaseStore.app.userInfo
const layerPos = ['up', 'rightup', 'right', 'rightdown', 'down', 'leftdown', 'left', 'leftup'];
const zoomType = ['zoomin', 'zoomout'];
const focusType = ['focusin', 'focusout'];
const apertureType = ['aperturein', 'apertureout']
class CameraControlView extends Component {
  static contextTypes = {
    fileData: PropTypes.object,
  };
  constructor(props) {
    super(props);
    this.isGB = false;
    this.CIG = false;
    this.type = "";
    // 国标摄像机
    // 控制速度0-3
    // 不能控制焦距，只能步骤控制（点控）

    // SDK
    // 控制速度0-8
    // 可以控制云台转动和焦距，持续控制

    // CIG
    // 控制速度1-3
    // 可以控制云台转动和焦距，持续控制


    // 非国标
    // 控制速度0-255
    // 上下控制较明显、左右不明显
    // 不能控制焦距，只能步骤控制（点控）
    [].concat(layerPos, zoomType, focusType, apertureType).forEach((item) => {
      this[item] = React.createRef();
    });
    this.addRef = React.createRef();
    this.reduceRef = React.createRef();
    this.state = {
      speed: (this.CIG || this.isGB) ? 2 : 20,
      totalSpeed: (this.CIG || this.isGB) ? 3 : 255,
      show: false,
        activeKeys: "doubling",
        d3Visible: false,
        lightVisible: false,
        wiperVisible: false
    };
  }

  // //按下事件
  // onKeyDown = (e) => {
  //   switch (e.keyCode) {
  //     case 37:
  //       this.type = 'left'
  //       break;
  //     case 38:
  //       this.type = 'up'
  //       break;
  //     case 39:
  //       this.type = 'right'
  //       break;
  //     case 40:
  //       this.type = 'down'
  //       break;
  //     default:
  //       break;
  //   }
  //   this.controlHandle(this.type);
  //   this.cancleControl(this.type);
  // }
  componentDidMount() {
    const { deviceInfo } = this.props;
    let speed, totalSpeed;
    try {
      if (deviceInfo.accessType.toLowerCase() === 'gb' || (deviceInfo.extJson.cameraInfo.type && deviceInfo.extJson.cameraInfo.type.toLowerCase() === 'gb')) {
        this.isGB = true;
        speed = 2;
        totalSpeed = 3;
      }
      if (deviceInfo.accessType.toLowerCase() === 'sdk') {
        this.isGB = true;
        speed = 3;
        totalSpeed = 8;
      }
      if (deviceInfo.accessType.toLowerCase() === 'cig') {
        this.CIG = true;
        speed = 2;
        totalSpeed = 3;
      }
    } catch (e) {
      console.warn('fileData.extJson.cameraInfo', deviceInfo);
    }
    // if (this.props.inputRef) {
    //   this.props.inputRef.current.addEventListener("blur", this.onBlur)//监听失去焦点
    //   this.props.inputRef.current.addEventListener("focus", this.onFocus)//监听获取焦点
    // }
    this.setState({
      speed: speed ? speed : 20,
      totalSpeed: totalSpeed ? totalSpeed : 255,
      show: false,
    });
  }
  //onBlur = () => {
  // console.log("移除")
  //this.props.inputRef.current !== null && this.props.inputRef.current.removeEventListener("keydown", this.onKeyDown)//监听按下事件
  /// this.props.playBox.current !== null && this.props.playBox.current.removeEventListener("mousewheel", this.onWheel)//监听滚轮事件
  // }
  //onFocus = () => {
  // console.log("加入")
  //this.props.inputRef.current.addEventListener("keydown", this.onKeyDown)//监听按下事件
  // this.props.playBox.current.addEventListener("mousewheel", this.onWheel)//监听滚轮事件
  //}
  //鼠标滚动事件
  onWheel = (e) => {
    if (e.wheelDelta === 120) {
      this.zoomAction("zoomin")
      this.cancleControl("zoomin")
    } else {
      this.zoomAction("zoomout")
      this.cancleControl("zoomout")
    }
  }
  bindEvents = () => {
    layerPos.forEach((v) => {
      this[v].current.addEventListener('mousedown', this.controlHandle);
      this[v].current.addEventListener('mouseup', this.cancleControl);
    });
    this.addRef.current.addEventListener('mousedown', this.addMousedown);
    this.addRef.current.addEventListener('mouseup', this.addMouseup);
    this.reduceRef.current.addEventListener('mouseup', this.reduceMousedown);
    this.reduceRef.current.addEventListener('mousedown', this.reduceMouseup);
  };


  removeEvents = () => {
    const { deviceInfo } = this.props;
    const isSDK = typeof deviceInfo.accessType === 'string' && deviceInfo.accessType.toLowerCase() === 'sdk';
    layerPos.forEach((v) => {
      this[v].current && this[v].current.removeEventListener('mousedown', this.controlHandle);
      this[v].current && this[v].current.removeEventListener('mouseup', this.cancleControl);
    });
    this.addRef.current && this.addRef.current.removeEventListener('mousedown', this.addMousedown);
    this.addRef.current && this.addRef.current.removeEventListener('mouseup', this.addMouseup);
    this.reduceRef.current && this.reduceRef.current.removeEventListener('mouseup', this.reduceMousedown);
    this.reduceRef.current && this.reduceRef.current.removeEventListener('mousedown', this.reduceMouseup);
  };

  setSpeed = (speed) => {
    this.setState({ speed });
  };

  // 调焦
  zoomAction = (e) => {
    // 国标相机才能调焦
    this.controlHandle(e);
  };

  controlHandle = (e, isStop = false) => {
    const direction = e.target ? e.target.dataset.type : e;
    const { deviceInfo } = this.props;
    const { speed } = this.state;
    let cmd, control;
    if (this.isGB || this.CIG) {
      cmd = isStop ? 'stop' : 'move';
      control = {
        direction,
        speed,
      };
      if(isStop == 'stop'){
        control = {
          direction:'down',
          speed,
        }
      }
    } else {
      cmd = 'direction';
      control = {
        direction,
        delay: 100,
        step: speed,
      };
    }
    Service.unifyControlPTZ({
      cid: deviceInfo.cid,
      cmd,
      control,
      userGrade: user.userGrade,
      userId: user.id
    }).then(res => {
      //如果第一次请求失败第二次弹出提示
      if (res.code !== 0 && res.message && isStop) {
        message.warn(res.message)
      }
    });
  };

  cancleControl = (e) => {
    if (this.isGB || this.CIG) {
      setTimeout(() => {
        this.controlHandle(e, true);
      }, 100);
    }
  };
  // 手动聚焦
  focusAction = (e, isStop = false) => {
    const direction = e.target.dataset.type;
    const { deviceInfo } = this.props;
    Service.controlFocus({
      cid: deviceInfo.cid,
      cmd: isStop ? 'stop' : 'manual',
      control: {
        operation: direction,
        speed: 4,
      },
    });
  };

  // 取消聚焦
  cancleFocus = (e) => {
    setTimeout(() => {
      this.focusAction(e, true);
    }, 100);
  };

  // 自动聚焦
  handleAutoFocus = () => {
    const { deviceInfo } = this.props;
    Service.controlFocus({
      cid: deviceInfo.cid,
      cmd: 'auto',
    });
  };

  onDoubleClick = (e) => {
    e.stopPropagation();
  };
  // 光圈
  apertureAction = (e) => {
      console.log("光圈",e)
  }
  // 取消光圈
  cancleAperture = (e) => {
      console.log("取消光圈",e)
  }
  setVisible = () => {
    const show = !this.state.show;
    this.props.showPTZModule(show)
    if (show) {
      this.setState({ show }, this.bindEvents);
    } else {
      this.removeEvents();
      this.setState({ show });
    }
  };
  // 功能按钮点击
  ToolsClick = (activeKeys) => {
    this.setState({ activeKeys });
  }
  // +按下触发
  addMousedown = () => {
    let { activeKeys } = this.state;
    let obj = functionType[activeKeys] || {};
    this.judgeIsRetrun(activeKeys) && this[obj.mousedown](obj.add.dataType);
  }
  // +放开触发
  addMouseup = () => {
      let { activeKeys } = this.state;
      let obj = functionType[activeKeys] || {};
      this.judgeIsRetrun(activeKeys) && this[obj.mouseup](obj.add.dataType);
  }
  // -按下触发
  reduceMousedown = () => {
    let { activeKeys } = this.state;
    let obj = functionType[activeKeys] || {};
    this.judgeIsRetrun(activeKeys) && this[obj.mousedown](obj.reduce.dataType);
  }
  // -放开触发
  reduceMouseup = () => {
    let { activeKeys } = this.state;
    let obj = functionType[activeKeys] || {};
    this.judgeIsRetrun(activeKeys) && this[obj.mouseup](obj.reduce.dataType);
  }
  // 判断是否SDK设备聚焦
  judgeIsRetrun = (activeKeys) => {
    const { deviceInfo } = this.props;
    const isSDK = typeof deviceInfo.accessType === 'string' && deviceInfo.accessType.toLowerCase() === 'sdk';
    // 聚焦判断是否为SDK设备  
    if (activeKeys === "focusing" && !isSDK) {
      return false
    }
    return true
  }
  render() {
    let { show, totalSpeed, speed, activeKeys, d3Visible, lightVisible, wiperVisible  } = this.state;
    const { deviceInfo } = this.props;
    const isSDK = typeof deviceInfo.accessType === 'string' && deviceInfo.accessType.toLowerCase() === 'sdk';
    return (
      <div className="function-control-layer" onDoubleClick={this.onDoubleClick}>
        <span className={`ptz-btn ${show ? 'open' : ''}`} onClick={this.setVisible}>
          <span className="ptz-status-icon" />
        </span>
        {show && (
            <div className="layout-content">
                <div className="header">
                    <IconFont className="icon-close" type="icon-S_Edit_LineClose" title="关闭"  onClick={this.setVisible}/>
                </div>
                <div className="module-box">
                    <div className="top-box">
                        <div className="camera-control-wrapper">
                            <ul>
                                {layerPos.map((item) => (
                                <li key={item} className={`camera-control-${item}`}>
                                    <span className="control-item" data-type={item} ref={this[item]}>
                                    <span />
                                    </span>
                                </li>
                                ))}
                            </ul>
                            {
                                activeKeys ==="focusing" ? ( <div className="focusing-layer" data-type="focusauto" onClick={() => this.handleAutoFocus() } title="自动聚焦"  ref={this.focusauto}/>)     
                                :(<div className="center-layer"/>)
                            }
                            <div className="center-circle" />
                        </div>
                        <div className="function-tools">
                            <div className="btn add-btn" data-type={functionType[activeKeys].add.dataType } ref={this.addRef}>+</div>
                            <div className={`btn ${activeKeys === "doubling" ? "active" : ""}`} onClick={()=>this.ToolsClick("doubling")}>变倍</div>
                            { isSDK && (
                                    <div className={`btn ${activeKeys === "focusing" ? "active" : ""}`} onClick={() => this.ToolsClick("focusing")}>聚焦</div>
                            )}   
                            <div className={`btn ${activeKeys ==="aperture" ? "active" : ""}`} onClick={()=>this.ToolsClick("aperture")}>光圈</div>
                            <div className="btn add-btn"  data-type={functionType[activeKeys].reduce.dataType } ref={this.reduceRef}>-</div>
                        </div>
                    </div>
                    <div className="box-speed">
                        <span className="tip">步长</span>
                        <Popover
                          content={
                            <div className="tip-content">
                              <p className="tip-title-box">步长</p>
                              <p className="remark-txt">设备转动的速度，由快到慢，数值越大，调整摄像机的转动角度越大。</p>
                            </div>}
                          title=""
                          trigger="hover">
                        &nbsp;<IconFont className="tip-icon" type="icon-Help1"></IconFont>
                        </Popover>
                        <CustomSlider min={0} max={totalSpeed} defaultPercent={speed / totalSpeed} getPlayContainer={this.props.getPlayContainer} onChange={this.setSpeed} />
                    </div>  
            </div>
                <div className="switch-box">
                    <span className="icon-box"> <IconFont className="icon" type="icon-S_Photo_ViewD1" ></IconFont></span>
                    <span className="tip-txt">3D控制
                      <Popover
                        content={
                          <div className="tip-content">
                            <p className="tip-title-box">3D控制</p>
                            <p className="tip-box">
                              <span className="icon-dianji"></span>
                              <span className="fun-txt"> 点击 </span>
                              <span className="remark-txt"> 点击视频画面，实现云台方向自动定位和聚焦 </span>
                            </p>
                            <p className="tip-box">
                              <span className="icon-huakuang"></span>
                              <span className="fun-txt"> 画框 </span>
                              <span className="remark-txt"> 视频画面画框，实现云台方向移动及变倍放大，右键缩放还原 </span>
                          </p>
                          <p className="tip-box">
                              <span className="icon-tuozhuai"></span>
                              <span className="fun-txt"> 拖拽 </span>
                              <span className="remark-txt"> 拖拽画面方向，实现云台移动镜头 </span>
                            </p>
                          </div>} 
                        title=""
                        trigger="hover">
                      &nbsp;<IconFont className="tip-icon" type="icon-Help1"></IconFont>
                      </Popover>
                    </span>
                    <span className="btn">{d3Visible ? "开启" : "关闭"}&nbsp;&nbsp;<Switch checked={d3Visible} onChange={() => this.setState({d3Visible:!d3Visible})}/></span>
                </div>
                <div className="switch-box">
                    <span className="icon-box"> <IconFont className="icon" type="icon-S_AID_dengguang" ></IconFont></span>
                    <span className="tip-txt">灯光</span>
                    <span className="btn">{lightVisible ? "开启" : "关闭"}&nbsp;&nbsp;<Switch checked={lightVisible} onChange={() => this.setState({lightVisible:!lightVisible})}/></span>
                </div>
                <div className="switch-box">
                    <span className="icon-box"> <IconFont className="icon" type="icon-PantsSkirt" ></IconFont></span>
                    <span className="tip-txt">雨刷</span>
                    <span className="btn">{wiperVisible ? "开启" : "关闭"}&nbsp;&nbsp;<Switch checked={wiperVisible} onChange={() => this.setState({wiperVisible:!wiperVisible})}/></span>
                </div>
          </div>
        )}
      </div>
    );
  }
}

export default function FunctionWindow({ deviceInfo, player, isFile, inputRef, playBox, showPTZModule }) {
  const barStatus = useBarStatus(player);
  const isHide = useMemo(() => !isFile, [isFile]);
  return !isHide ? <CameraControlView deviceInfo={deviceInfo} getPlayContainer={() => player.__player} barStatus={barStatus} isFile={isFile} inputRef={inputRef} playBox={playBox} showPTZModule={showPTZModule} /> : null;
}

  