/*
 * @Author: dayan_hjm  产供销价值链
 * @Date: 2023-11-10 10:19:34 
 * @Last Modified by: dayan_hjm
 * @Last Modified time: 2023-12-19 15:49:21
 */

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 {
  leftService,
  bigShopService,
  smallShopService,
  smallDayService,
  smallMaterialService,
  checkToken,
  updateTimeService
} from "./api";
import MapViewTwo from "./component/mapView2.jsx";
import mpVideoGvc from "@assets/imgs/dataVimg/videoGvc2.mp4";
import { getThousandNum,deleteCacheAndChangeUrl } from "@utils/util";

import 'animate.css';
import { get } from "lodash";

@withRouter

class Gvc extends Component {
  // 构造函数，组件的实例创建时，最先执行
  constructor(props, context) {
    super(props, context);
    this.store = mod;
    this.state = {
      LeftHtml: [
      ],
      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 {
          window.location = window.location.origin + '/transfer.html#/login';

          // this.props.history.replace("/home/index");
        }
      });
    }
  }
  componentDidMount() {
    this.getUrl();
    this.getUrl2()
    this.getUrl4()
    this.getUrl3();
    setTimeout(() => {
      this.videoStart();
    }, 200)
    setTimeout(() => {
      //替换gif
      $(".shu1").numScroll({ time: 3000 });
      // this.changeAllShu()
    }, 3000)
    setTimeout(() => {
      this.setState({ changGif: true });
    }, 4500)
  }

  changeAllShu() {
    const stu_input = document.getElementsByClassName("shu1");
    for (var i = 0; i < stu_input.length; i++) {
      console.log(stu_input[i], "arr_")
      console.log(stu_input[i].value, "arr_")
    }
  }

  videoStart() {
    /*     Chrome 浏览器的视频自动播放策略
        1.始终允许静音模式下自动播放
        2.在以下的情况中，带声音播放会被允许：
          ①用户已经与当前的域进行了交互（也就是click，tap事件）。
          ②在桌面设备上，用户的媒体参与度指数阈值已经超过，这意味着用户之前播放过有声视频。
          ③用户已经将网站添加到移动设备上的主屏幕或允在桌面上安装了PWA。
        3.顶部帧可以将自动播放权限委派给其iframe，来允许自动播放声音
        
        媒体参与度（Media Engagement）是指用户与媒体内容进行互动的程度，可以通过多个指标来衡量。这些指标主要包括观看时间、观看率、转化率、交互行为等。
        可以通过：chrome://media-engagement/ 查看
     */
    const video = document.querySelector('.video_box_2');
    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.playbackRate = 0.7;//设置视频为静音
      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 leftService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        let LeftHtml = [], name_ = ["碳酸锂", '氢氧化锂', '氯化锂', '金属锂'];
        data.map((x, i) => {
          if (i >= 4) {
            return
          }
          LeftHtml.push(
            {
              txt_name: name_[i],
              num1: x.production,
              num2: x.inventory,
            }
          );
        });
        this.setState({ LeftHtml });
      }
    });
  }
  async getUrl2() {
    await bigShopService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        const name_ = ["", "锂辉石库存量", "锂辉石库存量", "累计运输锂辉石"];
        const style__ = [{}, { left: "34%", top: "30%" }, { left: "11%", top: "48%" }, { left: "0%", top: "22%" }]
        data = data.map((x, i) => {
          return {
            ...x,
            total: x.indexValue,
            totalName: name_[x.warehouseNameCode],
            styles: style__[x.warehouseNameCode],
            cumulativeProduction: null,
            inventory: 0,
          }
        });
        const d_1 = data.filter(x => { return x.warehouseNameCode == 3 })[0];
        const d_2 = data.filter(x => { return x.warehouseNameCode == 2 })[0];
        const d_3 = data.filter(x => { return x.warehouseNameCode == 1 })[0];
        let old_imgMsgData = this.store.state.imgMsgData;
        old_imgMsgData[0] = d_1;
        old_imgMsgData[1] = d_2;
        old_imgMsgData[2] = d_3;

        this.store.saveState({ imgMsgData: old_imgMsgData });
      }
    });
  }
  async getUrl4() {
    await smallShopService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        const style__ = [{}, { left: "87%", top: "28%" }, { left: "69%", top: "46%" }, { left: "52%", top: "59%" }, { left: "29%", top: "76%" }, { left: "11%", top: "89%" }]
        data = data.map((x, i) => {
          0
          return {
            ...x,
            total: 0,
            totalName: "",
            styles: style__[x.factoryCode],
            cumulativeProduction: x.production,
            inventory: x.inventory,
          }
        });
        const d_1 = data.filter(x => { return x.factoryCode == 5 })[0];
        const d_2 = data.filter(x => { return x.factoryCode == 4 })[0];
        const d_3 = data.filter(x => { return x.factoryCode == 3 })[0];
        const d_4 = data.filter(x => { return x.factoryCode == 2 })[0];
        const d_5 = data.filter(x => { return x.factoryCode == 1 })[0];
        let old_imgMsgData = this.store.state.imgMsgData;
        old_imgMsgData[3] = d_1;
        old_imgMsgData[4] = d_2;
        old_imgMsgData[5] = d_3;
        old_imgMsgData[6] = d_4;
        old_imgMsgData[7] = d_5;


        console.log(old_imgMsgData, "old_imgMsgData")
        this.store.saveState({ imgMsgData: old_imgMsgData });
        this.getUrl5()
      }
    });
  }
  async getUrl5() {
    await smallDayService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        function getItems(num) {
          const datas = data.filter(x => { return x.factoryCode == num });
          const par = {
            day: getThousandNum(datas?.filter(x => { return x.dateType == 1 })?.[0]?.indexValue || 0),
            mood: getThousandNum(datas?.filter(x => { return x.dateType == 2 })?.[0]?.indexValue || 0),
            year: getThousandNum(datas?.filter(x => { return x.dateType == 3 })?.[0]?.indexValue || 0),
          }
          return par
        }

        const d_1 = getItems(5);
        const d_2 = getItems(4);
        const d_3 = getItems(3);
        // const d_4 = data.filter(x=>{return x.factoryCode == 2})[0];
        const d_4 = getItems(2);
        const d_5 = getItems(1);
        let old_imgMsgData = this.store.state.imgMsgData;
        old_imgMsgData[3] = { ...old_imgMsgData[3], ...d_1 };
        old_imgMsgData[4] = { ...old_imgMsgData[4], ...d_2 };
        old_imgMsgData[5] = { ...old_imgMsgData[5], ...d_3 };
        old_imgMsgData[6] = { ...old_imgMsgData[6], ...d_4 };
        old_imgMsgData[7] = { ...old_imgMsgData[7], ...d_5 };
        console.log(old_imgMsgData, "1111old_imgMsgData")
        this.store.saveState({ imgMsgData: old_imgMsgData });
        this.getUrl6()

      }
    });
  }

  async getUrl6() {
    await smallMaterialService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        function getItems(num) {
          const datas = data.filter(x => { return x.factoryCode == num });
          const rawMaterial = datas.map((item, index) => {
            return {
              prodCatgory: item.prodCatgory,
              indexValue: getThousandNum(item.indexValue),
            }
          })
          // const par = {
          //   rawMaterial: [
          //     {
          //       prodCatgory: "原料-鲤辉石",
          //       indexValue: datas?.filter(x => { return x.prodCatgory == 1 })?.[0]?.indexValue || 0,
          //     },
          //     {
          //       prodCatgory: "产品-碳酸锂",
          //       indexValue: datas?.filter(x => { return x.prodCatgory == 2 })?.[0]?.indexValue || 0,
          //     },
          //     {
          //       prodCatgory: "原料-氯化锂",
          //       indexValue: datas?.filter(x => { return x.prodCatgory == 3 })?.[0]?.indexValue || 0,
          //     },
          //     {
          //       prodCatgory: "产品-氢氧化锂",
          //       indexValue: datas?.filter(x => { return x.prodCatgory == 4 })?.[0]?.indexValue || 0,
          //     },
          //     {
          //       prodCatgory: "产品-金属锂",
          //       indexValue: datas?.filter(x => { return x.prodCatgory == 5 })?.[0]?.indexValue || 0,
          //     }
          //   ]
          // }
          return { rawMaterial: rawMaterial }
        }

        const d_1 = getItems(5);
        const d_2 = getItems(4);
        const d_3 = getItems(3);
        const d_4 = getItems(2);
        const d_5 = getItems(1);


        let old_imgMsgData = this.store.state.imgMsgData;
        old_imgMsgData[3] = { ...old_imgMsgData[3], ...d_1 };
        old_imgMsgData[4] = { ...old_imgMsgData[4], ...d_2 };
        old_imgMsgData[5] = { ...old_imgMsgData[5], ...d_3 };
        old_imgMsgData[6] = { ...old_imgMsgData[6], ...d_4 };
        old_imgMsgData[7] = { ...old_imgMsgData[7], ...d_5 };
        console.log(old_imgMsgData, "1111old_imgMsgData")
        this.store.saveState({ imgMsgData: old_imgMsgData });
      }
    });
  }
  async getUrl3() {
    await updateTimeService().then(({ data = [], resultCode }) => {
      if (+resultCode === 0) {
        this.setState({ updateTime: data?.[0]?.etlTime || '' })
      }
    });
  }

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


  getLeftHtml(x, i) {
    const { changGif } = this.state;
    return (
      <li>
        <div className={"top_div"}>
          <div class="animate__animated animate__pulse animate__slower animate__infinite">
            {i === 0 && <img class="img1" src={require("@assets/imgs/dataVimg/qiu1.png").default} alt="" />}
            {i === 1 && <img class="img1" src={require("@assets/imgs/dataVimg/qiu2.png").default} alt="" />}
            {i === 2 && <img class="img1" src={require("@assets/imgs/dataVimg/qiu3.png").default} alt="" />}
            {i === 3 && <img class="img1" src={require("@assets/imgs/dataVimg/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>
            {
              !changGif ? <span class="topMsg_number shu1">{x.num1}</span> : <span class="topMsg_number">{getThousandNum(x.num1)}</span>
            }

            <span class="topMsg_number_2" style={{ fontSize: "0.75em", color: "#fff" }}>吨</span>
          </div>
          <div>
            <p>产品库存</p>
            {
              !changGif ? <span class="topMsg_number shu1">{x.num2}</span> : <span class="topMsg_number">{getThousandNum(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, imgMsgData } = this.store.state;
    let { LeftHtml, updateTime, changGif } = this.state;
    return (
      <div className={[styles.gvc_home + ' home_box ']}>
        {/* 右键切换大屏 */}
        <Tooltip placement="bottom" title={"数据运营中心"}>
          <img src={require("@assets/imgs/iconJpg/rightJ.png").default} alt="" className={"rightJ_png"} onClick={() => {
            deleteCacheAndChangeUrl("/home/operation",(url)=>{
              this.props.history.replace(url);
            })

          }} />
        </Tooltip>
        <Tooltip placement="bottom" title={"数据运营中心"}>
          <img src={require("@assets/imgs/iconJpg/rightJL.png").default} alt="" className={"rightJ_png rightJ_png_L"} onClick={() => {
            deleteCacheAndChangeUrl("/home/operation",(url)=>{
              this.props.history.replace(url);
            })
          }} />
        </Tooltip>

        <div className={"all_box"}>
          {/* 视频播放器 */}
          <MapViewTwo></MapViewTwo>
          <div className={"video_box gvc_video"}>
            <div className="alls">
              <video src={mpVideoGvc} playbackRate={0.5} autoplay="autoplay" loop="loop" class="video_box_2 center_box2 animate__animated animate__fadeIn animate__delay-2s">
              </video>
            </div>

          </div>
          <div className={"gvcHome home cbHome"}>
            <div className="leftContent">
              <ul>
                {
                  LeftHtml.map((x, i) => {
                    return this.getLeftHtml(x, i)
                  })
                }
              </ul>
            </div>

            <div className="centerCon">
              <p className="rightCar">
                <img src={require("@assets/imgs/gvc/car.png").default} alt="" />
              </p>
              <ul className="imgMsg">
                {
                  toJS(imgMsgData).map((item, index) => {
                    if (!item) { return }
                    return (
                      <li style={{ ...item?.styles }} class="animate__animated animate__bounceInUp animate__slower">
                        {/* 矿产 */}
                        {
                          item.totalName && <p className="name">{item.totalName}</p>
                        }
                        {
                          item.totalName && !changGif && <span class="shu1 nums">{item.total}</span>
                        }
                        {
                          item.totalName && changGif && <span class="nums">{getThousandNum(item.total)}</span>
                        }
                        {
                          item.totalName && <span className="sma">吨</span>
                        }
                        {/* 基地 */}
                        {
                          item.cumulativeProduction !== null && <div className="hoverR">
                            <div className="hoverDiv chanL">
                              {/* <div style={{ width: "62%","textAlign":'right' }}> */}
                              <div style={{ width: "38%" }}>
                                <p className="title">
                                  产量/吨
                                </p>
                                <span>日：{item.day}</span>
                                <span>月：{item.mood}</span>
                                <span>年：{item.year}</span>
                              </div>
                              <div style={{ width: index == 5 ? "58%" : "55%" }}>
                                <p className="title">
                                  库存/吨
                                </p>
                                {
                                  get(item, "rawMaterial", []).map((ra, rai) => {
                                    return <span>{ra.prodCatgory}：{ra.indexValue}</span>
                                  })
                                }
                              </div>
                            </div>
                          </div>
                        }
                        {
                          item.cumulativeProduction !== null && <div className="chanL text">
                            <div>
                              <p>累计产量</p>
                              {
                                !changGif ? <span class="nums shu1">{item.cumulativeProduction}</span> : <span class="nums">{getThousandNum(item.cumulativeProduction)}</span>
                              }

                              <span class="topMsg_number_2" style={{ fontSize: "0.75em", color: "#fff" }}>吨</span>
                            </div>
                            <div>
                              <p>产品库存</p>
                              {
                                !changGif ? <span class="nums shu1">{item.inventory}</span> : <span class="nums">{getThousandNum(item.inventory)}</span>
                              }
                              <span class="topMsg_number_2" style={{ fontSize: "0.75em", color: "#fff" }}>吨</span>
                            </div>

                          </div>
                        }
                      </li>
                    )
                  })
                }
              </ul>
            </div>

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

              <div class="bottomContent3 animate__animated animate__fadeInDown animate__slower  animate__delay-1s">
                <div className="bottomContent bigDivPd">
                  <div className="topMsg_content">
                    <RightBottomView></RightBottomView>
                  </div>
                </div>
              </div>
            </div>
            <div className="bottom_box">
              <p style={{ color: "#6a818d", lineHeight: '2px', width: '100%', textAlign: "center" }}>
                更新日期 : {updateTime ? updateTime.split(" ")[0] : updateTime}
              </p>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default Gvc;
