<script setup lang="ts">
import "./realBox.less";
import moment from "moment";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { formatNumberData, formatNumberTo } from "../../../options/serveice";
import { handlegetServerConnec } from "../../newService";

// 省份信息
const baseInfoObj = ref<any>();

// 实时钱的数据对象
let realMoney = reactive<any>({});
// 定时器 ID，用于清除定时器
let timer;
// 时间变动的定时器
const startTimer = () => {
  timer = setInterval(() => {
    realMoney.realTime = moment().format("YYYY-MM-DD HH:mm:ss"); // 每秒更新一次
  }, 1000);
};

// 拿到实时营收 和 年度的营收  并开启定时器
const handleGetRealMoney = async (province_code: any) => {
  let req = {
    action_type: "getServerConnect",
    province_code: province_code,
  };
  if (!req.province_code) {
    return;
  }
  const data = await handlegetServerConnec(req);
  let obj = data.CurrentData[0];
  console.log("data321321", obj);

  let yearReq = {
    action_type: "getYearRevenue",
    province_code: province_code,
  };
  if (!yearReq.province_code) {
    return;
  }
  const yearData = await handlegetServerConnec(yearReq);

  obj = {
    ...obj,
    YEAR_REVENUE: yearData.YEAR_REVENUE,
  };

  nextTick(() => {
    // 实际时间
    realMoney.realTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 赋值完开始启动定时器
    startTimer();

    updateValues(obj, true);

    // 定时变值
    startChangeValue();

    // 接口取的 实际需要动态变化的值
    // 实际营收
    // realMoney.TOTALPRICE = formatNumberTo(obj.TOTALPRICE);
    // // 人数
    // realMoney.TOTALTICKET = formatNumber(obj.TOTALTICKET);
    // // 已售商品
    // realMoney.CURSELLCOUNT = formatNumber(obj.CURSELLCOUNT);

    // // 根据上面的值 算出来的数据
    // // 人均消费
    // realMoney.personAvg = formatNumberTo(obj.TOTALPRICE / obj.TOTALTICKET);
    // // 商品均价
    // realMoney.AvgPrice = formatNumberTo(obj.TOTALPRICE / obj.CURSELLCOUNT);
    // startChangeValue();
  });
};

// 定时器 ID，用于清除定时器
let valueTimer;
// 其他数据的定时变动
const startChangeValue = () => {
  valueTimer = setInterval(() => {
    updateValues(realMoney, false);
  }, 10000);
};

const handleAnimateValue = (
  start: any,
  end: any,
  element: any,
  duration = 3000
) => {
  start = Number(start);
  end = Number(end);

  // 检查 element 是否为 null 或 undefined
  if (!element) {
    return;
  }

  let startTime: number | null = null;

  const step = (timestamp: number) => {
    if (!startTime) startTime = timestamp;
    const progress: number = Math.min((timestamp - startTime) / duration, 1);
    // 计算过渡的数字值，并格式化为两位小数
    const value = start + (end - start) * progress;
    // 判断是否有小数
    const isInteger = value % 1 === 0;
    // 更新 DOM 元素的文本内容
    if (isInteger) {
      element.textContent = formatNumberData(value);
    } else {
      element.textContent = formatNumberTo(value);
    }
    if (progress < 1) {
      requestAnimationFrame(step);
    }
  };
  requestAnimationFrame(step);
};

