<template>
    <div class="production-day-statistics">
        <div class="top-bar">
            <div class="title-group">
                <div class="query-group">
                    <span class="query-label">统计日期</span>
                    <el-date-picker v-model="queryDate" type="date" size="small" :clearable="false"
                        value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择日期" class="date-picker" />
                    <el-button type="primary" size="small" icon="el-icon-search" :loading="loading"
                        @click="getStatisticsData">
                        查询
                    </el-button>
                </div>
            </div>
        </div>

        <div class="lines-grid">
            <div class="line-section" v-for="line in lineConfigs" :key="line.key">
                <div class="section-header">
                    <div class="section-title-wrap">
                        <div class="section-accent"></div>
                        <div>
                            <div class="section-title">{{ line.title }}</div>
                            <div class="section-desc">上线、下线与 JPH 趋势</div>
                        </div>
                    </div>
                    <div class="section-tag">{{ queryDate }}</div>
                </div>

                <div class="summary-grid">
                    <div class="summary-card">
                        <div class="summary-name">今日上线</div>
                        <div class="summary-value">{{ lineDataMap[line.key].overview.今日上线 }}</div>
                    </div>
                    <div class="summary-card">
                        <div class="summary-name">今日下线</div>
                        <div class="summary-value">{{ lineDataMap[line.key].overview.今日下线 }}</div>
                    </div>
                    <div class="summary-card">
                        <div class="summary-name">净增差值</div>
                        <div class="summary-value">{{ lineDataMap[line.key].overview.净增差值 }}</div>
                        <div class="summary-note">说明：今日上线数量减去今日下线数量</div>
                    </div>
                </div>

                <div class="content-grid content-grid-pack">
                    <div class="panel chart-panel" v-loading="lineDataMap[line.key].chartLoading">
                        <div class="panel-title">{{ line.title }} JPH</div>
                        <div class="panel-subtitle">每小时上下线数量</div>
                        <div :ref="line.chartRef" class="chart-canvas"></div>
                    </div>

                    <div class="panel table-panel">
                        <div class="panel-title">{{ line.title }} 小时明细</div>
                        <div class="panel-subtitle">按小时查看上下线数量</div>
                        <el-table :data="lineDataMap[line.key].hourlyTableData"
                            :header-cell-style="{ background: '#f6f8fb', color: '#314257' }" border stripe size="mini"
                            class="hourly-table" height="100%">
                            <el-table-column prop="小时显示" label="小时" align="center" width="90" />
                            <el-table-column prop="上线数" label="上线" align="center" width="90" />
                            <el-table-column prop="下线数" label="下线" align="center" width="90" />
                            <el-table-column label="状态" align="center">
                                <template slot-scope="scope">
                                    <span :class="getHourStatusClass(scope.row)">{{ getHourStatusText(scope.row)
                                        }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: 'ProductionDayStatistics',
    data() {
        return {
            loading: false,
            pendingRequestCount: 0,
            queryDate: '',
            lineConfigs: [
                {
                    key: 'module',
                    title: '模组线',
                    searchType: 1,
                    chartRef: 'moduleChart'
                },
                {
                    key: 'pack',
                    title: 'PACK线',
                    searchType: 2,
                    chartRef: 'packChart'
                }
            ],
            lineDataMap: {
                module: {
                    overview: {
                        今日上线: 0,
                        今日下线: 0,
                        净增差值: 0
                    },
                    hourlyTableData: [],
                    chartLoading: false
                },
                pack: {
                    overview: {
                        今日上线: 0,
                        今日下线: 0,
                        净增差值: 0
                    },
                    hourlyTableData: [],
                    chartLoading: false
                }
            },
            chartInstances: {}
        }
    },
    created() {
        this.queryDate = this.getToday()
        this.getStatisticsData()
    },
    mounted() {
        window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.handleResize)
        Object.keys(this.chartInstances).forEach(key => {
            if (this.chartInstances[key]) {
                this.chartInstances[key].dispose()
            }
        })
        this.chartInstances = {}
    },
    methods: {
        getToday() {
            const now = new Date()
            const year = now.getFullYear()
            const month = `${now.getMonth() + 1}`.padStart(2, '0')
            const day = `${now.getDate()}`.padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        getStatisticsData() {
            this.loading = true
            this.pendingRequestCount = this.lineConfigs.length * 2
            this.lineConfigs.forEach(line => {
                this.getOverviewData(line)
                this.getHourlyData(line)
            })
        },
        finishRequest() {
            this.pendingRequestCount--
            if (this.pendingRequestCount <= 0) {
                this.loading = false
                this.pendingRequestCount = 0
            }
        },
        getOverviewData(line) {
            const param = []
            param[0] = ['查询日期', this.queryDate]
            param[1] = ['SearchType', line.searchType]
            const Data = this.CreateData('11', '生产统计_日总览_查询', param)
            this.ExecDatabase(Data).then(response => {
                const data = response.data && response.data.length > 0 ? response.data[0] : {}
                const onlineCount = Number(data['今日上线'] || 0)
                const offlineCount = Number(data['今日下线'] || 0)
                this.lineDataMap[line.key].overview = {
                    今日上线: onlineCount,
                    今日下线: offlineCount,
                    净增差值: onlineCount - offlineCount
                }
            }).catch(() => {
                this.lineDataMap[line.key].overview = {
                    今日上线: 0,
                    今日下线: 0,
                    净增差值: 0
                }
                this.$message.error(`${line.title}总览数据获取失败`)
            }).finally(() => {
                this.finishRequest()
            })
        },
        getHourlyData(line) {
            const param = []
            param[0] = ['查询日期', this.queryDate]
            param[1] = ['SearchType', line.searchType]
            const Data = this.CreateData('11', '生产统计_JPH小时上下线_查询', param)
            this.lineDataMap[line.key].chartLoading = true
            this.ExecDatabase(Data).then(response => {
                const data = Array.isArray(response.data) ? response.data : []
                const formattedData = data.length > 0 ? data.map(item => {
                    const hour = `${item['小时']}`.padStart(2, '0')
                    return {
                        小时: hour,
                        小时显示: hour,
                        上线数: Number(item['上线数'] || 0),
                        下线数: Number(item['下线数'] || 0)
                    }
                }) : this.createDefaultHours()
                this.lineDataMap[line.key].hourlyTableData = this.trimHourlyEdges(formattedData)
                this.drawChart(line)
            }).catch(() => {
                this.lineDataMap[line.key].hourlyTableData = []
                this.drawChart(line)
                this.$message.error(`${line.title}JPH数据获取失败`)
            }).finally(() => {
                this.lineDataMap[line.key].chartLoading = false
                this.finishRequest()
            })
        },
        createDefaultHours() {
            const list = []
            for (let i = 0; i < 24; i++) {
                const hour = `${i}`.padStart(2, '0')
                list.push({
                    小时: hour,
                    小时显示: hour,
                    上线数: 0,
                    下线数: 0
                })
            }
            return list
        },
        trimHourlyEdges(list) {
            if (!Array.isArray(list) || list.length === 0) {
                return []
            }
            const firstIndex = list.findIndex(item => item.上线数 > 0 || item.下线数 > 0)
            if (firstIndex === -1) {
                return []
            }
            let lastIndex = -1
            for (let i = list.length - 1; i >= 0; i--) {
                if (list[i].上线数 > 0 || list[i].下线数 > 0) {
                    lastIndex = i
                    break
                }
            }
            return list.slice(firstIndex, lastIndex + 1)
        },
        drawChart(line) {
            this.$nextTick(() => {
                const chartDom = this.$refs[line.chartRef]
                if (!chartDom) {
                    return
                }
                const chartEl = Array.isArray(chartDom) ? chartDom[0] : chartDom
                if (!this.chartInstances[line.key]) {
                    this.chartInstances[line.key] = echarts.init(chartEl)
                }
                const tableData = this.lineDataMap[line.key].hourlyTableData
                if (tableData.length === 0) {
                    this.chartInstances[line.key].clear()
                    this.chartInstances[line.key].setOption({
                        title: {
                            text: '当日暂无上下线数据',
                            left: 'center',
                            top: 'middle',
                            textStyle: {
                                color: '#8b97a6',
                                fontSize: 14,
                                fontWeight: 400
                            }
                        },
                        xAxis: {
                            show: false
                        },
                        yAxis: {
                            show: false
                        },
                        series: []
                    })
                    return
                }
                const option = {
                    color: ['#2f67d8', '#1d9b84'],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        right: 20,
                        top: 10,
                        textStyle: {
                            color: '#4c5d73'
                        }
                    },
                    grid: {
                        left: 24,
                        right: 20,
                        top: 44,
                        bottom: 24,
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: tableData.map(item => item.小时显示),
                        axisLine: {
                            lineStyle: {
                                color: '#b8c4d3'
                            }
                        },
                        axisLabel: {
                            color: '#5b6b7c',
                            interval: 0,
                            rotate: 0
                        }
                    },
                    yAxis: {
                        type: 'value',
                        minInterval: 1,
                        axisLabel: {
                            color: '#5b6b7c'
                        },
                        splitLine: {
                            lineStyle: {
                                color: '#e8edf3'
                            }
                        }
                    },
                    series: [
                        {
                            name: '上线',
                            type: 'bar',
                            barMaxWidth: 16,
                            data: tableData.map(item => item.上线数)
                        },
                        {
                            name: '下线',
                            type: 'bar',
                            barMaxWidth: 16,
                            data: tableData.map(item => item.下线数)
                        }
                    ]
                }
                this.chartInstances[line.key].clear()
                this.chartInstances[line.key].setOption(option)
            })
        },
        getHourStatusText(row) {
            if (row.上线数 === 0 && row.下线数 === 0) {
                return '无数据'
            }
            if (row.上线数 > row.下线数) {
                return '上线高'
            }
            if (row.上线数 < row.下线数) {
                return '下线高'
            }
            return '平衡'
        },
        getHourStatusClass(row) {
            if (row.上线数 === 0 && row.下线数 === 0) {
                return 'status-text status-empty'
            }
            if (row.上线数 > row.下线数) {
                return 'status-text status-online'
            }
            if (row.上线数 < row.下线数) {
                return 'status-text status-offline'
            }
            return 'status-text status-balance'
        },
        handleResize() {
            Object.keys(this.chartInstances).forEach(key => {
                if (this.chartInstances[key]) {
                    this.chartInstances[key].resize()
                }
            })
        }
    }
}
</script>

