<template>
  <div class="enamelling-machine-container">
    <div class="table-header">
      <h3>漆包机台运行状态表</h3>
      <div class="table-actions">
        <el-button @click="refreshData" type="primary" size="small">刷新数据</el-button>
      </div>
    </div>
    
    <!-- 筛选器容器 -->
    <div class="filters-row">
      <div class="filter-container">
        <span class="filter-label">完成度筛选:</span>
        <el-select v-model="selectedCompletionLevel" @change="onCompletionLevelChange" placeholder="请选择完成度" style="width: 150px">
          <el-option label="全部显示" value="all" />
          <el-option label="0% - 25%" value="low" />
          <el-option label="25% - 75%" value="medium" />
          <el-option label="75% - 100%" value="high" />
          <el-option label="100%" value="full" />
        </el-select>
      </div>
      
      <div class="filter-container">
        <span class="filter-label">机台筛选:</span>
        <el-select v-model="selectedEquipment" @change="onEquipmentChange" placeholder="请选择机台" style="width: 200px">
          <el-option label="全部机台" value="all" />
          <el-option 
            v-for="equipment in equipmentList" 
            :key="equipment" 
            :label="equipment" 
            :value="equipment" 
          />
        </el-select>
      </div>
    </div>
    
    <!-- 调试信息 -->
    <div v-if="!loading" style="margin-bottom: 10px; font-size: 12px; color: #666;">
      调试信息: 获取到 {{ equipmentData.length }} 条设备数据，筛选后 {{ filteredEquipmentData.length }} 条，表格共 {{ tableData.length }} 行
    </div>
    
    <div v-loading="loading" class="table-wrapper">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        border
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
        empty-text="暂无数据"
        :scrollbar-always-on="true"
      >
        <el-table-column 
          prop="equipment_code" 
          label="设备编号" 
          width="120" 
          fixed="left"
        />
        
        <el-table-column 
          prop="axle_number" 
          label="轴号" 
          width="100" 
        />
        
        
        <el-table-column 
          prop="specification" 
          label="规格" 
          width="100" 
        />
        
        <el-table-column 
          prop="model" 
          label="型号" 
          width="100" 
        />
        
        <el-table-column 
          prop="raw_wire_disc" 
          label="原料线盘" 
          width="120" 
        />
        
        <!-- <el-table-column 
          prop="wire_disc" 
          label="线盘" 
          width="100" 
        /> -->
        
        <el-table-column 
          prop="wight_completion" 
          label="完成重量(kg)" 
          width="120" 
        >
          <template #default="scope">
            {{ scope.row.wight_completion }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="degree_of_completion" 
          label="完成度(%)" 
          width="100" 
        >
          <template #default="scope">
            {{ (scope.row.degree_of_completion * 100).toFixed(2)}}%
          </template>
        </el-table-column>

        <el-table-column 
          prop="total_number" 
          label="总箱数" 
          width="100" 
        >
          <template #default="scope">
            {{ scope.row.total_number || '-' }}
          </template>
        </el-table-column>

        <el-table-column 
          prop="total_net_weight" 
          label="总净重(kg)" 
          width="110" 
        >
          <template #default="scope">
            {{ scope.row.total_net_weight || '-' }}
          </template>
        </el-table-column>

        <el-table-column 
          prop="total_gross_weight" 
          label="总毛重(kg)" 
          width="110" 
        >
          <template #default="scope">
            {{ scope.row.total_gross_weight || '-' }}
          </template>
        </el-table-column>

        <el-table-column 
          prop="update_time" 
          label="更新时间" 
          width="180" 
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.update_time) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="status" 
          label="状态" 
          width="100" 
          fixed="right"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="销售历史" 
          width="100" 
          fixed="right"
        >
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="showSalesHistory(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 销售历史图表对话框 -->
    <el-dialog
      v-model="showChartDialog"
      :title="`销售历史 - ${salesChartTitle}`"
      width="90%"
      destroy-on-close
      @close="closeChart"
    >
      <div class="chart-controls">
        <span class="filter-label">时间范围:</span>
        <el-select v-model="selectedTimeRange" @change="onChartTimeRangeChange" style="width: 120px">
          <el-option label="近1天" value="近1天" />
          <el-option label="近3天" value="近3天" />
          <el-option label="近1周" value="近1周" />
          <el-option label="近1月" value="近1月" />
        </el-select>
        <span class="filter-label" style="margin-left: 20px;">显示单位:</span>
        <el-radio-group v-model="chartUnit" @change="onChartUnitChange" size="small">
          <el-radio-button value="box">箱数</el-radio-button>
          <el-radio-button value="weight">重量</el-radio-button>
        </el-radio-group>
      </div>
      <div v-if="salesChartLoading || historyChartLoading" v-loading="true" class="chart-loading" style="height: 400px;"></div>
      <div v-else-if="!hasSalesData && !hasHistoryData" class="no-data-message" style="height: 400px;">
        暂无销售和库存数据
      </div>
      <div v-show="!salesChartLoading && (hasSalesData || hasHistoryData)" ref="salesChartDialogRef" class="chart" style="height: 450px;"></div>
    </el-dialog>
    
    <!-- 销售历史图表（表格下方显示） -->
    <div v-if="showChart" class="sales-chart-container">
      <div class="chart-header">
        <h4>销售历史 - {{ salesChartTitle }}</h4>
        <el-button size="small" @click="closeChart">关闭</el-button>
      </div>
      <div class="chart-controls">
        <span class="filter-label">时间范围:</span>
        <el-select v-model="selectedTimeRange" @change="onChartTimeRangeChange" style="width: 120px">
          <el-option label="近1天" value="近1天" />
          <el-option label="近3天" value="近3天" />
          <el-option label="近1周" value="近1周" />
          <el-option label="近1月" value="近1月" />
        </el-select>
        <span class="filter-label" style="margin-left: 20px;">显示单位:</span>
        <el-radio-group v-model="chartUnit" @change="onChartUnitChange" size="small">
          <el-radio-button value="box">箱数</el-radio-button>
          <el-radio-button value="weight">重量</el-radio-button>
        </el-radio-group>
      </div>
      <div v-if="salesChartLoading || historyChartLoading" v-loading="true" class="chart-loading"></div>
      <div v-else-if="!hasSalesData && !hasHistoryData" class="no-data-message">
        暂无销售和库存数据
      </div>
      <div v-show="!salesChartLoading && (hasSalesData || hasHistoryData)" ref="salesChartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { API_CONFIG } from "@/config/api"
