<template>
  <div class="card">
    <div class="card-header">
      <div class="card-title">
        <span class="card-title-icon">
          <Icon icon="fa-solid:check-double" />
        </span>
        <span>成品检合格率趋势图</span>
      </div>
      <span class="tag">按天统计（全产线）</span>
    </div>
    <div class="card-body">
      <div id="chart-quality" class="chart"></div>
    </div>
  </div>
</template>

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

const route = useRoute()
const orgId = route.query.orgId

const { init } = useChart('chart-quality')

const last7Days: string[] = []
for (let i = 6; i >= 0; i--) {
  const d = new Date()
  d.setDate(d.getDate() - i)
  last7Days.push(`${d.getMonth() + 1}-${d.getDate()}`)
}

const passRate = [98.5, 99.2, 97.8, 98.9, 99.0, 98.2, 99.5]

type QualityPoint = {
  label: string
  rate: number
}

const normalizeQualityData = (raw: any): QualityPoint[] => {
  if (!raw) return []
  const source = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw
  const rows: QualityPoint[] = []

  if (Array.isArray(source)) {
    source.forEach((row: any) => {
      const rawDate = row?.day ?? row?.date ?? row?.statDate ?? row?.createDate ?? ''
      const rawLabel = typeof rawDate === 'string' ? rawDate : String(rawDate || '')
      const label = rawLabel.length >= 10 ? rawLabel.slice(5, 10).replace('-', '/') : rawLabel
      const rawRate = row?.rate ?? row?.passRate ?? row?.qualifiedRate ?? row?.value ?? 0
      const n = Number(rawRate)
      const rate = Number.isNaN(n) ? 0 : n
      rows.push({ label, rate })
    })
  } else if (source && typeof source === 'object') {
    const entries = Object.entries(source).sort(([a], [b]) => a.localeCompare(b))
    entries.forEach(([key, value]) => {
      const rawLabel = String(key || '')
      const label = rawLabel.length >= 10 ? rawLabel.slice(5, 10).replace('-', '/') : rawLabel
      const n = Number(value)
      const rate = Number.isNaN(n) ? 0 : n
      rows.push({ label, rate })
    })
  }

  return rows.filter((item) => item.label)
}

onMounted(async () => {
  let xAxisData = last7Days.slice()
  let seriesData = passRate.slice()

  try {
    const data = await PlanApi.getLastDaysRate({ orgId })
    const list = normalizeQualityData(data)
    if (list.length > 0) {
      xAxisData = list.map((item) => item.label)
      seriesData = list.map((item) => item.rate)
    }
  } catch {
  }

  const chart = init()
  if (!chart) return

  chart.setOption({
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis' },
    grid: { top: '18%', left: '6%', right: '6%', bottom: '10%', containLabel: true },
    xAxis: { type: 'category', data: xAxisData, axisLine: style.axisLine, axisLabel: style.axisLabel },
    yAxis: { type: 'value', min: 0, max: 100, axisLine: { show: false }, axisLabel: style.axisLabel, splitLine: style.splitLine },
    series: [{
      name: '合格率',
      type: 'bar',
      barWidth: '45%',
      itemStyle: {
        borderRadius: [6, 6, 0, 0],
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors.purple },
          { offset: 1, color: 'rgba(139,92,246,0.10)' }
        ])
      },
      data: seriesData,
      markLine: {
        symbol: ['none', 'none'],
        label: { show: true, color: '#fff', fontSize: 12, formatter: '平均 {c}%' },
        lineStyle: { color: colors.cyan, width: 2, type: 'dashed' },
        data: [{ type: 'average', name: '平均值' }]
      }
    }]
  })
})
</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; }
}
</style>
