<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleSummary"
          :loading="loading"
          v-hasPermi="['warehouse:WmsImportResult:query']"
        >获取维修汇总</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="repairSummaryList"
      element-loading-text="正在加载数据..."
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="equipment_code" label="设备编号" align="center" width="120" />
      <el-table-column prop="equipment_name" label="设备名称" align="center" min-width="200" />
      <el-table-column prop="record_count" label="维修次数" align="center" width="100" />
      <el-table-column prop="first_apply_time" label="首次维修时间" align="center" min-width="180" />
      <el-table-column prop="last_apply_time" label="最近维修时间" align="center" min-width="180" />
      <el-table-column label="距离上次维修天数" align="center" width="150">
        <template #default="scope">
          <el-tag
            :type="getDaysTagType(scope.row.days_since_last_repair)"
            effect="dark"
          >
            {{ scope.row.days_since_last_repair }} 天
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { API_CONFIG } from "@/config/api"

// 接收父组件传递的props
const props = defineProps({
  selectedEquipmentType: {
    type: String,
    default: '漆包机'
  }
})

const loading = ref(false)
const repairSummaryList = ref([])

// 监听设备类型变化
watch(() => props.selectedEquipmentType, (newVal, oldVal) => {
  console.log('设备类型从', oldVal, '变化为', newVal);
  // 如果当前是维修汇总组件，则重新获取数据
  if (newVal) {
    handleSummary();
  }
});

// 组件加载时自动获取数据
onMounted(() => {
  console.log('组件加载，设备类型:', props.selectedEquipmentType);
  handleSummary();
})

// 根据天数获取标签类型
const getDaysTagType = (days) => {
  if (days > 300) return 'danger'
  if (days > 180) return 'warning'
  if (days > 90) return 'success'
  return 'info'
}

// 获取维修汇总数据
function handleSummary() {
  console.log('设备类型:', props.selectedEquipmentType);
  loading.value = true
  fetch(`${API_CONFIG.BASE_URL}/api/eq-repair/enamelling-repair-summary?equipment_type=${props.selectedEquipmentType}`)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200 && data.data) {
        repairSummaryList.value = data.data
      }
    })
    .catch(error => {
      console.error('维修汇总API调用失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>