import { getDateRangeByTimeRange } from '@/utils/dateFormat';
import * as echarts from 'echarts';

// 接收从父组件传递的数据
const props = defineProps({
  equipmentData: {
    type: Array,
    default: () => []
  }
})

// 响应式数据
const loading = ref(false)
const equipmentData = ref([])

// 机台筛选相关状态
const selectedEquipment = ref('all')

// 完成度筛选相关状态
const selectedCompletionLevel = ref('all') // 默认显示全部

const salesChartLoading = ref(false)
const historyChartLoading = ref(false)
const salesData = ref([])
const historyData = ref([])
const hasSalesData = ref(false)
const hasHistoryData = ref(false)
const selectedTimeRange = ref('近1月')
const chartUnit = ref('box')
const salesChartTitle = ref('')
const currentSalesAxle = ref(null)
const salesChartRef = ref(null)
const salesChartDialogRef = ref(null)
let salesChart = null

// 销售图表相关状态
const showChart = ref(false)
const showChartDialog = ref(false)

// 当组件加载时，使用父组件传递的数据
equipmentData.value = props.equipmentData

// 计算属性：获取设备列表（用于筛选器）
const equipmentList = computed(() => {
  // 从设备数据中提取唯一的设备代码
  return [...new Set(equipmentData.value.map(equipment => equipment.equipment_code))].sort();
});

// 计算属性：筛选后的设备数据
const filteredEquipmentData = computed(() => {
  // 根据选择的机台筛选数据
  if (selectedEquipment.value === 'all') {
    return equipmentData.value;
  } else {
    return equipmentData.value.filter(equipment => equipment.equipment_code === selectedEquipment.value);
  }
});

