<template>
    <div class="quality-trend-container">
        <!-- 搜索区域 -->
        <el-card class="search-card" shadow="hover">
            <div class="search-form">
                <el-form :inline="true" size="small">
                    <el-form-item label="工位">
                        <el-select v-model="stationNo" filterable placeholder="请选择工位" style="width: 150px"
                            @change="handleStationChange">
                            <el-option v-for="item in stationList" :key="item.工位号" :label="item.工位号"
                                :value="item.工位号" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据项">
                        <el-select v-model="tagId" filterable placeholder="请选择数据项" style="width: 280px">
                            <el-option v-for="item in tagList" :key="item.TagID" :label="item.数据项"
                                :value="item.TagID" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间范围">
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="-"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
                            :picker-options="pickerOptions" style="width: 260px" @change="handleDateChange" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-data-line" @click="drawChart">绘制曲线</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧图表 -->
            <el-card class="chart-card" shadow="hover">
                <div slot="header" class="card-header">
                    <span class="header-title">
                        <i class="el-icon-data-line"></i> 质量趋势曲线
                    </span>
                    <div class="header-info" v-if="chartData.length > 0">
                        <el-tag size="small" type="success">数据点: {{ chartData.length }}</el-tag>
                        <el-tag size="small" type="info" style="margin-left: 8px">
                            上限: {{ chartInfo.upper || '-' }} | 下限: {{ chartInfo.lower || '-' }}
                        </el-tag>
                    </div>
                </div>
                <div ref="qualityChart" class="chart-container"></div>
            </el-card>

            <!-- 右侧统计 -->
            <div class="stats-section">
                <!-- 统计卡片 -->
                <el-card class="stats-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-marketing"></i> 统计分析
                        </span>
                    </div>
                    <div class="stats-grid">
                        <div class="stat-item">
                            <i class="el-icon-s-data stat-icon primary"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.count }}</div>
                                <div class="stat-label">数据点数</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <i class="el-icon-top stat-icon danger"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.max }}</div>
                                <div class="stat-label">最大值</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <i class="el-icon-bottom stat-icon success"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.min }}</div>
                                <div class="stat-label">最小值</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <i class="el-icon-s-operation stat-icon warning"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.avg }}</div>
                                <div class="stat-label">平均值</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <i class="el-icon-rank stat-icon info"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.stdDev }}</div>
                                <div class="stat-label">标准差</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <i class="el-icon-circle-check stat-icon success"></i>
                            <div class="stat-content">
                                <div class="stat-value">{{ statistics.passRate }}%</div>
                                <div class="stat-label">合格率</div>
                            </div>
                        </div>
                    </div>
                </el-card>

                <!-- CPK指标（简化版） -->
                <el-card class="cpk-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-platform"></i> 过程能力
                        </span>
                    </div>
                    <div class="cpk-display">
                        <div class="cpk-value" :class="cpkClass">{{ cpkValue }}</div>
                        <div class="cpk-label">CPK</div>
                        <!-- <div class="cpk-status">
                            <el-tag :type="cpkType" effect="dark">{{ cpkStatus }}</el-tag>
                        </div> -->
                    </div>
                    <!-- <div class="cpk-legend">
                        <div class="legend-item">
                            <span class="legend-color excellent"></span>
                            <span>≥1.33 优秀</span>
                        </div>
                        <div class="legend-item">
                            <span class="legend-color good"></span>
                            <span>≥1.0 良好</span>
                        </div>
                        <div class="legend-item">
                            <span class="legend-color poor"></span>
                            <span>&lt;1.0 需改进</span>
                        </div>
                    </div> -->
                </el-card>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: 'QualityTrend',
    data() {
        return {
            stationNo: '',
            stationList: [],
            tagId: '',
            tagList: [],
            dateRange: [],
            chartData: [],
            chartInfo: { upper: null, lower: null },
            chartInstance: null,
            pickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近7天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setDate(start.getDate() - 7)
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近30天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setDate(start.getDate() - 30)
                            picker.$emit('pick', [start, end])
                        }
                    }
                ]
            }
        }
    },
    computed: {
        statistics() {
            if (this.chartData.length === 0) {
                return { count: 0, max: '-', min: '-', avg: '-', stdDev: '-', passRate: '0.0' }
            }
            const values = this.chartData.map(item => parseFloat(item.测量值)).filter(v => !isNaN(v))
            if (values.length === 0) {
                return { count: 0, max: '-', min: '-', avg: '-', stdDev: '-', passRate: '0.0' }
            }

            const count = values.length
            const max = Math.max(...values).toFixed(3)
            const min = Math.min(...values).toFixed(3)
            const avg = (values.reduce((a, b) => a + b, 0) / count).toFixed(3)

            // 标准差
            const mean = parseFloat(avg)
            const squareDiffs = values.map(v => Math.pow(v - mean, 2))
            const avgSquareDiff = squareDiffs.reduce((a, b) => a + b, 0) / count
            const stdDev = Math.sqrt(avgSquareDiff).toFixed(4)

            // 合格率
            const upper = parseFloat(this.chartInfo.upper)
            const lower = parseFloat(this.chartInfo.lower)
            let passCount = count
            if (!isNaN(upper) && !isNaN(lower)) {
                passCount = values.filter(v => v >= lower && v <= upper).length
            }
            const passRate = (passCount / count * 100).toFixed(1)

            return { count, max, min, avg, stdDev, passRate }
        },
        cpkValue() {
            if (this.chartData.length < 2) return '-'
            const values = this.chartData.map(item => parseFloat(item.测量值)).filter(v => !isNaN(v))
            const upper = parseFloat(this.chartInfo.upper)
            const lower = parseFloat(this.chartInfo.lower)
            if (isNaN(upper) || isNaN(lower) || values.length < 2) return '-'

            const mean = values.reduce((a, b) => a + b, 0) / values.length
            const squareDiffs = values.map(v => Math.pow(v - mean, 2))
            const stdDev = Math.sqrt(squareDiffs.reduce((a, b) => a + b, 0) / values.length)
            if (stdDev === 0) return '-'

            const cpU = (upper - mean) / (3 * stdDev)
            const cpL = (mean - lower) / (3 * stdDev)
            const cpk = Math.min(cpU, cpL)

            return cpk.toFixed(2)
        },
        cpkClass() {
            const cpk = parseFloat(this.cpkValue)
            if (isNaN(cpk)) return ''
            if (cpk >= 1.33) return 'excellent'
            if (cpk >= 1.0) return 'good'
            return 'poor'
        },
        cpkType() {
            const cpk = parseFloat(this.cpkValue)
            if (isNaN(cpk)) return 'info'
            if (cpk >= 1.33) return 'success'
            if (cpk >= 1.0) return 'warning'
            return 'danger'
        },
        cpkStatus() {
            const cpk = parseFloat(this.cpkValue)
            if (isNaN(cpk)) return '无数据'
            if (cpk >= 1.33) return '优秀'
            if (cpk >= 1.0) return '良好'
            return '需改进'
        }
    },
    created() {
        this.setDefaultDate()
        this.loadStationList()
    },
    beforeDestroy() {
        if (this.chartInstance) this.chartInstance.dispose()
    },
    methods: {
        setDefaultDate() {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            const formatDate = (date) => {
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
            }
            this.dateRange = [formatDate(start), formatDate(end)]
        },
        loadStationList() {
            // 获取工位列表
            const param = []
            const Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.stationList = (response.data || []).map(item => ({ 工位号: item.工位号 }))
                if (this.stationList.length > 0) {
                    this.stationNo = this.stationList[0].工位号
                    this.loadTagList()
                }
            })
        },
        handleStationChange() {
            this.tagId = ''
            this.tagList = []
            this.chartData = []
            this.loadTagList()
        },
        handleDateChange() {
            // 时间范围变化时重新加载数据项列表
            this.tagId = ''
            this.tagList = []
            this.chartData = []
            if (this.stationNo && this.dateRange && this.dateRange.length === 2) {
                this.loadTagList()
            }
        },
        loadTagList() {
            if (!this.stationNo) return
            const param = [
                ['工位号', this.stationNo],
                ['开始时间', this.dateRange && this.dateRange.length === 2 ? this.dateRange[0] + ' 00:00:00' : ''],
                ['结束时间', this.dateRange && this.dateRange.length === 2 ? this.dateRange[1] + ' 23:59:59' : '']
            ]
            const Data = this.CreateData('11', '生产分析_质量趋势_数据项_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.tagList = response.data || []
                if (this.tagList.length > 0) {
                    this.tagId = this.tagList[0].TagID
                    this.chartInfo.upper = this.tagList[0].上限值
                    this.chartInfo.lower = this.tagList[0].下限值
                }
            })
        },
        drawChart() {
            if (!this.stationNo) {
                this.$message.warning('请选择工位')
                return
            }
            if (!this.tagId) {
                this.$message.warning('请选择数据项')
                return
            }
            if (!this.dateRange || this.dateRange.length !== 2) {
                this.$message.warning('请选择时间范围')
                return
            }

            const param = [
                ['工位号', this.stationNo],
                ['TagID', this.tagId],
                ['开始时间', this.dateRange[0]],
                ['结束时间', this.dateRange[1]]
            ]
            const Data = this.CreateData('11', '生产分析_质量趋势_数据_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.chartData = response.data || []
                if (this.chartData.length === 0) {
                    this.$message.info('该时间段内无数据')
                    if (this.chartInstance) this.chartInstance.clear()
                    return
                }
                if (this.chartData.length > 0) {
                    this.chartInfo.upper = this.chartData[0].上限值
                    this.chartInfo.lower = this.chartData[0].下限值
                }
                this.$nextTick(() => this.renderChart())
            })
        },
        renderChart() {
            const chartDom = this.$refs.qualityChart
            if (!chartDom) return

            if (this.chartInstance) this.chartInstance.dispose()
            this.chartInstance = echarts.init(chartDom)

            const xData = this.chartData.map(item => item.操作时间)
            const seriesData = this.chartData.map(item => ({
                value: parseFloat(item.测量值),
                工件编号: item.工件编号,
                操作时间: item.操作时间
            }))

            const upper = parseFloat(this.chartInfo.upper)
            const lower = parseFloat(this.chartInfo.lower)
            const markLineData = []

            if (!isNaN(upper)) {
                markLineData.push({
                    yAxis: upper,
                    name: '上限值',
                    lineStyle: { color: '#ff4d4f', type: 'dashed', width: 2 },
                    label: { formatter: '上限: {c}', position: 'end', color: '#ff4d4f' }
                })
            }
            if (!isNaN(lower)) {
                markLineData.push({
                    yAxis: lower,
                    name: '下限值',
                    lineStyle: { color: '#52c41a', type: 'dashed', width: 2 },
                    label: { formatter: '下限: {c}', position: 'end', color: '#52c41a' }
                })
            }

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const data = params[0].data
                        const status = (!isNaN(upper) && !isNaN(lower))
                            ? (data.value >= lower && data.value <= upper ? '✅ 合格' : '❌ 超限')
                            : ''
                        return `<div style="padding: 8px">
              <div><b>工件:</b> ${data.工件编号}</div>
              <div><b>时间:</b> ${data.操作时间}</div>
              <div><b>测量值:</b> ${data.value} ${status}</div>
            </div>`
                    }
                },
                grid: {
                    left: '60',
                    right: '40',
                    top: '40',
                    bottom: '60'
                },
                dataZoom: [
                    { type: 'inside', start: 0, end: 100 },
                    { type: 'slider', start: 0, end: 100, height: 20, bottom: 10 }
                ],
                xAxis: {
                    type: 'category',
                    data: xData,
                    axisLabel: {
                        rotate: 30,
                        fontSize: 10,
                        formatter: (value) => {
                            const date = new Date(value)
                            return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    scale: true,
                    axisLabel: { fontSize: 11 }
                },
                series: [{
                    type: 'line',
                    data: seriesData,
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    lineStyle: {
                        color: '#1890ff',
                        width: 2
                    },
                    itemStyle: {
                        color: (params) => {
                            const val = params.data.value
                            if (!isNaN(upper) && !isNaN(lower)) {
                                return (val >= lower && val <= upper) ? '#1890ff' : '#ff4d4f'
                            }
                            return '#1890ff'
                        }
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                            { offset: 1, color: 'rgba(24, 144, 255, 0.05)' }
                        ])
                    },
                    markLine: {
                        silent: true,
                        symbol: 'none',
                        data: markLineData
                    }
                }]
            }

            this.chartInstance.setOption(option)
        }
    }
}
</script>

