<template>
    <div class="production-analysis-container">
        <!-- 顶部统计卡片 -->
        <div class="stats-cards">
            <div class="stat-card primary">
                <div class="stat-icon">
                    <i class="el-icon-s-data"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ summaryData.length }}</div>
                    <div class="stat-label">产品总数</div>
                </div>
            </div>
            <div class="stat-card success">
                <div class="stat-icon">
                    <i class="el-icon-circle-check"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ completedCount }}</div>
                    <div class="stat-label">已完成</div>
                </div>
            </div>
            <div class="stat-card warning">
                <div class="stat-icon">
                    <i class="el-icon-time"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ avgTaktTime }}</div>
                    <div class="stat-label">平均节拍(min)</div>
                </div>
            </div>
            <div class="stat-card info">
                <div class="stat-icon">
                    <i class="el-icon-s-operation"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ passRate }}%</div>
                    <div class="stat-label">工位合格率</div>
                </div>
            </div>
        </div>

        <!-- 搜索区域 -->
        <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: 260px" />
                    </el-form-item>
                    <el-form-item label="产品编号">
                        <el-input v-model="searchForm.productId" placeholder="请输入产品编号" clearable style="width: 200px" />
                    </el-form-item>
                    <el-form-item label="订单号">
                        <el-input v-model="searchForm.orderId" placeholder="请输入订单号" clearable style="width: 200px" />
                    </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-button type="success" icon="el-icon-download" @click="exportExcel">导出</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card" shadow="hover">
            <div slot="header" class="card-header">
                <span class="header-title">
                    <i class="el-icon-s-data"></i> 产品节拍明细
                </span>
                <span class="header-tips">点击行展开查看工位详情</span>
            </div>
            <el-table ref="summaryTable" v-loading="loading" :data="summaryData" :header-cell-style="headerCellStyle"
                :row-class-name="tableRowClassName" :row-key="row => row.产品编号" border stripe highlight-current-row
                style="width: 100%" @expand-change="handleExpandChange">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <div class="expand-content" v-loading="!scope.row.details">
                            <!-- 详情表格 -->
                            <div class="detail-section">
                                <div class="section-title">
                                    <i class="el-icon-document"></i> 工位过站详情
                                    <el-tag size="mini" type="info" style="margin-left: 10px">共 {{ (scope.row.details ||
                                        []).length }} 个工位</el-tag>
                                </div>
                                <el-table :data="scope.row.details || []" size="mini" border stripe
                                    :header-cell-style="{ background: '#f0f9ff', color: '#1890ff' }">
                                    <el-table-column type="index" label="序号" width="60" align="center" />
                                    <el-table-column prop="工位号" label="工位号" width="120" align="center" />
                                    <el-table-column prop="到达时间" label="到达时间" min-width="160" align="center" />
                                    <el-table-column prop="离开时间" label="离开时间" min-width="160" align="center" />
                                    <el-table-column label="在线时间" width="120" align="center">
                                        <template slot-scope="detailScope">
                                            <span :class="getTaktClass(detailScope.row.在线时间)">
                                                {{ formatTaktTime(detailScope.row.在线时间) }}
                                            </span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="状态" width="100" align="center">
                                        <template slot-scope="detailScope">
                                            <el-tag
                                                :type="detailScope.row.是否合格 === '合格' ? 'success' : detailScope.row.是否合格 === '不合格' ? 'danger' : 'info'"
                                                size="small">
                                                {{ detailScope.row.是否合格 }}
                                            </el-tag>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="产品编号" label="产品编号" min-width="200" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span class="product-id">{{ scope.row.产品编号 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="订单号" label="订单号" min-width="180" show-overflow-tooltip />
                <el-table-column prop="产品型号" label="产品型号" width="160" align="center" />
                <el-table-column label="上线时间" width="160" align="center">
                    <template slot-scope="scope">
                        <span class="time-text">{{ formatDateTime(scope.row.上线时间) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="下线时间" width="160" align="center">
                    <template slot-scope="scope">
                        <span class="time-text">{{ formatDateTime(scope.row.下线时间) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="总生产时间" width="120" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getProductionTimeType(scope.row.总生产时间)" effect="dark">
                            {{ formatProductionTime(scope.row.总生产时间) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="过站/合格" width="100" align="center">
                    <template slot-scope="scope">
                        <span class="station-count">
                            {{ scope.row.过站工位数 }}/{{ scope.row.合格工位数 }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination background :current-page="pagination.currentPage" :page-sizes="[20, 50, 100, 200]"
                    :page-size="pagination.pageSize" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: 'ProductTaktTime',
    data() {
        return {
            loading: false,
            dateRange: [],
            searchForm: {
                productId: '',
                orderId: ''
            },
            summaryData: [],
            currentExpandRow: null,
            chartInstance: null,
            pagination: {
                currentPage: 1,
                pageSize: 50,
                total: 0
            },
            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: '14px'
            }
        }
    },
    computed: {
        completedCount() {
            return this.summaryData.filter(item => item.下线时间).length
        },
        avgTaktTime() {
            if (this.summaryData.length === 0) return '0.0'
            const total = this.summaryData.reduce((sum, item) => sum + (item.总生产时间 || 0), 0)
            return (total / this.summaryData.length / 60).toFixed(1)
        },
        passRate() {
            if (this.summaryData.length === 0) return '0.0'
            const totalStations = this.summaryData.reduce((sum, item) => sum + (item.过站工位数 || 0), 0)
            const passStations = this.summaryData.reduce((sum, item) => sum + (item.合格工位数 || 0), 0)
            if (totalStations === 0) return '0.0'
            return (passStations / totalStations * 100).toFixed(1)
        }
    },
    created() {
        this.setDefaultDate()
        this.queryData()
    },
    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)]
        },
        queryData() {
            if (!this.dateRange || this.dateRange.length !== 2) {
                this.$message.warning('请选择时间范围')
                return
            }
            this.loading = true
            // 收起所有展开行
            if (this.$refs.summaryTable) {
                this.summaryData.forEach(row => {
                    this.$refs.summaryTable.toggleRowExpansion(row, false)
                })
            }
            const param = [
                ['开始时间', this.dateRange[0] + ' 00:00:00'],
                ['结束时间', this.dateRange[1] + ' 23:59:59'],
                ['发动机号', this.searchForm.productId || ''],
                ['订单号', this.searchForm.orderId || '']
            ]
            const Data = this.CreateData('11', '生产分析_产品节拍_汇总_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.summaryData = response.data || []
                this.pagination.total = this.summaryData.length
                this.loading = false
            }).catch(() => {
                this.loading = false
                this.$message.error('查询失败，请检查网络连接')
            })
        },
        handleExpandChange(row, expandedRows) {
            // 当展开行时加载详情
            if (expandedRows.includes(row)) {
                this.loadDetailData(row)
            }
        },
        loadDetailData(row) {
            if (row.details && row.details.length > 0) return // 已加载过则不重复加载
            const param = [['发动机号', row.产品编号]]
            const Data = this.CreateData('11', '生产分析_产品节拍_明细_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.$set(row, 'details', response.data || [])
            })
        },
        drawGanttChart(details) {
            if (!details || details.length === 0) return

            const chartDom = this.$refs.ganttChart
            if (!chartDom) return

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

            const categories = details.map(item => item.工位号)
            const baseTime = new Date(details[0].到达时间).getTime()

            const data = details.map((item, index) => {
                const startTime = new Date(item.到达时间).getTime()
                const endTime = new Date(item.离开时间).getTime()
                return {
                    name: item.工位号,
                    value: [index, startTime, endTime, item.在线时间],
                    itemStyle: {
                        color: item.是否合格 === '合格'
                            ? new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#52c41a' },
                                { offset: 1, color: '#95de64' }
                            ])
                            : item.是否合格 === '不合格'
                                ? new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                    { offset: 0, color: '#ff4d4f' },
                                    { offset: 1, color: '#ff7875' }
                                ])
                                : new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                    { offset: 0, color: '#1890ff' },
                                    { offset: 1, color: '#69c0ff' }
                                ])
                    }
                }
            })

            const option = {
                tooltip: {
                    formatter: (params) => {
                        const item = details[params.value[0]]
                        return `<div style="padding: 5px">
              <div style="font-weight: bold; margin-bottom: 5px">${item.工位号}</div>
              <div>到达: ${item.到达时间}</div>
              <div>离开: ${item.离开时间}</div>
              <div>节拍: ${this.formatTaktTime(item.在线时间)}</div>
              <div>状态: ${item.是否合格}</div>
            </div>`
                    }
                },
                grid: {
                    left: '80',
                    right: '40',
                    top: '20',
                    bottom: '30'
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        formatter: (value) => {
                            const date = new Date(value)
                            return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
                        }
                    }
                },
                yAxis: {
                    type: 'category',
                    data: categories,
                    axisLabel: {
                        fontSize: 12
                    }
                },
                series: [{
                    type: 'custom',
                    renderItem: (params, api) => {
                        const categoryIndex = api.value(0)
                        const start = api.coord([api.value(1), categoryIndex])
                        const end = api.coord([api.value(2), categoryIndex])
                        const height = api.size([0, 1])[1] * 0.6

                        return {
                            type: 'rect',
                            shape: {
                                x: start[0],
                                y: start[1] - height / 2,
                                width: end[0] - start[0],
                                height: height,
                                r: 4
                            },
                            style: api.style()
                        }
                    },
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data
                }]
            }

            this.chartInstance.setOption(option)
        },
        formatDateTime(dateStr) {
            if (!dateStr) return '-'
            const date = new Date(dateStr)
            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')}`
        },
        formatProductionTime(seconds) {
            if (!seconds) return '-'
            const minutes = Math.floor(seconds / 60)
            const hours = Math.floor(minutes / 60)
            if (hours > 0) {
                return `${hours}h${minutes % 60}m`
            }
            return `${minutes}min`
        },
        formatTaktTime(seconds) {
            if (!seconds) return '-'
            if (seconds >= 60) {
                return `${Math.floor(seconds / 60)}m${seconds % 60}s`
            }
            return `${seconds}s`
        },
        getProductionTimeType(seconds) {
            if (!seconds) return 'info'
            return 'success'
        },
        getTaktClass(seconds) {
            if (!seconds) return ''
            if (seconds > 300) return 'takt-danger'
            if (seconds > 180) return 'takt-warning'
            return 'takt-success'
        },
        tableRowClassName({ row }) {
            if (row.合格工位数 < row.过站工位数) {
                return 'row-warning'
            }
            return ''
        },
        resetSearch() {
            this.searchForm = { productId: '', orderId: '' }
            this.setDefaultDate()
            this.queryData()
        },
        exportExcel() {
            if (this.summaryData.length === 0) {
                this.$message.warning('暂无数据可导出')
                return
            }
            const param = [
                ['开始时间', this.dateRange[0] + ' 00:00:00'],
                ['结束时间', this.dateRange[1] + ' 23:59:59'],
                ['发动机号', this.searchForm.productId || ''],
                ['订单号', this.searchForm.orderId || '']
            ]
            const Data = this.CreateData('2001', '生产分析_产品节拍_汇总_查询', param)
            this.exportExcel_NPOI(Data)
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val
        },
        handleCurrentChange(val) {
            this.pagination.currentPage = val
        }
    }
}
</script>

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

