import { multiply, divide } from "@/utils/decimal.js";

/**
 * 根据屏幕缩放率 来进行样式缩放
 */
export default class ScreenScal {
  // 需要缩放适配的倍率
  resultCalcZoom = null;
  // 总缩放倍数
  zoom = null;
  // 浏览器缩放倍数
  browserZoom = null;
  // 系统缩放倍数
  systemZoom = null;
  // 系统分辨率
  systemResolution = null;
  constructor() {
    this.setUserScreenScal();
    window.addEventListener("resize", this.setUserScreenScal.bind(this), false);
  }

  setDefaultOptions() {
    const { zoom, resultCalcZoom, browserZoom, systemResolution, systemZoom } = this.getUserScreenInfo();
    this.zoom = zoom;
    this.resultCalcZoom = resultCalcZoom;
    this.browserZoom = browserZoom;
    this.systemZoom = systemZoom;
    this.systemResolution = systemResolution;
  }

  /**
   * 设置用户缩放
   */
  setUserScreenScal() {
    this.setDefaultOptions();
    document.body.style.setProperty("zoom", this.resultCalcZoom);
  }

  /**
   * 参数转换浮点
   * @param {*} num 
   * @returns 
   */
  getDecimal = (num) => {
    return parseFloat(divide(multiply(num, 100, 5), 100));
  };

  /**
   * 获取用户屏幕信息
   */
  getUserScreenInfo() {
    // 总缩放倍数
    const zoom = this.getZoom();
    // 屏幕分辨率
    const screenResolution = window.screen.width;
    // 获取浏览器内部宽度
    const browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    // 浏览器缩放倍数
    // 浏览器外部宽度不受浏览器缩放影响，浏览器内部宽度受影响,所以根据这个可以计算出浏览器缩放倍数（F12调试工具的占位会影响该值）
    const browserZoom = this.getDecimal(window.outerWidth / browserWidth);
    // 系统缩放倍数
    const systemZoom = this.getDecimal(zoom / browserZoom);
    // 系统分辨率
    const systemResolution = Math.round(screenResolution * systemZoom);
    // 屏幕最终需要适配结果
    const resultCalcZoom = 1 / zoom;

    // console.log('系统分辨率', systemResolution, '屏幕分辨率', screenResolution, '浏览器外部宽度', window.outerWidth, '浏览器内部宽度', browserWidth, '总缩放倍数', zoom, "系统最终适配倍数", resultCalcZoom, '浏览器缩放倍数', browserZoom, '系统缩放倍数', systemZoom);

    return {
      zoom,
      resultCalcZoom,
      browserZoom,
      systemZoom,
      systemResolution
    };
  }

  /**
   * 获取用户屏幕缩放倍数 后期需要考虑 echarts 缩放兼容性问题
   * @returns 
   */
  getZoom() {
    let zoom = 1;
    const screen = window.screen,
      ua = navigator.userAgent.toLowerCase();

    if (window.devicePixelRatio !== undefined) {
      const _devicePixelRatio = window.devicePixelRatio;
      zoom = _devicePixelRatio > 1 ? window.outerWidth / window.innerWidth : window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
      if (screen.deviceXDPI && screen.logicalXDPI) {
        zoom = screen.deviceXDPI / screen.logicalXDPI;
      }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
      zoom = window.outerWidth / window.innerWidth;
    }
    return this.getDecimal(zoom);
  }
}