<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleRealTimeInventory"
          v-hasPermi="['warehouse:WmsImportResult:query']"
        >实时库存表</el-button>
        <el-button
          type="success"
          plain
          @click="handleEnamellingMachineStatus"
          v-hasPermi="['warehouse:WmsImportResult:query']"
        >漆包机台运行状态表</el-button>
        <el-button
          type="info"
          plain
          @click="handleEquipmentStatus"
          v-hasPermi="['warehouse:WmsImportResult:query']"
        >设备运行状态</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 动态内容显示区域 -->
    <el-row class="mb8">
      <el-col :span="24">
        <!-- 根据currentComponent动态切换组件 -->
        <component
          :is="currentComponent"
          v-if="currentComponent"
          :selected-time-range="queryForm.selectedTimeRange"
          :pareto-data="paretoData"
          :date-range="dateRange"
          :equipment-data="equipmentData"
          @ai-analysis-complete="handleAIAnalysisComplete"
        />
      </el-col>
    </el-row>

    <!-- 消息显示文本框 -->
    <el-row>
      <el-col :span="24">
        <el-input
          v-model="message"
          type="textarea"
          :rows="6"
          placeholder="API返回的消息将显示在这里"
          clearable
        />
      </el-col>
    </el-row>

  </div>

</template>

<script setup name="WmsImportResult">
import { ref, reactive, shallowRef, onMounted } from 'vue'
import { API_CONFIG } from "@/config/api"
import { getDateRangeByTimeRange } from "@/utils/dateFormat"
import ParetoAnalysis from './ParetoAnalysis.vue'
import ItemAnalysis from './ItemAnalysis.vue'
import EquipmentStatus from './EquipmentStatus.vue'
import EnamellingMachineStatus from './EnamellingMachineStatus.vue'
import RealTimeInventory from './RealTimeInventory.vue'
import EmptyContent from './EmptyContent.vue'

const showSearch = ref(true)
const single = ref(true)
const multiple = ref(true)
const message = ref("")
const timeRangeOptions = ref([
  { value: "近1年", label: "近1年" },
  { value: "近2年", label: "近2年" },
  { value: "近3年", label: "近3年" }
])
const queryForm = ref({
  selectedTimeRange: "近1年"
})
const paretoData = ref([])
const dateRange = ref({
  start_date: '',
  end_date: ''
})
const equipmentData = ref([])

// 当前显示的组件
const currentComponent = shallowRef(EmptyContent)

// 页面加载时自动显示实时库存表
onMounted(() => {
  handleRealTimeInventory()
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    model: null,
    specification: null,
    wireDisc: null,
    totalNumber: null,
    totalNetWeight: null,
    totalGrossWeight: null,
    type: 1,
    warningValue: null,
  },
  rules: {
  }
})

function handlePareto() {
  // 根据选择的时间范围计算开始和结束日期
  const dateRange = getDateRangeByTimeRange(queryForm.value.selectedTimeRange);
  const { start_date: startDateStr, end_date: endDateStr } = dateRange;

  // console.log(startDateStr, endDateStr);
  // 调用质检API并显示结果
  fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.PARETO_ANALYSIS}?start_date=${startDateStr}&end_date=${endDateStr}`)
    .then(response => response.json())
    .then(data => {
      message.value = data.message || `质检数据获取成功 (${queryForm.value.selectedTimeRange})`
      // 更新帕累托数据
      if (data.code === 200 && data.data) {
        paretoData.value = data.data;
        dateRange.value = {
          start_date: data.start_date,
          end_date: data.end_date
        };
        // 切换到帕累托分析组件
        currentComponent.value = ParetoAnalysis;
      }
    })
    .catch(error => {
      console.error('质检API调用失败:', error)
      message.value = '质检API调用失败'
    })
}

// 处理AI分析完成事件
function handleAIAnalysisComplete(result) {
  message.value = result;
}


// 项目分析按钮点击事件
function handleItemAnalysis() {
  // 切换到项目分析组件
  currentComponent.value = ItemAnalysis;
}

// 漆包机台运行状态表按钮点击事件
function handleEnamellingMachineStatus() {
  // 调用设备状态API
  fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.EQUIPMENT_STATUS}`)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200 && data.data && data.data.equipment_status_list) {
        equipmentData.value = data.data.equipment_status_list;
        message.value = data.message || '设备状态数据获取成功';
        // 切换到漆包机台状态组件
        currentComponent.value = EnamellingMachineStatus;
      } else {
        message.value = '设备状态数据获取失败';
      }
    })
    .catch(error => {
      console.error('设备状态API调用失败:', error);
      message.value = '设备状态API调用失败';
    });
}

// 设备状态按钮点击事件
function handleEquipmentStatus() {
  // 调用设备状态API
  fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.EQUIPMENT_STATUS}`)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200 && data.data && data.data.equipment_status_list) {
        equipmentData.value = data.data.equipment_status_list;
        message.value = data.message || '设备状态数据获取成功';
        // 切换到设备状态组件
        currentComponent.value = EquipmentStatus;
      } else {
        message.value = '设备状态数据获取失败';
      }
    })
    .catch(error => {
      console.error('设备状态API调用失败:', error);
      message.value = '设备状态API调用失败';
    });
}

// 实时库存表按钮点击事件
function handleRealTimeInventory() {
  message.value = '正在获取实时库存数据...';
  // 直接切换到实时库存组件，组件内部会自行获取数据
  currentComponent.value = RealTimeInventory;
}

// 处理查询表格事件
function getList() {
  // 根据当前组件状态执行相应的刷新操作
  if (currentComponent.value === EnamellingMachineStatus) {
    // 刷新漆包机台运行状态表
    handleEnamellingMachineStatus();
  } else if (currentComponent.value === EquipmentStatus) {
    // 刷新设备状态
    handleEquipmentStatus();
  } else if (currentComponent.value === RealTimeInventory) {
    // 刷新实时库存表
    message.value = '正在获取实时库存数据...';
    currentComponent.value = RealTimeInventory;
  }
}

</script>

<style>
/* 在全局样式文件中添加 */
.el-dialog {
margin-top: 0 !important;
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
}

.statistics-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.statistics-info p {
  margin: 5px 0;
  font-size: 14px;
}

.ai-analysis-content {
  padding: 10px 0;
}
</style>
