/*
 * @Author: dayan_hjm 
 * @Date: 2023-10-25 10:32:44 
 * @Last Modified by: dayan_hjm
 * @Last Modified time: 2023-11-05 11:14:56
 */
/*
 * @Author: dayan_hjm 
 * @Date: 2022-10-27 11:40:02 
 * @Last Modified by: dayan_hjm
 * @Last Modified time: 2023-10-25 10:32:07
 */

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, Carousel, Icon, Button } from "antd";
import mod from './mod';
import { toJS } from "mobx";
import BottomLineForSend from "./component/bottomLineForSend.jsx";
import MoodSendView from "./component/moodSendView.jsx";
import LeftMenoyView from "./component/leftMenoyView.jsx";
import RightBottomView from "./component/rightBottomView.jsx";
import OneQualified from "./component/oneQualified.jsx";
import MapView from "./component/mapView.jsx";
import {
  timeService,
  numberService,
} from "./api";

import 'animate.css';
@withRouter

class Home extends Component {
  // 构造函数，组件的实例创建时，最先执行
  constructor(props, context) {
    super(props, context);
    this.store = mod;
    this.state = {
      changGif: false,
      plannedCompletionData:[
        {name:'射洪',value:78.1},
        {name:'广东',value:12},
        {name:'珠海',value:65},
        {name:'潮汕',value:45},
      ],
      plannedCompletionNum:1,
      manHourData:[
        {name:'射洪',value:0.2},
        {name:'广东',value:33},
        {name:'珠海',value:65},
        {name:'潮汕',value:65},
      ],
      manHourNum:1,
    };
    this.timer = null //定时器，用于检测同步状态
  }

  componentDidMount() {
    this.fontMsgChange();
    this.getUrl();
    this.getUrl2()
    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)
      }
    });
  }

  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 + '</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 + '</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)
  }

  render() {
    const stores = this.store.state;
    const {totalValue,yearDecline,yearSend,productInventory} = this.store.state;
    let { changGif,plannedCompletionData, } = this.state;
    return (
      <div className={"home_box"}>
        {/* 视频播放器 */}
        <MapView></MapView>
        <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={[styles.home + " home cbHome"]}>
          <div className="leftContent">

            <div class="topMsg2 animate__animated animate__fadeInDown animate__slower">
              <div className="topMsg">
                <p className="topMsg_title">总产值</p>
                <div className={changGif ? "topMsg_content changBg_topMsg_content" : "topMsg_content"}>
                  <span className="topMsg_number" class="shu1">{totalValue}</span><span className="topMsg_number_2">万元</span>
                </div>
              </div>
            </div>

            <div class="center_box2 animate__animated animate__fadeInDown animate__slower animate__delay-1s">
              <div className="center_box">
                <p className="topMsg_title">库存金额</p>
                <div className="topMsg_content">
                  <LeftMenoyView></LeftMenoyView>
                </div>
              </div>
            </div>

            <div class="bottomContent2 animate__animated animate__fadeInDown animate__slower animate__delay-1s">
              <div className="bottomContent bigDivPd">
                <p className="topMsg_title">月度产量/发货量</p>
                <div className="topMsg_content">
                  <MoodSendView></MoodSendView>
                </div>
              </div>
            </div>

          </div>

          <div className="centerCon">
            <div class="topMsg3 animate__animated animate__fadeInUp animate__slower">
              <div className="topMsg">
                <div className="topMsg2">
                  <div className="topMsg_content">
                    <div className="center_li">
                      <div className="right_li">
                        <span className="topMsg_number" class="shu1">{yearDecline}</span>
                        <p className="topMsg_line"></p>
                        <span className="topMsg_tip">年度产量/吨</span>
                      </div>
                    </div>
                    <div className="center_li">
                      <div className="right_li">
                        <span className="topMsg_number" class="shu1">{yearSend}</span>
                        <p className="topMsg_line"></p>
                        <span className="topMsg_tip">年度发货量/吨</span>
                      </div>
                    </div>
                    <div className="center_li">
                      <span className="topMsg_number" class="shu1">{productInventory}</span>
                      <p className="topMsg_line"></p>
                      <span className="topMsg_tip">产品库存/吨</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="bottomContent3 animate__animated animate__fadeInUp animate__slower">
              <div className="bottomContent">
                <p className="topMsg_title">近30天产量</p>
                <div className="topMsg_content">
                  <BottomLineForSend></BottomLineForSend>
                </div>
              </div>
            </div>

          </div>

          {/* 右侧信息栏 */}
          <div className="rightContent">
            <div class="topMsg2 animate__animated animate__fadeInDown animate__slower">
              <div className="topMsg bigDivPd">
                <p className="topMsg_title">百万工时损工率</p>
                <div className={changGif ? "topMsg_content changBg_topMsg_content" : "topMsg_content"} id="manHourBox">
                  <div className="topMsg_box">
                    <span className="topMsg_number" class="shu1"></span><span className="topMsg_number_2"></span>
                    <p className="topMsg_number_p"></p>
                  </div>
                </div>
              </div>
            </div>

            <div class="topMsg_22 animate__animated animate__fadeInDown animate__slower">
              <div className="topMsg_2">
                <p className="topMsg_title">一次合格率</p>
                <div className="topMsg_content">
                  <OneQualified></OneQualified>
                </div>
              </div>
            </div>

            <div class="topMsg_33 animate__animated animate__fadeInDown animate__slower animate__delay-1s">
              <div className="topMsg_3">
                <p className="topMsg_title">产量计划完成率</p>
                <div className={changGif ? "topMsg_content changBg_topMsg_content" : "topMsg_content"} id="plannedCompletionBox">
                  <div className="topMsg_box">
                    <span className="topMsg_number" class="shu1"></span><span className="topMsg_number_2"></span>
                    <p className="topMsg_number_p"></p>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="bottomContent2 animate__animated animate__fadeInDown animate__slower  animate__delay-1s">
              <div className="bottomContent bigDivPd">
                <p className="topMsg_title">碳排放</p>
                <div className="topMsg_content">
                  <RightBottomView></RightBottomView>
                </div>
              </div>
            </div>
          </div>
          <div className="bottom_box">
              <p style={{color:"#6a818d"}}>
                更新时间:2023-10-18
              </p>
          </div>

        </div>
      </div>
    )
  }
}
export default Home;
