import { defineComponent, reactive, onMounted, ref, onUnmounted } from 'vue';
import Draw from './draw';

export default defineComponent({
  components: {
    Draw
  },
  setup() {
    const drawTiming = ref(0);
    const cdata = reactive({
      year: null,
      weekCategory: [],
      dayInData: [],  // 新增：入库数据
      dayOutData: [], // 新增：出库数据
      maxData: 60,    // 调整最大值为60，根据数据范围
    });

    // 获取后端数据
    const fetchData = async () => {
      try {
        const token = localStorage.getItem('token') || 'PDA1'; // 从localStorage获取token
        const headers = new Headers({
          Accept: "application/json, text/plain, */*",
          token: token,
        });

        // const url = "http://192.168.31.105:8008/reportcenter/bigScreen/day/";
        const url = "http://192.168.18.200:8008/reportcenter/bigScreen/day/";
        const response = await fetch(url, {
          method: "GET",
          headers: headers,
        });
        
        if (!response.ok) throw new Error('网络响应异常');
        const data = await response.json();
        
        // 处理数据
        processData(data.results);
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 处理数据
    const processData = (results) => {
      // 清空数据
      cdata.weekCategory = [];
      cdata.dayInData = [];
      cdata.dayOutData = [];
      
      // 按日期排序 (修复类型错误)
      const sortedData = [...results].sort((a, b) => {
        const dateA = new Date(a.day).getTime();
        const dateB = new Date(b.day).getTime();
        return dateA - dateB;
      });
      
      // 提取数据
      sortedData.forEach(item => {
        cdata.weekCategory.push(item.day);
        cdata.dayInData.push(parseFloat(item.day_in));
        cdata.dayOutData.push(parseFloat(item.day_out));
      });
      
      // 计算最大值
      const allValues = [...cdata.dayInData, ...cdata.dayOutData];
      const maxValue = Math.max(...allValues);
      cdata.maxData = maxValue > 0 ? maxValue * 1.2 : 60; // 增加20%余量
    };

    // 定时更新数据
    const drawTimingFn = () => {
      fetchData();
      drawTiming.value = setInterval(() => {
        fetchData();
      }, 60000); // 每分钟更新一次
    };

    // 生命周期
    onMounted(() => {
      drawTimingFn();
    });

    onUnmounted(() => {
      clearInterval(drawTiming.value);
    });

    return () => {
      return <div>
        <Draw cdata={cdata} />
      </div>;
    };
  }
});