const updateValues = (obj?: any, haveObj?: boolean) => {
  let newObj: any = {};
  if (haveObj) {
    newObj = obj;
    newObj.personAvg = obj.TOTALPRICE / obj.TOTALTICKET;
    newObj.AvgPrice = obj.TOTALPRICE / obj.CURSELLCOUNT;
  } else {
    let oldObj: any = JSON.parse(JSON.stringify(realMoney));
    let num_1: number = Math.floor(Math.random() * 14) + 1; //人
    let num_2: number = Math.floor(Math.random() * 21) + 1; //商品
    let num_3: number = Math.random() * 462 + 1; //钱
    newObj.TOTALTICKET = oldObj.TOTALTICKET + num_1;
    newObj.TOTALPRICE = oldObj.TOTALPRICE + num_3;
    newObj.YEAR_REVENUE = oldObj.YEAR_REVENUE + num_3;
    newObj.CURSELLCOUNT = oldObj.CURSELLCOUNT + num_2;
    newObj.personAvg =
      (oldObj.TOTALPRICE + num_3) / (oldObj.TOTALTICKET + num_1);
    newObj.AvgPrice =
      (oldObj.TOTALPRICE + num_3) / (oldObj.CURSELLCOUNT + num_2);
  }

  // 动画更新
  // 人数
  const TOTALTICKETElement = document.querySelector(".TOTALTICKET");
  // 实际营收
  const TOTALPRICEElement = document.querySelector(" .TOTALPRICE");
  // 本年度累计营收额
  const YEAR_REVENUEElement = document.querySelector(".YEAR_REVENUE");
  // 人均消费
  const personAvgElement = document.querySelector(".personAvg");
  // 已售商品
  const CURSELLCOUNTElement = document.querySelector(".CURSELLCOUNT");
  // 商品均价
  const AvgPriceElement = document.querySelector(".AvgPrice");

  handleAnimateValue(
    realMoney.TOTALTICKET || 0,
    newObj?.TOTALTICKET || 0,
    TOTALTICKETElement
  );
  handleAnimateValue(
    realMoney.TOTALPRICE || 0,
    newObj?.TOTALPRICE || 0,
    TOTALPRICEElement
  );
  handleAnimateValue(
    realMoney.YEAR_REVENUE || 0,
    newObj?.YEAR_REVENUE || 0,
    YEAR_REVENUEElement
  );
  handleAnimateValue(
    realMoney.CURSELLCOUNT || 0,
    newObj?.CURSELLCOUNT || 0,
    CURSELLCOUNTElement
  );

  handleAnimateValue(
    realMoney.personAvg || 0,
    newObj.personAvg || 0,
    personAvgElement
  );
  handleAnimateValue(
    realMoney.AvgPrice || 0,
    newObj.AvgPrice || 0,
    AvgPriceElement
  );
  // 更新计算后的值
  // 人数
  realMoney.TOTALTICKET = newObj.TOTALTICKET;
  // 实际营收
  realMoney.TOTALPRICE = newObj.TOTALPRICE;
  // 年度总营收
  realMoney.YEAR_REVENUE = newObj.YEAR_REVENUE;
  // 人均消费
  realMoney.personAvg = newObj.personAvg;
  // 已售商品
  realMoney.CURSELLCOUNT = newObj.CURSELLCOUNT;
  // 商品均价
  realMoney.AvgPrice = newObj.AvgPrice;
};

// 传入的数据
const props = defineProps<{
  show: any;
}>();

watch(
  () => props.show,
  (newVal, oldVal) => {
    console.log("realboxnewVal", newVal);
    if (newVal) {
      let saveData = localStorage.getItem("baseInfoObj");
      if (saveData) {
        baseInfoObj.value = JSON.parse(saveData);
      }
      handleGetRealMoney(baseInfoObj.value.ProvinceId);
    }
  },
  { deep: true }
);

defineExpose({
  handleGetRealMoney: handleGetRealMoney,
});
</script>
<template>
  <div class="realBoxContent">
    <div class="leftBox">
      <div class="realTime">{{ realMoney.realTime || "-" }}</div>
      <div class="leftOther">
        <span class="label">服务司乘：</span>
        <span class="value TOTALTICKET">{{
          realMoney.TOTALTICKET || "-"
        }}</span>
        <span class="unit">人</span>
      </div>
    </div>

    <div class="middleBox">
      <div class="realText TOTALPRICE">
        {{ realMoney.TOTALPRICE || "-" }}<span class="unit">元</span>
      </div>
      <div class="yearRevenue">
        <span class="label">本年度累计营收额为：</span>
        <span class="value YEAR_REVENUE"
          >{{ realMoney.YEAR_REVENUE || "-" }}<span class="unit">元</span></span
        >
      </div>
    </div>

    <div class="rightBox">
      <div class="rightItem">
        <span class="label">人均消费：</span>
        <span class="value personAvg">{{ realMoney.personAvg || "-" }}</span>
        <span class="unit">元</span>
      </div>
      <div class="rightItem">
        <span class="label">已售商品：</span>
        <span class="value CURSELLCOUNT">{{
          realMoney.CURSELLCOUNT || "-"
        }}</span>
        <span class="unit">件</span>
      </div>
      <div class="rightItem">
        <span class="label">商品均价：</span>
        <span class="value AvgPrice">{{ realMoney.AvgPrice || "-" }}</span>
        <span class="unit">元</span>
      </div>
    </div>
  </div>
</template>