// 设备代码与轴号的映射表
const equipmentAxlesMap = {
  'QB001': ['左边', '右边'],
  'QB002': ['左边', '右边'],
  'QB003': ['左边', '右边'],
  'QB004': ['左1', '左2', '左3', '左4', '左5', '右1', '右2', '右3', '右4', '右5'],
  'QB0042': ['左1', '左2', '左3', '左4', '左5', '右1', '右2', '右3', '右4', '右5'],
  'QB005': ['左1', '左2', '左3', '左4', '左5', '左6', '右1', '右2', '右3', '右4', '右5', '右6'],
  'QB007': ['左边', '右边'],
  'QB008': ['左边', '右边'],
  'QB009': ['左边', '右边'],
  'QB010': ['左边', '右边'],
  'QB011': ['左边', '右边'],
  'QB012': ['左边', '右边'],
  'QB013': ['左边', '右边'],
  'QB014': ['左边', '右边'],
  'QB015': ['左边', '右边'],
  'QB016': ['左边', '右边'],
  'QB017': ['左边', '右边'],
  'QB018': ['左1', '左2', '右1', '右2'],
  'QB019': ['左1', '左2', '右1', '右2'],
  'QB020': ['左1', '左2', '右1', '右2'],
  'QB024': ['左1', '左2', '左3', '左4', '右1', '右2', '右3', '右4'],
  'QB025': ['左边', '右边'],
  'QB026': ['左边', '右边'],
  'QB027': ['左边', '右边'],
  'QB028': ['左1', '左2', '右1', '右2'],
  'QB029': ['左边', '右边'],
  'QB030': ['左边', '右边'],
  'QB031': ['左边', '右边'],
  'QB032': ['左边', '右边'],
  'QB033': ['左边', '右边'],
  'QB034': ['左边', '右边']
};

const isMoreThanOneWeek = (startDate, endDate) => {
  if (!startDate || !endDate) return false;
  const start = new Date(startDate);
  const end = new Date(endDate);
  const diffDays = (end - start) / (1000 * 60 * 60 * 24);
  return diffDays > 7;
};

const downsampleHistoryToKeyTimes = (records, targetHours = [8, 12, 16, 18]) => {
  if (!records?.length) return [];

  const groups = new Map();
  records.forEach(item => {
    const dt = new Date(item.create_time);
    const dateKey = dt.toISOString().split('T')[0];
    if (!groups.has(dateKey)) groups.set(dateKey, []);
    groups.get(dateKey).push({ dt, item });
  });

  const result = [];

  groups.forEach((items, dateKey) => {
    items.sort((a, b) => a.dt - b.dt);

    const selected = new Map();

    targetHours.forEach(targetH => {
      let closest = null;
      let minDiff = Infinity;

      items.forEach(({ dt, item }) => {
        const diff = Math.abs((dt.getHours() - targetH) * 60 + dt.getMinutes());
        if (diff < minDiff) {
          minDiff = diff;
          closest = item;
        }
      });

      if (closest && minDiff <= 90) {
        selected.set(targetH, closest);
      }
    });

    targetHours.forEach(h => {
      if (selected.has(h)) {
        result.push(selected.get(h));
      }
    });
  });

  result.sort((a, b) => new Date(a.create_time) - new Date(b.create_time));
  return result;
};

// 判断是否应该显示轴
const shouldShowAxle = (degree) => {
  if (!degree) return false;
  
  const percentage = degree * 100;
  
  switch (selectedCompletionLevel.value) {
    case 'all':
      return true;
    case 'low':
      return percentage >= 0 && percentage < 25;
    case 'medium':
      return percentage >= 25 && percentage < 75;
    case 'high':
      return percentage >= 75 && percentage < 100;
    case 'full':
      return percentage >= 100;
    default:
      return true;
  }
};