<style scoped>
.production-day-statistics {
    width: 100%;
    min-height: 100%;
    padding: 12px;
    background: linear-gradient(180deg, #eef3f8 0%, #e7edf4 100%);
    box-sizing: border-box;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: rgba(255, 255, 255, 0.92);
    border: 1px solid #d8e0ea;
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(38, 58, 89, 0.06);
    backdrop-filter: blur(8px);
}

.title-group {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.page-title {
    font-size: 24px;
    font-weight: 700;
    color: #1d2b3a;
    letter-spacing: 0.5px;
}

.query-group {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 10px;
    padding: 10px 12px;
    background: #f7f9fc;
    border: 1px solid #dde5ef;
    border-radius: 12px;
}

.query-label {
    font-size: 13px;
    color: #516274;
    font-weight: 600;
}

.date-picker {
    width: 180px;
}

.lines-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px;
    margin-top: 14px;
}

.line-section {
    background: rgba(255, 255, 255, 0.94);
    border: 1px solid #d8e0ea;
    border-radius: 18px;
    box-shadow: 0 10px 28px rgba(38, 58, 89, 0.06);
    overflow: hidden;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 18px;
    background: linear-gradient(180deg, #fbfcfe 0%, #f3f6fa 100%);
    border-bottom: 1px solid #e1e7ef;
}

.section-title-wrap {
    display: flex;
    align-items: center;
    gap: 12px;
}

.section-accent {
    width: 4px;
    height: 34px;
    border-radius: 999px;
    background: linear-gradient(180deg, #2f67d8 0%, #6aa1ff 100%);
}

.section-title {
    font-size: 16px;
    font-weight: 700;
    color: #233445;
}

.section-desc {
    margin-top: 4px;
    font-size: 12px;
    color: #768698;
}

.section-tag {
    padding: 5px 10px;
    background: #eef3f8;
    border: 1px solid #d8e2ec;
    border-radius: 999px;
    font-size: 12px;
    color: #556575;
}

.summary-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 12px;
    padding: 16px 18px;
}

.summary-card {
    padding: 16px 16px 14px 16px;
    border: 1px solid #e1e7ef;
    border-radius: 14px;
    background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
}

.summary-name {
    font-size: 13px;
    color: #667788;
}

.summary-value {
    margin-top: 8px;
    font-size: 32px;
    font-weight: 700;
    color: #223244;
    letter-spacing: 1px;
}

.summary-note {
    margin-top: 8px;
    font-size: 12px;
    line-height: 1.5;
    color: #7a8796;
}

.content-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.45fr) minmax(300px, 0.95fr);
    gap: 12px;
    padding: 0 18px 18px 18px;
}

