<template>
  <div class="app-container">
    <!-- 添加下拉选框 -->
    <div class="filter-container" style="margin-bottom: 20px;">
      <el-select
          v-model="selectedUpdateTime"
          placeholder="选择更新时间"
          style="width: 200px"
          @change="handleTimeChange"
      >
        <el-option
            v-for="time in updateTimes"
            :key="time"
            :label="time"
            :value="time"
        />
      </el-select>

      <!-- Toggle 开关 -->
      <el-switch
          v-model="showDiff"
          active-text="显示差值"
          inactive-text="显示当前值"
          style="margin-left: 20px"
      />

      <!-- 显示 matrixDiff 非零元素的总数 -->
      <span style="margin-left: 20px">
        非零差值总数: {{ nonZeroDiffCount }}
      </span>

      <span style="margin-left: 20px">
        正差值总数: {{ positiveDiffCount }}
        <el-select
            v-model="selectedPositiveDiff"
            placeholder="查看正差值详情"
            style="width: 300px; margin-left: 10px"
            :disabled="positiveDiffCount === 0"
        >
          <el-option
              v-for="(item, index) in positiveDiffList"
              :key="index"
              :label="`Spec: ${item.specification}, Model: ${item.model}, Value: ${item.value}`"
              :value="index"
          />
        </el-select>
      </span>

      <span style="margin-left: 20px">
        负差值总数: {{ negativeDiffCount }}
        <el-select
            v-model="selectedNegativeDiff"
            placeholder="查看负差值详情"
            style="width: 300px; margin-left: 10px"
            :disabled="negativeDiffCount === 0"
        >
          <el-option
              v-for="(item, index) in negativeDiffList"
              :key="index"
              :label="`Spec: ${item.specification}, Model: ${item.model}, Value: ${item.value}`"
              :value="index"
          />
        </el-select>
      </span>
    </div>

    <el-table
        :data="tableData"
        border
        style="width: 100%"
        :max-height="800"
    >
      <!-- 固定第一列为规格 -->
      <el-table-column
          prop="specification"
          label="规格"
          fixed="left"
          width="80"
          align="center"
      />

      <!-- 动态列为型号-轴型组合 -->
      <el-table-column
          v-for="(model, colIndex) in modelWireDiscs"
          :key="model"
          :label="model"
          width="100"
          align="center"
      >
        <template #default="scope">
          <span>
            {{ showDiff
              ? (matrixDiff[scope.$index]?.[colIndex] === 0 ? '' : matrixDiff[scope.$index]?.[colIndex] ?? '')
              : matrix[scope.$index]?.[colIndex] ?? '' }}
          </span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { listWmsImportResultHistory } from "@/api/system/WmsImportResultHistory"

// 定义规格数组
const specifications = ref([
  '0.060', '0.070', '0.080', '0.090', '0.100', '0.110', '0.120', '0.130',
  '0.140', '0.150', '0.160', '0.170', '0.180', '0.190', '0.200', '0.210',
  '0.220', '0.230', '0.240', '0.250', '0.260', '0.270', '0.280', '0.290',
  '0.300', '0.310', '0.320', '0.330', '0.340', '0.350', '0.370', '0.380',
  '0.390', '0.400', '0.410', '0.420', '0.430', '0.440', '0.450', '0.470',
  '0.490', '0.500', '0.510', '0.530', '0.550', '0.570', '0.590', '0.600',
  '0.620', '0.630', '0.640', '0.650', '0.670', '0.690', '0.700', '0.710',
  '0.720', '0.740', '0.750', '0.770', '0.800', '0.850', '0.860',
  '0.900', '0.930', '0.950', '1.000', '1.040', '1.060', '1.160', '1.180',
  '1.200', '1.250', '1.300', '1.350', '1.400', '1.450',
  '1.500', '1.560', '1.600', '1.680', '1.700', '1.740', '1.800', '1.900',
  '2.000', '2.120', '2.165', '2.240', '2.360', '2.400', '2.500', '2.600',
  '3.000'
])

// 定义型号-轴型组合
const modelWireDiscs = ref([
  'Q(ZY/XY)-2/200-PT-25', 'Q(ZY/XY)-2/200-PT-10', 'QA-1/155-PT-15',
  'QA-1/155-PT-25', 'QA-1/155-PT-4', 'QA-2/155-PT-15', 'QA-2/155-PT-4',
  'QZ-1/130L-PT-15', 'QZ-1/130L-PT-4', 'QZ-2/130L-PT-15', 'QZ-2/130L-PT-25',
  'QZ-2/155-PT-25', 'QZY-1/180-PT-10', 'QZY-2/180-PT-25', 'QZY-2/180-PT-60'
])

// 二维矩阵存储数据
const matrix = ref([])
// 用于表格显示的辅助数据
const tableData = ref([])
// 更新时间列表
const updateTimes = ref([])
// 选中的更新时间
const selectedUpdateTime = ref('')

const basetime = ref('2025-07-02 09:11:00')
const matrixDiff = ref([])
const baseMatrix = ref([])
const showDiff = ref(false)  // 控制 toggle

