/*
 * @Author: dayan_hjm  产供销价值链
 * @Date: 2023-11-10 10:19:34 
 * @Last Modified by: dayan_hjm
 * @Last Modified time: 2023-11-10 16:43:06
 */

import React, { useState, useEffect, Component } from "react";
import styles from "./style.less";
import { useHistory, useLocation, withRouter } from "react-router-dom";
import { observer, observable } from "mobx-react";
import { message, Space, Form, Popconfirm, Modal, Tooltip, Icon, Button } from "antd";
import mod from './mod';
import { toJS } from "mobx";
import RightBottomView from "./component/rightBottomView.jsx";
import {
  timeService,
  numberService,
  checkToken,
  updateTimeService
} from "./api";

import 'animate.css';
@withRouter

class Gvc extends Component {
  // 构造函数，组件的实例创建时，最先执行
  constructor(props, context) {
    super(props, context);
    this.store = mod;
    this.state = {
      LeftHtml: [
        {
          txt_name: '碳酸锂',
          num1: 1222,
          num2: 1000,
        },
        {
          txt_name: '氢氧化钠',
          num1: 2525,
          num2: 25,
        },
        {
          txt_name: '氯化锂',
          num1: 3654,
          num2: 7541,
        },
        {
          txt_name: '金属锂',
          num1: 45,
          num2: 698,
        },
      ],
      updateTime: '',
      changGif: false,
      plannedCompletionData: [
      ],
      plannedCompletionNum: 1,
      manHourData: [
      ],
      manHourNum: 1,
    };
    this.timer = null //定时器，用于检测同步状态
  }
  componentWillMount() {
    if (window.location.host.indexOf("localhost") == -1) {
      this.getToken()
    }
  }

  async getToken() {
    if (!sessionStorage.getItem("tqcVToken")) {
      this.props.history.replace("/home/index");
    } else {
      await checkToken(sessionStorage.getItem("tqcVToken")).then(({ data, resultCode }) => {
        if (data?.userId) {
          // this.props.history.push('/')
        } else {
          this.props.history.replace("/home/index");
        }
      });
    }
  }
  componentDidMount() {
    this.fontMsgChange();
    this.getUrl();
    this.getUrl2()
    this.getUrl3();
    setTimeout(() => {
      this.videoStart();
    }, 200)
    setTimeout(() => {
      //替换gif
      this.setState({ changGif: true });

    }, 2000)
  }
  videoStart() {
    /*     Chrome 浏览器的视频自动播放策略
        1.始终允许静音模式下自动播放
        2.在以下的情况中，带声音播放会被允许：
          ①用户已经与当前的域进行了交互（也就是click，tap事件）。
          ②在桌面设备上，用户的媒体参与度指数阈值已经超过，这意味着用户之前播放过有声视频。
          ③用户已经将网站添加到移动设备上的主屏幕或允在桌面上安装了PWA。
        3.顶部帧可以将自动播放权限委派给其iframe，来允许自动播放声音
        
        媒体参与度（Media Engagement）是指用户与媒体内容进行互动的程度，可以通过多个指标来衡量。这些指标主要包括观看时间、观看率、转化率、交互行为等。
        可以通过：chrome://media-engagement/ 查看
     */
    const video = document.querySelector('.video2');
    console.log(video.play());

    const model = document.querySelector('.model')
    const btn = document.querySelector('button')
    // 第一种方法 引导用户去与页面交互实现播放
    async function play() {
      try {
        await video.play();
        //使用await的原因是因为video.play()方法返回的是一个Promise,所以在这里我们可以对他进行一些处理
        model.style.display = 'none';
        btn.removeEventListener('click', play);
        // 如果他自动播放了就隐藏按钮，消除点击事件
      } catch (err) {
        model.style.display = 'block';
        btn.addEventListener('click', play);
        // 如果Promise返回的是error就引导用户点击按钮，在调用play方法
      }
    }
    play();

    //第二种方法比较主流，类似的有网页版抖音以及B站
    function play() {
      video.muted = true;//设置视频为静音
      video.play();//调用播放方法
      const ctx = new AudioContext();
      const canAutoPlay = ctx.state === 'running'; //通过这个可以判断出视频能不能够自动播放 如何可以它的值就是“running” 否则为"suspended"
      // 如果是不能播放我们就执行下面的逻辑，其实就是类似于第一种方法，让用户与其交互
      ctx.close();
      if (canAutoPlay) {
        video.muted = false;
        model.style.display = 'none';
        btn.removeEventListener('click', play);
      }
      else {
        model.style.display = 'block';
        btn.addEventListener('click', play);
      }
    }
    play()

  }

