import React, { useEffect, useState } from 'react';
import styles from './index.less';
import * as datav from '@jiaminghi/data-view-react';
import dataBoardTitle from '../../../public/assets/dataBoardTitle.png';
import decoration_two from '../../../public/assets/decoration_two.png';
import decoration_three from '../../../public/assets/decoration_three.png';
import decoration_five from '../../../public/assets/decoration_five.png';
import MapComponent from '@/pages/DataBoard/mapComponent';
import border from '../../../public/assets/border.png';
import dataBoardBg_two from '../../../public/assets/dataBoardBg_two.png';
import LineChartsCommon from '@/pages/DataBoard/lineChartsCommon';
import Slider from 'react-slick';
import SliderData from '@/pages/DataBoard/sliderData';
import AreaDeviceData from '@/pages/DataBoard/areaDeviceData';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import {
  queryAreaData,
  queryDeviceChart,
  queryDeviceData,
  queryDeviceRunTime,
  queryHomeInfo,
  queryUserChart,
  queryUserData,
} from '@/services/dataBoardService';
import PreloadImage from '@/components/PreloadImage';

// 数据大屏
const DataBoard: React.FC = () => {
  const [deviceTypeValue, setDeviceTypeValue] = useState(1);
  const [userTypeValue, setUserTypeValue] = useState(1);
  const [userNum, setUserNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 28,
      fill: '#2ff8ff',
    },
  });
  const [homeNum, setHomeNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 28,
      fill: '#2ff8ff',
    },
  });
  const [onlineDeviceNum, setOnlineDeviceNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [offlineDeviceNum, setOfflineDeviceNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [deviceNum, setDeviceNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [errorDeviceNum, setErrorDeviceNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [masterControlNum, setMasterControlNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [subControlNum, setSubControlNum] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 20,
      fill: '#2ff8ff',
    },
  });
  const [deviceStatistics, setDeviceStatistics] = useState({
    number: [0],
    content: '{nt}',
    style: {
      fontSize: 33,
      fill: '#08c7f1',
    },
  });
  const [allRunTime, setAllRunTime] = useState({
    number: [0],
    content: '{nt}',
    toFixed: 2,
    style: {
      fontSize: 33,
      fill: '#ffb026',
    },
  });
  const [todayRunTime, setTodayRunTime] = useState({
    number: [0],
    content: '{nt}',
    toFixed: 2,
    style: {
      fontSize: 33,
      fill: '#0dde79',
    },
  });
  const [homeInfo, setHomeInfo] = useState([]);
  const [userChartsData, setUserChartsData] = useState([]);
  const [deviceChartsData, setDeviceChartsData] = useState([]);
  const [areaDeviceList, setAreaDeviceList] = useState([]);

  const settings = {
    dots: false, //圆点显示（false隐藏）
    infinite: true, //无限的环绕内容
    autoplay: true, //自动播放，速度默认为（3000毫秒）
    speed: 3000, //自动播放速度（毫秒）
    slidesToShow: 2, //在一帧中显示2张卡片
    slidesToScroll: 1, //一次滚动2张卡片
    variableWidth: true,
  };

  // 设备统计
  const getDeviceData = () => {
    queryDeviceData().then((res) => {
      if (res?.code === 0) {
        // 设备数
        setDeviceNum((data) => {
          data.number = [res.data.device_count * 15]; // 暂时乘以15
          return { ...data };
        });
        // 故障设备数
        setErrorDeviceNum((data) => {
          data.number = [res.data.failure_device];
          return { ...data };
        });
        // 主控数量
        setMasterControlNum((data) => {
          // data.number = [res.data.master_count];
          data.number = [150]; // 假数据 回头删
          return { ...data };
        });
        // 分控数量
        setSubControlNum((data) => {
          // data.number = [res.data.sub_count];
          data.number = [150 * 3]; // 假数据 回头删
          return { ...data };
        });
        // 设备数统计
        setDeviceStatistics((data) => {
          data.number = [res.data.device_count * 15]; // 假数据 回头删
          return { ...data };
        });
      }
    });
  };

  // 用户数据统计
  const userNumData = () => {
    queryUserData().then((res) => {
      if (res?.code === 0) {
        // 注册用户数
        setUserNum((data) => {
          data.number = [res.data.user_count * 15]; // 暂时乘以15
          return { ...data };
        });
        // 家庭数量
        setHomeNum((data) => {
          data.number = [res.data.home_count * 15]; // 假数据 回头删
          return { ...data };
        });
        // 在线设备数
        setOnlineDeviceNum((data) => {
          // data.number = [res.data.device_online];
          data.number = [150];
          return { ...data };
        });
        // 离线设备数
        setOfflineDeviceNum((data) => {
          // data.number = [res.data.device_offline];
          data.number = [0];
          return { ...data };
        });
      }
    });
  };

  // 设备运行时长统计
  const getRunTime = () => {
    queryDeviceRunTime().then((res) => {
      if (res.code === 0) {
        setAllRunTime((data) => {
          data.number = [res.data.total_run_time];
          return { ...data };
        });
        setTodayRunTime((data) => {
          data.number = [res.data.day_run_time];
          return { ...data };
        });
      }
    });
  };

  //地区设备数量Top5
  const getAreaData = () => {
    queryAreaData({ region_type: '1' }).then((res) => {
      if (res?.code === 0) {
        // 假数据 回头删
        const arr: any = [
          {
            name: '济南',
            value: 27,
          },
          {
            name: '菏泽',
            value: 19,
          },
          {
            name: '泰安',
            value: 16,
          },
          {
            name: '济宁',
            value: 10,
          },
          {
            name: '潍坊',
            value: 10,
          },
        ];
        setAreaDeviceList(arr);
      }
    });
  };

  // 设备增长趋势
  const deviceCharts = () => {
    queryDeviceChart({ time_type: deviceTypeValue }).then((res) => {
      if (res?.code === 0) {
        // 假数据 回头删
        const arr = res.data;
        for (let i = 0; i < arr.length; i++) {
          arr[i].value = arr[i].value * 15;
        }
        setDeviceChartsData(res.data);
      }
    });
  };

  // 用户增长趋势
  const userCharts = () => {
    queryUserChart({ time_type: userTypeValue }).then((res) => {
      if (res?.code === 0) {
        // 假数据 回头删
        const arr = res.data;
        for (let i = 0; i < arr.length; i++) {
          arr[i].value = arr[i].value * 15;
        }
        setUserChartsData(res.data);
      }
    });
  };

  // 查询家列表
  const getHomeListInfo = () => {
    queryHomeInfo().then((res) => {
      if (res.code === 0) {
        setHomeInfo(res.data);
      }
    });
  };

  useEffect(() => {
    // 组件挂载时立即获取一次数据
    getAreaData();
    userNumData();
    getDeviceData();
    getRunTime();
    deviceCharts();
    userCharts();
    getHomeListInfo();

    // 定义一个函数，用于设置定时器
    const timer = setInterval(() => {
      getAreaData();
      userNumData();
      getDeviceData();
    }, 10 * 60 * 1000); // 10分钟，单位为毫秒

    // 两秒刷新一次顶部的时长数据
    const timer_two = setInterval(() => {
      getRunTime();
    }, 1000 * 2);

    // 组件卸载时清除定时器
    return () => {
      clearInterval(timer);
      clearInterval(timer_two);
    };
  }, []); // 传入一个空数组作为第二个参数，确保只在组件挂载和卸载时执行一次

  // 设备增长趋势切换
  useEffect(() => {
    deviceCharts();
    const interval = setInterval(() => {
      setDeviceTypeValue((prevParam) => (prevParam === 1 ? 2 : 1));
    }, 1000 * 10);
    return () => clearInterval(interval);
  }, [deviceTypeValue]);

  // 用户增长趋势切换
  useEffect(() => {
    userCharts();
    const interval = setInterval(() => {
      setUserTypeValue((prevParam) => (prevParam === 1 ? 2 : 1));
    }, 1000 * 10);
    return () => clearInterval(interval);
  }, [userTypeValue]);

  return (
    <div className={styles.container}>
      <PreloadImage
        src={dataBoardBg_two}
        alt="背景边框"
        style={{ position: 'absolute', bottom: 0 }}
      />
      {/* 顶部 */}
      <div className={styles.dataTitleItem}>
        <PreloadImage src={dataBoardTitle} alt="顶部标题背景" />
        <img src={decoration_three} style={{ width: '50%' }} alt="顶部标题背景装饰" />
        <div className={styles.title}>山东永续绿建五恒环境科技有限公司</div>
      </div>
      {/* 中间内容 */}
      <div className={styles.dataBoardContent}>
        {/* 中间内容-----左侧 */}
        {/* 中间内容-----左侧--统计数据 */}
        <div className={styles.decoration_left_1}>
          <PreloadImage src={border} alt="边框" />
          <div className={styles.title_text}>统计数据</div>
          <div className={styles.statistics}>
            <div className={styles.user_data}>
              <div className={styles.statistics_title_text}>用户统计</div>
              <div className={styles.user_content}>
                <div className={styles.user_item}>
                  <div className={styles.item_title}>注册用户数</div>
                  <datav.DigitalFlop config={userNum} style={{ width: '200px', height: '50px' }} />
                </div>
                <div className={styles.user_item}>
                  <div className={styles.item_title}>家庭数量</div>
                  <datav.DigitalFlop
                    config={homeNum}
                    className={styles.item_content}
                    style={{ width: '200px', height: '50px' }}
                  />
                </div>
              </div>
            </div>
            <div className={styles.device_data}>
              <div className={styles.statistics_title_text}>设备统计</div>
              <div className={styles.device_content}>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={deviceNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>设备数</div>
                </div>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={onlineDeviceNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>在线设备数</div>
                </div>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={offlineDeviceNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>离线设备数</div>
                </div>
              </div>
              <div className={styles.device_content}>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={errorDeviceNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>故障设备数</div>
                </div>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={masterControlNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>主控数量</div>
                </div>
                <div className={styles.device_item}>
                  <datav.DigitalFlop
                    config={subControlNum}
                    className={styles.device_num}
                    style={{ width: '200px', height: '50px' }}
                  />
                  <img src={decoration_two} className={styles.device_bg} alt="装饰背景" />
                  <div className={styles.device_title}>分控数量</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        {/* 中间内容-----左侧--用户增长趋势*/}
        <div className={styles.decoration_left_2}>
          <PreloadImage src={border} alt="边框" />
          <div className={styles.title_text}>用户增长趋势</div>
          <div className={styles.user_charts}>
            {userChartsData && userChartsData.length ? (
              <LineChartsCommon width={450} height={250} data={userChartsData} />
            ) : (
              <datav.Loading style={{ position: 'absolute' }}>Loading...</datav.Loading>
            )}
          </div>
        </div>
        {/* 中间内容-----地图 */}
        <div className={styles.decoration_map}>
          {/* 数据统计 */}
          <div style={{ display: 'flex', justifyContent: 'space-around' }}>
            <div className={styles.data_show}>
              <PreloadImage src={decoration_five} alt="背景边框" />
              <datav.DigitalFlop
                config={deviceStatistics}
                className={styles.data_show_num}
                style={{ width: '200px', height: '50px' }}
              />
              <div className={styles.data_show_title} style={{ color: '#08c7f1' }}>
                设备数
              </div>
            </div>
            <div className={styles.data_show}>
              <PreloadImage src={decoration_five} alt="背景边框" />
              <datav.DigitalFlop
                config={allRunTime}
                className={styles.data_show_num}
                style={{ width: '200px', height: '50px' }}
              />
              <div className={styles.data_show_title} style={{ color: '#ffb026' }}>
                总运行时长(小时)
              </div>
            </div>
            <div className={styles.data_show}>
              <PreloadImage src={decoration_five} alt="背景边框" />
              <datav.DigitalFlop
                config={todayRunTime}
                className={styles.data_show_num}
                style={{ width: '200px', height: '50px' }}
              />
              <div className={styles.data_show_title} style={{ color: '#0dde79' }}>
                今日运行时长(小时)
              </div>
            </div>
          </div>
          {areaDeviceList && areaDeviceList.length ? (
            <MapComponent userData={userNum} areaList={areaDeviceList} />
          ) : (
            <datav.Loading style={{ position: 'absolute' }}>Loading...</datav.Loading>
          )}
        </div>
        {/* 中间内容-----右侧 */}
        {/* 中间内容-----右侧--地区设备数量统计 */}
        <div className={styles.decoration_right_3}>
          <PreloadImage src={border} alt="边框" />
          <div className={styles.title_text}>地区设备数量统计</div>
          {areaDeviceList && areaDeviceList.length && <AreaDeviceData data={areaDeviceList} />}
        </div>
        {/* 中间内容-----右侧--设备增长趋势*/}
        <div className={styles.decoration_right_4}>
          <PreloadImage src={border} alt="边框" />
          <div className={styles.title_text}>设备增长趋势</div>
          {deviceChartsData && deviceChartsData.length ? (
            <LineChartsCommon width={450} height={250} data={deviceChartsData} />
          ) : (
            <datav.Loading style={{ position: 'absolute' }}>Loading...</datav.Loading>
          )}
        </div>
      </div>
      {/* 底部轮播 */}
      <div className={styles.dataBottom}>
        <div className="swiper-content">
          {homeInfo && homeInfo.length ? (
            <Slider {...settings} className="swiper-container">
              {homeInfo.map((res) => {
                return <SliderData key={res} data={res} />;
              })}
            </Slider>
          ) : (
            <datav.Loading style={{ position: 'absolute' }}>Loading...</datav.Loading>
          )}
        </div>
      </div>
    </div>
  );
};
export default DataBoard;