// 计算属性：展开状态记录为表格行数据
const tableData = computed(() => {
  if (!filteredEquipmentData.value.length) return [];
  
  // 展开每个设备的状态记录为表格行
  const rows = [];
  filteredEquipmentData.value.forEach(equipment => {
    if (equipment.status_records && equipment.status_records.length > 0) {
      equipment.status_records.forEach(record => {
        // 检查完成度是否符合筛选条件
        if (shouldShowAxle(record.degree_of_completion)) {
          rows.push({
            ...record,
            equipment_code: equipment.equipment_code
          });
        }
      });
    }
  });
  
  // 按照设备编号和轴号排序
  return rows.sort((a, b) => {
    // 先按设备编号排序
    const equipmentCompare = a.equipment_code.localeCompare(b.equipment_code);
    if (equipmentCompare !== 0) {
      return equipmentCompare;
    }
    
    // 如果设备编号相同，则按轴号排序
    return sortByAxleNumber(a.axle_number, b.axle_number, a.equipment_code);
  });
});

// 按轴号排序的函数
const sortByAxleNumber = (axleA, axleB, equipmentCode) => {
  // 获取设备对应的预期轴号列表
  const validAxles = equipmentAxlesMap[equipmentCode] || [];
  
  // 获取两个轴号在有效轴号列表中的索引
  const getIndexInValidAxles = (axleNumber) => {
    // 处理复合轴号（如"左1,左2"），取第一个轴号的索引
    const firstAxle = axleNumber ? axleNumber.split(',')[0] : '';
    return validAxles.indexOf(firstAxle);
  };
  
  const aIndex = getIndexInValidAxles(axleA);
  const bIndex = getIndexInValidAxles(axleB);
  
  // 如果两个轴号都在有效轴号列表中，按索引排序
  if (aIndex !== -1 && bIndex !== -1) {
    return aIndex - bIndex;
  }
  
  // 如果只有一个在有效轴号列表中，有效轴号排在前
  if (aIndex !== -1) return -1;
  if (bIndex !== -1) return 1;
  
  // 如果都不在有效轴号列表中，按字符串排序
  return (axleA || '').localeCompare(axleB || '');
};

// 方法：获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.EQUIPMENT_STATUS}`);
    const result = await response.json();
    
    if (result.code === 200 && result.data && result.data.equipment_status_list) {
      equipmentData.value = result.data.equipment_status_list;
      console.log('API返回数据:', result.data.equipment_status_list);
    } else {
      console.error('获取设备状态数据失败:', result.message);
    }
  } catch (error) {
    console.error('API调用失败:', error);
  } finally {
    loading.value = false;
  }
};

// 方法：刷新数据
const refreshData = () => {
  fetchData();
};

// 方法：处理机台筛选变化
const onEquipmentChange = () => {
  console.log('选择的机台:', selectedEquipment.value);
};

// 方法：处理完成度筛选变化
const onCompletionLevelChange = () => {
  console.log('选择的完成度:', selectedCompletionLevel.value);
};

// 方法：显示销售历史图表
const showSalesHistory = (row) => {
  if (!row.update_time || !row.model || !row.specification) {
    console.error('缺少必要的数据参数');
    return;
  }
  
  currentSalesAxle.value = { ...row };
  salesChartTitle.value = `${row.equipment_code} - ${row.axle_number} - ${row.specification} - ${row.model}`;
  
  if (selectedEquipment.value === 'all') {
    showChartDialog.value = true;
  } else {
    showChart.value = true;
  }
  
  salesData.value = [];
  historyData.value = [];
  hasSalesData.value = false;
  hasHistoryData.value = false;
  
  fetchSalesData(row.model, row.specification);
  fetchHistoryData(row.model, row.specification, row.wire_disc);
};

// 方法：关闭图表
const closeChart = () => {
  showChart.value = false;
  showChartDialog.value = false;
  if (salesChart) {
    salesChart.dispose();
    salesChart = null;
  }
};

// 方法：图表时间范围变化
const onChartTimeRangeChange = () => {
  if (currentSalesAxle.value) {
    fetchSalesData(currentSalesAxle.value.model, currentSalesAxle.value.specification);
    fetchHistoryData(currentSalesAxle.value.model, currentSalesAxle.value.specification, currentSalesAxle.value.wire_disc);
  }
};

