<template>
  <div class="card">
    <div class="card-header">
      <div class="card-title">
        <span class="card-title-icon">
          <Icon icon="fa-solid:wave-square" />
        </span>
        <span>产能完成数</span>
      </div>
      <div class="ops-header-right">
			<span class="tag">{{ summary }}</span>
		</div>
    </div>
    <div class="card-body">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { colors, style } from '../utils'
import { PlanApi } from '@/api/mes/plan'

const route = useRoute()

const opsDays: string[] = []
const opsLines: { name: string; value: number[] }[] = [
	{ name: '全部产线', value: [] }
]

const currentLine = ref(opsLines[0].name)
const summary = ref('')
const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const avg = (arr: number[]) => {
  return Math.round((arr.reduce((s, v) => s + v, 0) / arr.length) * 10) / 10
}

const updateOps = (lineName: string) => {
  currentLine.value = lineName
  const item = opsLines.find((x) => x.name === lineName) || opsLines[0]
	summary.value = `${item.name} · 日均完成 ${avg(item.value)}`

  if (!chart) return
  chart.setOption({
    xAxis: { data: opsDays },
		series: [{ data: item.value }]
  })
}

const loadOpsData = async () => {
	try {
		const orgId = route.query.orgId
		const res = await PlanApi.getLastSevenDaysCompletedCount({ orgId })
		const raw = res && typeof res === 'object' && 'data' in (res as any) ? (res as any).data : res
		const list = Array.isArray(raw) ? raw : []
		const days: string[] = []
		const values: number[] = []
		list.forEach((item: any) => {
			const src = item.day || item.date || item.time || item.hour || item.key || item.name || ''
			let label = src
			if (typeof label === 'string' && label.includes(' ')) {
				label = label.split(' ')[0]
			}
			days.push(label)
			const raw = item.totalWangong ?? item.count ?? 0
			const n = Number(raw)
			values.push(Number.isFinite(n) ? n : 0)
		})
		opsDays.length = 0
		opsDays.push(...days)
		opsLines.length = 0
		opsLines.push({ name: '全部产线', value: values })
		if (opsLines[0]) {
			currentLine.value = opsLines[0].name
			updateOps(currentLine.value)
		}
	} catch (e) {
		console.error('Failed to load ops trend:', e)
	}
}

const initChart = async () => {
  if (!chartRef.value) return
  chart = echarts.init(chartRef.value, 'dark', { renderer: 'canvas' })
  chart.setOption({
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis' },
    legend: { top: 0, right: 0, textStyle: style.legendText },
    grid: { top: '22%', left: '6%', right: '6%', bottom: '10%', containLabel: true },
    xAxis: { type: 'category', data: opsDays, axisLine: style.axisLine, axisLabel: style.axisLabel },
    yAxis: {
      type: 'value',
      name: '产能完成数',
      nameTextStyle: { color: '#a8b7d8', fontSize: 12 },
      axisLabel: style.axisLabel,
      splitLine: style.splitLine
    },
    series: [
      {
        name: '产能完成数',
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: { width: 2, color: colors.blue },
        itemStyle: { color: colors.blue },
        data: []
      }
    ]
  })
	await loadOpsData()
}

const resizeHandler = () => {
  chart?.resize()
}

onMounted(() => {
	initChart()
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  chart?.dispose()
})
</script>

<style scoped>
.card {
  position: relative;
  display: flex;
  padding: 10px;
  overflow: hidden;
  background: linear-gradient(135deg, rgb(15 23 42 / 96%), rgb(15 23 42 / 88%));
  border: 1px solid rgb(30 64 175 / 85%);
  border-radius: 10px;
  box-shadow:
    0 18px 45px rgb(15 23 42 / 95%),
    0 0 0 1px rgb(15 23 42 / 100%),
    inset 0 0 0 1px rgb(56 189 248 / 5%);
  flex-direction: column;
}

.card::before,
.card::after {
  position: absolute;
  width: 13px;
  height: 13px;
  pointer-events: none;
  border: 1px solid rgb(56 189 248 / 75%);
  border-radius: 2px;
  content: "";
  opacity: 0.6;
}

.card::before {
  top: -1px;
  left: -1px;
  border-right: none;
  border-bottom: none;
}

.card::after {
  right: -1px;
  bottom: -1px;
  border-top: none;
  border-left: none;
}

.card-header {
  display: flex;
  padding-bottom: 4px;
  margin-bottom: 8px;
  border-bottom: 1px solid rgb(41 54 95 / 90%);
  align-items: center;
  justify-content: space-between;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 700;
  color: #e5f0ff;
}

.card-title-icon {
  color: #22d3ee;
}

.card-body {
  display: flex;
  min-height: 0;
  flex: 1;
  flex-direction: column;
  gap: 8px;
}

.tag {
  padding: 2px 6px;
  font-size: 10px;
  color: #94a3b8;
  border: 1px solid rgb(148 163 184 / 40%);
  border-radius: 999px;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 180px;
}

@media (width <= 1600px) {
  .chart { min-height: 160px; }
}

.ops-header-right {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.tabs {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.tab-btn {
  padding: 3px 8px;
  font-size: 10px;
  line-height: 1;
  color: var(--muted);
  cursor: pointer;
  background: rgb(2 6 23 / 28%);
  border: 1px solid rgb(148 163 184 / 55%);
  border-radius: 999px;
  transition: border-color 0.25s, box-shadow 0.25s, color 0.25s, background 0.25s;
  user-select: none;
}

.tab-btn:hover {
  color: #e0f2fe;
  border-color: rgb(56 189 248 / 90%);
}

.tab-btn.active {
  color: #e0f2fe;
  background: radial-gradient(circle at 0 0, rgb(34 211 238 / 32%), rgb(2 6 23 / 20%) 60%);
  border-color: rgb(34 211 238 / 90%);
  box-shadow: 0 0 14px rgb(34 211 238 / 45%);
}
</style>