/* 统计卡片 */
.stats-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin-bottom: 15px;
}

.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.stat-card.primary {
    border-left: 4px solid #1890ff;
}

.stat-card.success {
    border-left: 4px solid #52c41a;
}

.stat-card.warning {
    border-left: 4px solid #faad14;
}

.stat-card.info {
    border-left: 4px solid #722ed1;
}

.stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
}

.stat-card.primary .stat-icon {
    background: linear-gradient(135deg, #1890ff 0%, #69c0ff 100%);
}

.stat-card.success .stat-icon {
    background: linear-gradient(135deg, #52c41a 0%, #95de64 100%);
}

.stat-card.warning .stat-icon {
    background: linear-gradient(135deg, #faad14 0%, #ffc53d 100%);
}

.stat-card.info .stat-icon {
    background: linear-gradient(135deg, #722ed1 0%, #b37feb 100%);
}

.stat-icon i {
    font-size: 28px;
    color: #fff;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #1f2329;
    line-height: 1.2;
}

.stat-label {
    font-size: 14px;
    color: #8c8c8c;
    margin-top: 4px;
}

/* 搜索卡片 */
.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;
    margin-right: 20px;
}

/* 表格卡片 */
.table-card {
    border-radius: 12px;
}

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

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

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

.header-tips {
    font-size: 12px;
    color: #8c8c8c;
}

/* 产品编号样式 */
.product-id {
    font-weight: 600;
    color: #1890ff;
}

.time-text {
    font-family: 'Monaco', monospace;
    font-size: 13px;
}

.station-count {
    font-weight: 600;
    color: #52c41a;
}

/* 展开内容 */
.expand-content {
    padding: 20px;
    background: linear-gradient(135deg, #fafbfc 0%, #f0f2f5 100%);
}

.gantt-section,
.detail-section {
    margin-bottom: 20px;
}

.section-title {
    font-size: 14px;
    font-weight: 600;
    color: #1f2329;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
}

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

.gantt-chart {
    width: 100%;
    height: 200px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 节拍时间样式 */
.takt-success {
    color: #52c41a;
    font-weight: 600;
}

.takt-warning {
    color: #faad14;
    font-weight: 600;
}

.takt-danger {
    color: #ff4d4f;
    font-weight: 600;
}

/* 表格行样式 */
::v-deep .row-warning {
    background-color: #fff7e6 !important;
}

/* 分页 */
.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}
</style>