// 方法：图表单位切换
const onChartUnitChange = () => {
  if (hasSalesData.value || hasHistoryData.value) {
    nextTick(() => {
      setTimeout(() => {
        initSalesChart();
      }, 100);
    });
  }
};

// 获取销量数据
const fetchSalesData = (model, specification) => {
  salesChartLoading.value = true;
  
  const dateRange = getDateRangeByTimeRange(selectedTimeRange.value);
  
  let apiUrl = `${API_CONFIG.BASE_URL}/api/sale/records?model=${model}&specification=${specification}&start_date=${dateRange.start_date}&end_date=${dateRange.end_date}`;
  
  fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200 && data.data) {
        salesData.value = data.data;
        hasSalesData.value = salesData.value.length > 0;
        
        nextTick(() => {
          setTimeout(() => {
            initSalesChart();
          }, 100);
        });
      } else {
        salesData.value = [];
        hasSalesData.value = false;
      }
    })
    .catch(error => {
      console.error('销量数据API调用失败:', error);
      salesData.value = [];
      hasSalesData.value = false;
    })
    .finally(() => {
      salesChartLoading.value = false;
    });
};

// 获取库存历史数据
const fetchHistoryData = (model, specification, wireDisc) => {
  historyChartLoading.value = true;
  
  const dateRange = getDateRangeByTimeRange(selectedTimeRange.value);
  
  let apiUrl = `${API_CONFIG.BASE_URL}/api/plan/wms/history?model=${model}&specification=${specification}&wire_disc=${wireDisc}&start_date=${dateRange.start_date}&end_date=${dateRange.end_date}`;
  
  fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200 && data.data && data.data.records) {
        let records = data.data.records;

        if (isMoreThanOneWeek(dateRange.start_date, dateRange.end_date)) {
          const beforeCount = records.length;
          records = downsampleHistoryToKeyTimes(records);
          console.log(`库存数据降采样：${beforeCount} → ${records.length} 条 (时间范围超过1周)`);
        }

        historyData.value = records;
        hasHistoryData.value = records.length > 0;
        
        nextTick(() => {
          setTimeout(() => {
            initSalesChart();
          }, 100);
        });
      } else {
        historyData.value = [];
        hasHistoryData.value = false;
      }
    })
    .catch(error => {
      console.error('库存历史数据API调用失败:', error);
      historyData.value = [];
      hasHistoryData.value = false;
    })
    .finally(() => {
      historyChartLoading.value = false;
    });
};