  async getUrl() {
    await timeService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        let plannedCompletionData = [], manHourData = [];
        data.map((x, i) => {
          if (x.indexName == '产量计划完成率') {
            plannedCompletionData.push({
              name: x.factoryName,
              value: x.indexValue * 100,
            })
          } else {
            manHourData.push({
              name: x.factoryName,
              value: x.indexValue * 100,
            })
          }
        });
        this.setState({ plannedCompletionData, manHourData, plannedCompletionNum: 1, manHourNum: 1 });
      }
    });
  }
  async getUrl2() {
    await numberService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        let totalValue = 0, yearDecline = 0, yearSend = 0, productInventory = 0;
        data.map((x, i) => {
          if (x.indexName == '产值') {
            totalValue = x.indexValue
          } else if (x.indexName == '年度产量') {
            yearDecline = x.indexValue
          } else if (x.indexName == '产品库存') {
            yearSend = x.indexValue
          } else if (x.indexName == '年度发货量') {
            productInventory = x.indexValue
          }
        });
        this.store.saveState({ totalValue, yearDecline, yearSend, productInventory });
        setTimeout(() => {
          $(".shu1").numScroll();
        }, 2500)
      }
    });
  }
  async getUrl3() {
    await updateTimeService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        this.setState({ updateTime: data?.[0]?.etlTime || '' })
      }
    });
  }

  componentDidCatch() {
    clearInterval(this.timer);
    this.timer = null;
  }

  fontMsgChange() {
    this.timer = setInterval(() => {
      const { plannedCompletionData, plannedCompletionNum, manHourData, manHourNum } = this.state;

      //产量计划完成率
      var p1 = document.getElementById('plannedCompletionBox');
      const datas_ = plannedCompletionData[plannedCompletionNum - 1];
      var res = '<div class="topMsg_box animate__animated animate__zoomIn"><span class="topMsg_number shu1">' + datas_?.value.toFixed(2) + '</span><span class="topMsg_number_2" style={{fontSize: "0.75em",color: "#fff"}}>%</span><p class="topMsg_number_p">' + datas_.name + '</p></div>';
      p1.innerHTML = res;

      //百万工时损工率
      var p2 = document.getElementById('manHourBox');
      const datas_2 = manHourData[manHourNum - 1];
      var res2 = '<div class="topMsg_box animate__animated animate__zoomIn"><span class="topMsg_number shu1">' + datas_2?.value.toFixed(2) + '</span><span class="topMsg_number_2">%</span><p class="topMsg_number_p">' + datas_2.name + '</p></div>';
      p2.innerHTML = res2;

      const num_ = plannedCompletionNum + 1 >= plannedCompletionData.length ? 1 : plannedCompletionNum + 1;
      const num_2 = manHourNum + 1 >= manHourData.length ? 1 : manHourNum + 1;
      this.setState({ plannedCompletionNum: num_, manHourNum: num_2 })
    }, 4000)
  }

  getLeftHtml(x, i) {
    return (
      <li>
        <div className={"top_div"}>
          <div class="animate__animated animate__pulse animate__slower animate__infinite">
            {i === 0 && <img className={"img1"} src={require("@assets/imgs/gvc/qiu1.png").default} alt="" />}
            {i === 1 && <img className={"img1"} src={require("@assets/imgs/gvc/qiu2.png").default} alt="" />}
            {i === 2 && <img className={"img1"} src={require("@assets/imgs/gvc/qiu3.png").default} alt="" />}
            {i === 3 && <img className={"img1"} src={require("@assets/imgs/gvc/qiu4.png").default} alt="" />}
            {i === 0 && <img src={require("@assets/imgs/gvc/qiuH1.png").default} alt="" class="img2 animate__animated animate__heartBeat animate__slower animate__infinite" />}
            {i === 1 && <img src={require("@assets/imgs/gvc/qiuH2.png").default} alt="" class="img2 animate__animated animate__heartBeat animate__slower animate__infinite" />}
            {i === 2 && <img src={require("@assets/imgs/gvc/qiuH3.png").default} alt="" class="img2 animate__animated animate__heartBeat animate__slower animate__infinite" />}
            {i === 3 && <img src={require("@assets/imgs/gvc/qiuH4.png").default} alt="" class="img2 animate__animated animate__heartBeat animate__slower animate__infinite" />}
            <span>{x.txt_name}</span>
          </div>
        </div>
        <div className="text">
          <div>
            <p>累计产量</p>
            <span class="topMsg_number shu1">{x.num1}</span><span class="topMsg_number_2" style={{ fontSize: "0.75em", color: "#fff" }}>吨</span>
          </div>
          <div>
            <p>产品库存</p>
            <span class="topMsg_number shu1">{x.num2}</span><span class="topMsg_number_2" style={{ fontSize: "0.75em", color: "#fff" }}>吨</span>
          </div>
        </div>
      </li>

    )
  }

  render() {
    const stores = this.store.state;
    let { totalValue, yearDecline, yearSend, productInventory } = this.store.state;
    let { LeftHtml, } = this.state;
    return (
      <div className={[styles.home_box + ' home_box']}>
        <div className={"all_box"}>
          <div className={"video_box"}>
            <video src={require("@assets/imgs/dataVImg/homeVideo2.mp4").default} autoplay="autoplay" loop="loop" class="video2 center_box2 animate__animated animate__fadeIn animate__delay-2s"></video>
          </div>
          <div className={"gvcHome home cbHome"}>
            <div className="leftContent">
              <ul>
                {
                  LeftHtml.map((x, i) => {
                    return this.getLeftHtml(x, i)
                  })
                }
              </ul>
            </div>

            <div className="centerCon">
            </div>

            {/* 右侧信息栏 */}
            <div className="rightContent">

              <div class="bottomContent2 animate__animated animate__fadeInDown animate__slower  animate__delay-1s">
                <div className="bottomContent bigDivPd">
                  <Tooltip placement="bottom" title={' ● 近三年的碳排放强度、碳排放总量数据'}>
                    <p className="topMsg_title">碳排放</p>
                  </Tooltip>
                  <div className="topMsg_content">
                    <RightBottomView></RightBottomView>
                  </div>
                </div>
              </div>
            </div>
            <div className="bottom_box">
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default Gvc;