<style scoped>
.quality-trend-container {
    padding: 15px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
    min-height: calc(100vh - 100px);
}

.search-card {
    margin-bottom: 15px;
    border-radius: 12px;
}

.search-card ::v-deep .el-card__body {
    padding: 15px 20px;
}

.search-form ::v-deep .el-form-item {
    margin-bottom: 0;
}

.main-content {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 15px;
}

.chart-card {
    border-radius: 12px;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.header-title {
    font-size: 15px;
    font-weight: 600;
    color: #1f2329;
}

.header-title i {
    margin-right: 8px;
    color: #1890ff;
}

.chart-container {
    height: 450px;
}

/* 统计区域 */
.stats-section {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.stats-card,
.cpk-card {
    border-radius: 12px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
}

.stat-item {
    display: flex;
    align-items: center;
    padding: 12px;
    background: #fafafa;
    border-radius: 10px;
    transition: all 0.3s;
}

.stat-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-icon {
    font-size: 24px;
    margin-right: 12px;
}

.stat-icon.primary {
    color: #1890ff;
}

.stat-icon.success {
    color: #52c41a;
}

.stat-icon.warning {
    color: #faad14;
}

.stat-icon.danger {
    color: #ff4d4f;
}

.stat-icon.info {
    color: #722ed1;
}

.stat-value {
    font-size: 18px;
    font-weight: 700;
    color: #1f2329;
}

.stat-label {
    font-size: 12px;
    color: #8c8c8c;
}

/* CPK */
.cpk-display {
    text-align: center;
    padding: 20px 0;
}

.cpk-value {
    font-size: 48px;
    font-weight: 700;
    line-height: 1;
}

.cpk-value.excellent {
    color: #52c41a;
}

.cpk-value.good {
    color: #faad14;
}

.cpk-value.poor {
    color: #ff4d4f;
}

.cpk-label {
    font-size: 14px;
    color: #8c8c8c;
    margin: 8px 0;
}

.cpk-status {
    margin-top: 10px;
}

.cpk-legend {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
}

.legend-item {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #8c8c8c;
}

.legend-color {
    width: 12px;
    height: 12px;
    border-radius: 3px;
    margin-right: 5px;
}

.legend-color.excellent {
    background: #52c41a;
}

.legend-color.good {
    background: #faad14;
}

.legend-color.poor {
    background: #ff4d4f;
}
</style>