// 初始化销售图表
const initSalesChart = (retryCount = 0) => {
  if (!hasSalesData.value && !hasHistoryData.value) {
    return;
  }
  
  const isDialog = showChartDialog.value;
  const chartRef = isDialog ? salesChartDialogRef.value : salesChartRef.value;
  
  if (!chartRef) {
    if (retryCount >= 20) {
      return;
    }
    setTimeout(() => {
      initSalesChart(retryCount + 1);
    }, 50);
    return;
  }
  
  if (salesChart) {
    salesChart.dispose();
  }
  
  salesChart = echarts.init(chartRef);
  
  const salesDateMap = new Map();
  const historyDateMap = new Map();
  
  if (hasSalesData.value && salesData.value.length > 0) {
    salesData.value.forEach((item, index) => {
      const dateStr = item.date;
      const date = new Date(dateStr);
      if (!isNaN(date.getTime())) {
        const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}-${index}`;
        const existing = salesDateMap.get(dateKey);
        if (existing) {
          existing.boxCount += item.box_count || 0;
          existing.weight += item.weight || 0;
        } else {
          salesDateMap.set(dateKey, {
            displayDate: `${date.getMonth() + 1}/${date.getDate()}`,
            boxCount: item.box_count || 0,
            weight: item.weight || 0
          });
        }
      }
    });
  }
  
  if (hasHistoryData.value && historyData.value.length > 0) {
    historyData.value.forEach((item, index) => {
      const dateStr = item.create_time;
      const date = new Date(dateStr);
      if (!isNaN(date.getTime())) {
        const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}-${index}`;
        historyDateMap.set(dateKey, {
          displayDate: `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`,
          totalNumber: item.total_number ?? null,
          totalNetWeight: item.total_net_weight ?? null
        });
      }
    });
  }
  
  const allDates = new Set([...salesDateMap.keys(), ...historyDateMap.keys()]);
  
  const sortedDates = Array.from(allDates).sort((a, b) => {
    const timeA = a.split('-').slice(0, 3).join('-');
    const timeB = b.split('-').slice(0, 3).join('-');
    return new Date(timeA) - new Date(timeB);
  });
  
  const dates = [];
  const salesBoxData = [];
  const salesWeightData = [];
  const historyBoxData = [];
  const historyWeightData = [];
  
  sortedDates.forEach(dateKey => {
    const salesItem = salesDateMap.get(dateKey);
    const historyItem = historyDateMap.get(dateKey);
    
    if (salesItem || historyItem) {
      dates.push(salesItem?.displayDate || historyItem?.displayDate);
      salesBoxData.push(salesItem?.boxCount ?? null);
      salesWeightData.push(salesItem?.weight ?? null);
      historyBoxData.push(historyItem?.totalNumber ?? null);
      historyWeightData.push(historyItem?.totalNetWeight ?? null);
    }
  });
  
  const isBoxUnit = chartUnit.value === 'box';
  const chartSalesData = isBoxUnit ? salesBoxData : salesWeightData;
  const chartHistoryData = isBoxUnit ? historyBoxData : historyWeightData;
  const yAxisName = isBoxUnit ? '箱数' : '重量(kg)';
  const historyName = isBoxUnit ? '库存箱数' : '库存重量(kg)';
  const salesName = isBoxUnit ? '销售箱数' : '销售重量(kg)';
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      textStyle: {
        fontSize: 14
      }
    },
    legend: {
      data: [salesName, historyName],
      top: 10,
      textStyle: {
        fontSize: 14
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        interval: Math.floor(dates.length / 10),
        rotate: 30,
        fontSize: 13
      },
      axisLine: {
        lineStyle: {
          fontSize: 13
        }
      }
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      position: 'left',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#5470C6'
        }
      },
      axisLabel: {
        fontSize: 13
      },
      nameTextStyle: {
        fontSize: 14
      }
    },
    series: [
      {
        name: salesName,
        type: 'bar',
        data: chartSalesData,
        itemStyle: {
          color: '#5470C6'
        },
        barGap: '10%',
        connectNulls: true,
        label: {
          show: false
        }
      },
      {
        name: historyName,
        type: 'line',
        data: chartHistoryData,
        itemStyle: {
          color: '#91CC75'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'none',
        connectNulls: true,
        label: {
          show: false
        }
      }
    ]
  };
  
  salesChart.setOption(option);
  
  window.addEventListener('resize', () => {
    if (salesChart) {
      salesChart.resize();
    }
  });
};

// 方法：格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    return dateTimeStr;
  }
};

// 方法：获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '1':
      return 'success';
    case '2':
      return 'warning';
    case '3':
      return 'danger';
    default:
      return 'info';
  }
};

// 方法：获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case '1':
      return '运行中';
    case '2':
      return '待机';
    case '3':
      return '故障';
    default:
      return '未知';
  }
};

// 组件挂载时获取数据
onMounted(() => {
  // 如果组件是通过按钮点击加载的，则不需要在挂载时获取数据
  // 因为数据已经通过父组件的 handleEnamellingMachineStatus 方法获取了
});

// 监听图表显示状态，初始化图表
watch(showChart, (newValue) => {
  if (newValue && hasSalesData.value) {
    nextTick(() => {
      setTimeout(() => {
        initSalesChart();
      }, 100);
    });
  }
});
</script>

<style scoped>
.enamelling-machine-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 筛选器行样式 */
.filters-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  align-items: center;
  flex-wrap: wrap;
}

/* 筛选器样式 */
.filter-container {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
  white-space: nowrap;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
  white-space: nowrap;
}

:deep(.el-table td) {
  padding: 8px 0;
  white-space: nowrap;
}

.sales-chart-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: 80vw;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.chart-loading {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-data-message {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.chart {
  width: 100%;
  min-height: 350px;
}
</style>