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

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['warehouse:WmsImportResult:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="3">
        <el-form :model="queryForm" label-width="80px">
          <el-form-item label="数据范围">
            <el-select v-model="queryForm.selectedTimeRange" placeholder="选择时间范围" style="width: 100%">
              <el-option
                v-for="item in timeRangeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handlePareto"
            v-hasPermi="['warehouse:WmsImportResult:add']"
        >帕累托分析</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          @click="handleItemAnalysis"
          v-hasPermi="['warehouse:WmsImportResult:edit']"
        >项目分析</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:WmsImportResult:remove']"
        >趋势分析</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleExport"
          v-hasPermi="['warehouse:WmsImportResult:export']"
        >产品特征分析</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"
          @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 } from 'vue'
import { API_CONFIG } from "@/config/api"
import ParetoAnalysis from './ParetoAnalysis.vue'
import ItemAnalysis from './ItemAnalysis.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 currentComponent = shallowRef(EmptyContent)

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 endDate = new Date();
  const startDate = new Date();

  if (queryForm.value.selectedTimeRange === '近1年') {
    startDate.setFullYear(endDate.getFullYear() - 1);
  } else if (queryForm.value.selectedTimeRange === '近2年') {
    startDate.setFullYear(endDate.getFullYear() - 2);
  } else if (queryForm.value.selectedTimeRange === '近3年') {
    startDate.setFullYear(endDate.getFullYear() - 3);
  }

  // 格式化日期为 YYYY-MM-DD
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const startDateStr = formatDate(startDate);
  const endDateStr = formatDate(endDate);

  // 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;
}

</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>