// 非零差值计数
const nonZeroDiffCount = ref(0)
// 正差值计数和列表
const positiveDiffCount = ref(0)
const positiveDiffList = ref([])
const selectedPositiveDiff = ref(null) // 新增：正差值选中的项
// 负差值计数和列表
const negativeDiffCount = ref(0)
const negativeDiffList = ref([])
const selectedNegativeDiff = ref(null) // 新增：负差值选中的项

// 计算 matrixDiff 中非零元素的数量和详细列表
function calculateNonZeroDiffCount(matrixDiff) {
  let nonZeroCount = 0
  let positiveCount = 0
  let negativeCount = 0
  const positiveList = []
  const negativeList = []

  matrixDiff.forEach((row, rowIndex) => {
    row.forEach((val, colIndex) => {
      if (val !== '' && val !== 0 && !isNaN(val)) {
        nonZeroCount++
        const diffItem = {
          specification: specifications.value[rowIndex],
          model: modelWireDiscs.value[colIndex],
          value: val
        }
        if (val > 0) {
          positiveCount++
          positiveList.push(diffItem)
        } else if (val < 0) {
          negativeCount++
          negativeList.push(diffItem)
        }
      }
    })
  })

  positiveDiffList.value = positiveList
  negativeDiffList.value = negativeList
  return { nonZeroCount, positiveCount, negativeCount }
}

watch(selectedUpdateTime, async (newTime) => {
  if (!newTime) return
  await fetchData()

  // 如果 basetime 的 matrix 还未加载，加载一次
  const response = await listWmsImportResultHistory({
    type: 1,
    pageNum: 1,
    pageSize: 999,
    updateTime: basetime.value,
  })

  if (response.rows) {
    baseMatrix.value = transformToMatrix(response.rows)
  }

  // 计算差值矩阵
  matrixDiff.value = matrix.value.map((row, i) =>
      row.map((val, j) => {
        const baseVal = baseMatrix.value?.[i]?.[j] || 0
        const currVal = val || 0
        const diff = parseFloat(currVal) - parseFloat(baseVal)
        return isNaN(diff) ? '' : diff
      })
  )

  const counts = calculateNonZeroDiffCount(matrixDiff.value)
  nonZeroDiffCount.value = counts.nonZeroCount
  positiveDiffCount.value = counts.positiveCount
  negativeDiffCount.value = counts.negativeCount
})

/**
 * 将原始数据转换为矩阵格式
 *
 * @param rawData 原始数据数组，每个元素包含 model、wireDisc、specification 和 totalNumber 属性
 * @returns 转换后的矩阵，矩阵的行数等于 specifications.value 的长度，列数等于 modelWireDiscs.value 的长度
 */
function transformToMatrix(rawData) {
  const newMatrix = Array(specifications.value.length).fill().map(() =>
      Array(modelWireDiscs.value.length).fill('')
  )
  rawData.forEach(item => {
    const itemModelWireDisc = `${item.model}-${item.wireDisc}`.trim().replace(/\s+/g, '')
    const itemSpec = Number(item.specification)
    const rowIndex = specifications.value.indexOf(itemSpec.toFixed(3))
    const colIndex = modelWireDiscs.value.indexOf(itemModelWireDisc)
    if (rowIndex !== -1 && colIndex !== -1) {
      newMatrix[rowIndex][colIndex] = item.totalNumber
    }
  })
  return newMatrix
}

// 生成最近24小时的更新时间（每小时的11分和41分）
function generateUpdateTimes() {
  const times = []
  const now = new Date()
  const currentMinutes = now.getMinutes()

  if (currentMinutes >= 42) {
    now.setMinutes(41)
  } else if (currentMinutes >= 11) {
    now.setMinutes(11)
  } else {
    now.setHours(now.getHours() - 1)
    now.setMinutes(41)
  }

  now.setSeconds(0)
  now.setMilliseconds(0)

  for (let i = 0; i < 48; i++) {
    const time = new Date(now.getTime() - i * 30 * 60 * 1000)
    const hours = String(time.getHours()).padStart(2, '0')
    const minutes = String(time.getMinutes()).padStart(2, '0')
    const formatted = `${time.getFullYear()}-${String(time.getMonth() + 1).padStart(2, '0')}-${String(time.getDate()).padStart(2, '0')} ${hours}:${minutes}:00`
    times.push(formatted)
  }
  return times
}

function transformData(rawData) {
  matrix.value = transformToMatrix(rawData)
  tableData.value = specifications.value.map((spec, index) => ({
    specification: spec,
    rowIndex: index
  }))
}

// 获取并处理数据
async function fetchData() {
  try {
    const query = {
      type: 1,
      pageNum: 1,
      pageSize: 999
    }

    if (selectedUpdateTime.value) {
      query.updateTime = selectedUpdateTime.value
    }

    const response = await listWmsImportResultHistory(query)
    if (response.rows) {
      transformData(response.rows)
    }
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

// 处理时间选择变化
function handleTimeChange() {
  fetchData()
}

onMounted(() => {
  updateTimes.value = generateUpdateTimes()
  selectedUpdateTime.value = updateTimes.value[0]
  fetchData()
})
</script>

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

:deep(.el-table) {
  /* 自定义表格样式 */
}

:deep(.el-table__header) {
  th {
    background-color: #f5f7fa;
    color: #606266;
  }
}

:deep(.el-table__row) {
  td {
    padding: 8px 0;
  }
}

:deep(.el-table__body) td {
  text-align: center;
}
</style>