.content-grid-pack {
    grid-template-columns: 1fr;
}

.panel {
    display: flex;
    flex-direction: column;
    min-height: 430px;
    padding: 14px 14px 12px 14px;
    border: 1px solid #e1e7ef;
    border-radius: 14px;
    background: #ffffff;
}

.panel-title {
    font-size: 15px;
    font-weight: 700;
    color: #233445;
}

.panel-subtitle {
    margin-top: 4px;
    margin-bottom: 10px;
    font-size: 12px;
    color: #6f7f8f;
}

.chart-canvas {
    width: 100%;
    height: 350px;
}

.hourly-table {
    flex: 1;
}

.status-text {
    display: inline-block;
    min-width: 54px;
    padding: 2px 8px;
    border-radius: 2px;
    font-size: 12px;
    line-height: 20px;
}

.status-online {
    color: #1d5ece;
    background: #eaf1ff;
    border: 1px solid #c8d9ff;
}

.status-offline {
    color: #0e7b67;
    background: #e6f6f2;
    border: 1px solid #bfe8dd;
}

.status-balance {
    color: #8a5b08;
    background: #fff6e5;
    border: 1px solid #f1ddb1;
}

.status-empty {
    color: #7a8695;
    background: #f0f3f6;
    border: 1px solid #d9e0e6;
}

::v-deep .date-picker .el-input__inner {
    border-radius: 2px;
}

@media (max-width: 1280px) {
    .lines-grid {
        grid-template-columns: 1fr;
    }

    .content-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {

    .top-bar,
    .query-group {
        flex-direction: column;
        align-items: flex-start;
    }

    .summary-grid {
        grid-template-columns: 1fr;
    }
}
</style>
