<template>
    <div class="efficiency-container">
        <!-- 顶部搜索区域 -->
        <el-card class="search-card" shadow="hover">
            <div class="search-form">
                <el-form :inline="true" size="small">
                    <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: 280px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="queryData">查询分析</el-button>
                        <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧图表区域 -->
            <div class="chart-section">
                <!-- 平均节拍柱状图 -->
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-data"></i> 各工位平均节拍对比
                        </span>
                        <!-- <el-tag v-if="bottleneckStation" type="danger" size="small" effect="dark">
                            <i class="el-icon-warning"></i> 瓶颈工位: {{ bottleneckStation }}
                        </el-tag> -->
                    </div>
                    <div ref="taktChart" class="chart-container"></div>
                </el-card>

                <!-- 吞吐量柱状图 -->
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-cooperation"></i> 各工位产品吞吐量
                        </span>
                    </div>
                    <div ref="throughputChart" class="chart-container"></div>
                </el-card>
            </div>

            <!-- 右侧数据区域 -->
            <div class="data-section">
                <!-- 汇总统计 -->
                <el-card class="summary-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-marketing"></i> 效率汇总
                        </span>
                    </div>
                    <div class="summary-grid">
                        <div class="summary-item">
                            <div class="summary-value primary">{{ totalStations }}</div>
                            <div class="summary-label">工位数量</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-value success">{{ totalProducts }}</div>
                            <div class="summary-label">产品过站总数</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-value warning">{{ avgTakt }}s</div>
                            <div class="summary-label">平均节拍</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-value info">{{ totalPassRate }}%</div>
                            <div class="summary-label">综合合格率</div>
                        </div>
                    </div>
                </el-card>

                <!-- 详细表格 -->
                <el-card class="table-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-document"></i> 工位效率明细
                        </span>
                    </div>
                    <el-table v-loading="loading" :data="tableData" :header-cell-style="headerCellStyle"
                        :row-class-name="tableRowClassName" border stripe size="small" max-height="400">
                        <el-table-column type="index" label="序号" width="55" align="center" />
                        <el-table-column prop="工位号" label="工位号" width="100" align="center">
                            <template slot-scope="scope">
                                <span :class="isBottleneck(scope.row) ? 'bottleneck-station' : ''">
                                    {{ scope.row.工位号 }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="过站数量" label="过站数量" width="90" align="center">
                            <template slot-scope="scope">
                                <span class="count-value">{{ scope.row.过站数量 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="平均节拍" width="100" align="center">
                            <template slot-scope="scope">
                                <el-tag :type="getTaktType(scope.row.平均节拍)" size="small" effect="dark">
                                    {{ formatTakt(scope.row.平均节拍) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="最长节拍" width="90" align="center">
                            <template slot-scope="scope">
                                <span class="max-takt">{{ formatTakt(scope.row.最长节拍) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="最短节拍" width="90" align="center">
                            <template slot-scope="scope">
                                <span class="min-takt">{{ formatTakt(scope.row.最短节拍) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="合格数量" label="合格数量" width="90" align="center" />
                        <el-table-column label="合格率" width="100" align="center">
                            <template slot-scope="scope">
                                <el-progress :percentage="Number(scope.row.合格率)"
                                    :color="getProgressColor(scope.row.合格率)" :stroke-width="10" :show-text="false"
                                    style="width: 60px; display: inline-block" />
                                <span style="margin-left: 5px">{{ scope.row.合格率 }}%</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: 'StationEfficiency',
    data() {
        return {
            loading: false,
            dateRange: [],
            tableData: [],
            taktChartInstance: null,
            throughputChartInstance: 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])
                        }
                    }
                ]
            },
            headerCellStyle: {
                background: 'linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)',
                color: '#ffffff',
                fontWeight: 'bold',
                fontSize: '13px'
            }
        }
    },
    computed: {
        totalStations() {
            return this.tableData.length
        },
        totalProducts() {
            return this.tableData.reduce((sum, item) => sum + (item.过站数量 || 0), 0)
        },
        avgTakt() {
            if (this.tableData.length === 0) return 0
            const total = this.tableData.reduce((sum, item) => sum + (item.平均节拍 || 0), 0)
            return Math.round(total / this.tableData.length)
        },
        totalPassRate() {
            if (this.tableData.length === 0) return '0.0'
            const totalPass = this.tableData.reduce((sum, item) => sum + (item.合格数量 || 0), 0)
            const totalCount = this.tableData.reduce((sum, item) => sum + (item.过站数量 || 0), 0)
            if (totalCount === 0) return '0.0'
            return (totalPass / totalCount * 100).toFixed(1)
        },
        bottleneckStation() {
            if (this.tableData.length === 0) return ''
            const sorted = [...this.tableData].sort((a, b) => (b.平均节拍 || 0) - (a.平均节拍 || 0))
            return sorted[0] ? sorted[0].工位号 : ''
        }
    },
    created() {
        this.setDefaultDate()
        this.queryData()
    },
    beforeDestroy() {
        if (this.taktChartInstance) this.taktChartInstance.dispose()
        if (this.throughputChartInstance) this.throughputChartInstance.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)]
        },
        queryData() {
            if (!this.dateRange || this.dateRange.length !== 2) {
                this.$message.warning('请选择时间范围')
                return
            }
            this.loading = true
            const param = [
                ['开始时间', this.dateRange[0] + ' 00:00:00'],
                ['结束时间', this.dateRange[1] + ' 23:59:59']
            ]
            const Data = this.CreateData('11', '生产分析_工位效率_统计_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.tableData = (response.data || []).sort((a, b) => a.工位号.localeCompare(b.工位号))
                this.loading = false
                this.$nextTick(() => {
                    this.drawTaktChart()
                    this.drawThroughputChart()
                })
            }).catch(() => {
                this.loading = false
                this.$message.error('查询失败')
            })
        },
        drawTaktChart() {
            if (!this.$refs.taktChart || this.tableData.length === 0) return

            if (this.taktChartInstance) this.taktChartInstance.dispose()
            this.taktChartInstance = echarts.init(this.$refs.taktChart)

            const sortedData = [...this.tableData].sort((a, b) => a.工位号.localeCompare(b.工位号))
            const stations = sortedData.map(item => item.工位号)
            const avgTakts = sortedData.map(item => item.平均节拍 || 0)
            const avgValue = this.avgTakt

            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' },
                    formatter: (params) => {
                        const item = sortedData[params[0].dataIndex]
                        return `<div style="padding: 10px">
              <div style="font-weight: bold; margin-bottom: 8px">${item.工位号}</div>
              <div>平均节拍: <b>${this.formatTakt(item.平均节拍)}</b></div>
              <div>最长: ${this.formatTakt(item.最长节拍)} | 最短: ${this.formatTakt(item.最短节拍)}</div>
            </div>`
                    }
                },
                grid: {
                    left: '50',
                    right: '30',
                    top: '30',
                    bottom: '50'
                },
                xAxis: {
                    type: 'category',
                    data: stations,
                    axisLabel: {
                        rotate: 45,
                        fontSize: 11
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '秒(s)',
                    nameTextStyle: { color: '#8c8c8c' }
                },
                series: [
                    {
                        type: 'bar',
                        data: avgTakts.map((val, idx) => ({
                            value: val,
                            itemStyle: {
                                color: val === Math.max(...avgTakts)
                                    ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#ff4d4f' },
                                        { offset: 1, color: '#ff7875' }
                                    ])
                                    : new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#1890ff' },
                                        { offset: 1, color: '#69c0ff' }
                                    ])
                            }
                        })),
                        barWidth: '50%',
                        label: {
                            show: true,
                            position: 'top',
                            formatter: (params) => this.formatTakt(params.value),
                            fontSize: 10
                        },
                        markLine: {
                            silent: true,
                            symbol: 'none',
                            data: [{
                                yAxis: avgValue,
                                lineStyle: { color: '#faad14', type: 'dashed', width: 2 },
                                label: { formatter: `平均: ${avgValue}s`, color: '#faad14' }
                            }]
                        }
                    }
                ]
            }
            this.taktChartInstance.setOption(option)
        },
        drawThroughputChart() {
            if (!this.$refs.throughputChart || this.tableData.length === 0) return

            if (this.throughputChartInstance) this.throughputChartInstance.dispose()
            this.throughputChartInstance = echarts.init(this.$refs.throughputChart)

            const sortedData = [...this.tableData].sort((a, b) => a.工位号.localeCompare(b.工位号))
            const stations = sortedData.map(item => item.工位号)
            const counts = sortedData.map(item => item.过站数量 || 0)
            const passCounts = sortedData.map(item => item.合格数量 || 0)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' }
                },
                legend: {
                    data: ['过站数量', '合格数量'],
                    top: 0
                },
                grid: {
                    left: '50',
                    right: '30',
                    top: '40',
                    bottom: '50'
                },
                xAxis: {
                    type: 'category',
                    data: stations,
                    axisLabel: {
                        rotate: 45,
                        fontSize: 11
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '件数'
                },
                series: [
                    {
                        name: '过站数量',
                        type: 'bar',
                        data: counts,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#1890ff' },
                                { offset: 1, color: '#69c0ff' }
                            ])
                        },
                        barWidth: '35%'
                    },
                    {
                        name: '合格数量',
                        type: 'bar',
                        data: passCounts,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#52c41a' },
                                { offset: 1, color: '#95de64' }
                            ])
                        },
                        barWidth: '35%'
                    }
                ]
            }
            this.throughputChartInstance.setOption(option)
        },
        formatTakt(seconds) {
            if (!seconds) return '-'
            if (seconds >= 60) {
                return `${Math.floor(seconds / 60)}m${seconds % 60}s`
            }
            return `${seconds}s`
        },
        getTaktType(seconds) {
            if (!seconds) return 'info'
            return 'success'
        },
        getProgressColor(rate) {
            if (rate >= 98) return '#52c41a'
            if (rate >= 95) return '#faad14'
            return '#ff4d4f'
        },
        isBottleneck(row) {
            return row.工位号 === this.bottleneckStation
        },
        tableRowClassName({ row }) {
            if (this.isBottleneck(row)) return 'bottleneck-row'
            return ''
        },
        resetSearch() {
            this.setDefaultDate()
            this.queryData()
        }
    }
}
</script>

<style scoped>
.efficiency-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 400px;
    gap: 15px;
}

.chart-section {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.chart-card,
.summary-card,
.table-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: 280px;
}

/* 汇总统计 */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.summary-item {
    background: #fafafa;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
    transition: all 0.3s;
}

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

.summary-value {
    font-size: 26px;
    font-weight: 700;
    line-height: 1.2;
}

.summary-value.primary {
    color: #1890ff;
}

.summary-value.success {
    color: #52c41a;
}

.summary-value.warning {
    color: #faad14;
}

.summary-value.info {
    color: #722ed1;
}

.summary-label {
    font-size: 13px;
    color: #8c8c8c;
    margin-top: 5px;
}

/* 表格样式 */
.data-section {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.count-value {
    font-weight: 600;
    color: #1890ff;
}

.max-takt {
    color: #ff4d4f;
}

.min-takt {
    color: #52c41a;
}

.bottleneck-station {
    color: #ff4d4f;
    font-weight: 700;
}

::v-deep .bottleneck-row {
    background-color: #fff1f0 !important;
}
</style>
