<template>
    <div class="order-progress-container">
        <!-- 顶部状态卡片 -->
        <div class="status-cards">
            <div class="status-card waiting" @click="filterByStatus(0)">
                <div class="status-icon">
                    <i class="el-icon-time"></i>
                </div>
                <div class="status-content">
                    <div class="status-value">{{ statusCounts.waiting }}</div>
                    <div class="status-label">待生产</div>
                </div>
                <div class="status-indicator"></div>
            </div>
            <div class="status-card producing" @click="filterByStatus(1)">
                <div class="status-icon">
                    <i class="el-icon-loading"></i>
                </div>
                <div class="status-content">
                    <div class="status-value">{{ statusCounts.producing }}</div>
                    <div class="status-label">生产中</div>
                </div>
                <div class="status-indicator"></div>
            </div>
            <div class="status-card completed" @click="filterByStatus(2)">
                <div class="status-icon">
                    <i class="el-icon-circle-check"></i>
                </div>
                <div class="status-content">
                    <div class="status-value">{{ statusCounts.completed }}</div>
                    <div class="status-label">已完成</div>
                </div>
                <div class="status-indicator"></div>
            </div>
            <div class="status-card delayed" @click="filterByDelayed">
                <div class="status-icon">
                    <i class="el-icon-warning"></i>
                </div>
                <div class="status-content">
                    <div class="status-value">{{ statusCounts.delayed }}</div>
                    <div class="status-label">延期预警</div>
                </div>
                <div class="status-indicator"></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-select v-model="statusFilter" placeholder="全部状态" style="width: 120px">
                            <el-option label="全部" :value="-1" />
                            <el-option label="待生产" :value="0" />
                            <el-option label="生产中" :value="1" />
                            <el-option label="已完成" :value="2" />
                        </el-select>
                    </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">
            <!-- 左侧表格 -->
            <el-card class="table-card" shadow="hover">
                <div slot="header" class="card-header">
                    <span class="header-title">
                        <i class="el-icon-document-copy"></i> 订单列表
                    </span>
                    <span class="header-count">共 {{ filteredData.length }} 条</span>
                </div>
                <el-table v-loading="loading" :data="filteredData" :header-cell-style="headerCellStyle"
                    :row-class-name="tableRowClassName" border stripe highlight-current-row max-height="550"
                    @row-click="handleRowClick">
                    <el-table-column prop="排序" label="序号" width="55" align="center" />
                    <el-table-column prop="订单号" label="订单号" min-width="180" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span class="order-id">{{ scope.row.订单号 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="产品型号" label="产品型号" width="160" show-overflow-tooltip />
                    <el-table-column label="生产类型" width="100" align="center">
                        <template slot-scope="scope">
                            <span class="time-text">{{ scope.row.生产类型 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="计划时间" width="130" align="center">
                        <template slot-scope="scope">
                            <span class="time-text">{{ formatDate(scope.row.计划开始时间) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="开始时间" width="130" align="center">
                        <template slot-scope="scope">
                            <span class="time-text">{{ formatDate(scope.row.生产开始时间) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="完成时间" width="130" align="center">
                        <template slot-scope="scope">
                            <span class="time-text">{{ formatDate(scope.row.生产完成时间) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="90" align="center">
                        <template slot-scope="scope">
                            <el-tag :type="getStatusType(scope.row.执行状态)" effect="dark" size="small">
                                {{ scope.row.状态文本 }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="预警" width="70" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.是否延期 === 1" class="delay-warning">
                                <i class="el-icon-warning"></i>
                            </span>
                            <span v-else class="normal-status">
                                <i class="el-icon-check"></i>
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <!-- 右侧图表区域 -->
            <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-pie-chart"></i> 订单状态分布
                        </span>
                    </div>
                    <div ref="pieChart" class="pie-chart-container"></div>
                </el-card>

                <!-- 甘特图 -->
                <el-card class="gantt-card" shadow="hover">
                    <div slot="header" class="card-header">
                        <span class="header-title">
                            <i class="el-icon-s-data"></i> 生产进度甘特图
                        </span>
                    </div>
                    <div ref="ganttChart" class="gantt-chart-container"></div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: 'OrderProgress',
    data() {
        return {
            loading: false,
            dateRange: [],
            statusFilter: -1,
            tableData: [],
            showDelayedOnly: false,
            pieChartInstance: null,
            ganttChartInstance: 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: {
        filteredData() {
            let data = this.tableData
            if (this.statusFilter !== -1) {
                data = data.filter(item => item.执行状态 === this.statusFilter)
            }
            if (this.showDelayedOnly) {
                data = data.filter(item => item.是否延期 === 1)
            }
            return data
        },
        statusCounts() {
            const waiting = this.tableData.filter(item => item.执行状态 === 0).length
            const producing = this.tableData.filter(item => item.执行状态 === 1).length
            const completed = this.tableData.filter(item => item.执行状态 === 2).length
            const delayed = this.tableData.filter(item => item.是否延期 === 1).length
            return { waiting, producing, completed, delayed }
        }
    },
    created() {
        this.setDefaultDate()
        this.queryData()
    },
    beforeDestroy() {
        if (this.pieChartInstance) this.pieChartInstance.dispose()
        if (this.ganttChartInstance) this.ganttChartInstance.dispose()
    },
    methods: {
        setDefaultDate() {
            const end = new Date()
            end.setDate(end.getDate() + 7)
            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
            this.showDelayedOnly = false
            const param = [
                ['开始时间', this.dateRange[0] + ' 00:00:00'],
                ['结束时间', this.dateRange[1] + ' 23:59:59'],
                ['执行状态', this.statusFilter]
            ]
            const Data = this.CreateData('11', '生产分析_订单进度_查询', param)
            this.ExecDatabase(Data).then(response => {
                this.tableData = response.data || []
                this.loading = false
                this.$nextTick(() => {
                    this.drawPieChart()
                    this.drawGanttChart()
                })
            }).catch(() => {
                this.loading = false
                this.$message.error('查询失败')
            })
        },
        filterByStatus(status) {
            this.statusFilter = status
            this.showDelayedOnly = false
        },
        filterByDelayed() {
            this.statusFilter = -1
            this.showDelayedOnly = true
        },
        handleRowClick(row) {
            // 可扩展详情展示
        },
        drawPieChart() {
            if (!this.$refs.pieChart) return

            if (this.pieChartInstance) this.pieChartInstance.dispose()
            this.pieChartInstance = echarts.init(this.$refs.pieChart)

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'horizontal',
                    bottom: 10,
                    itemWidth: 12,
                    itemHeight: 12
                },
                series: [{
                    type: 'pie',
                    radius: ['45%', '70%'],
                    center: ['50%', '45%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 8,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: true,
                        formatter: '{c}',
                        fontSize: 14,
                        fontWeight: 'bold'
                    },
                    labelLine: {
                        show: true
                    },
                    data: [
                        {
                            value: this.statusCounts.waiting,
                            name: '待生产',
                            itemStyle: { color: '#909399' }
                        },
                        {
                            value: this.statusCounts.producing,
                            name: '生产中',
                            itemStyle: { color: '#1890ff' }
                        },
                        {
                            value: this.statusCounts.completed,
                            name: '已完成',
                            itemStyle: { color: '#52c41a' }
                        }
                    ]
                }]
            }
            this.pieChartInstance.setOption(option)
        },
        drawGanttChart() {
            if (!this.$refs.ganttChart) return

            if (this.ganttChartInstance) this.ganttChartInstance.dispose()
            this.ganttChartInstance = echarts.init(this.$refs.ganttChart)

            // 取前10条显示
            const displayData = this.tableData.slice(0, 10)
            const categories = displayData.map(item => item.订单号.substring(0, 15) + '...')

            const now = new Date().getTime()
            const data = displayData.map((item, index) => {
                const planTime = new Date(item.计划开始时间).getTime()
                const startTime = item.生产开始时间 ? new Date(item.生产开始时间).getTime() : planTime
                const endTime = item.生产完成时间 ? new Date(item.生产完成时间).getTime() : now

                let color = '#909399'
                if (item.执行状态 === 2) {
                    color = '#52c41a'
                } else if (item.执行状态 === 1) {
                    color = '#1890ff'
                }
                if (item.是否延期 === 1) {
                    color = '#ff4d4f'
                }

                return {
                    name: item.订单号,
                    value: [index, startTime, endTime, item.状态文本],
                    itemStyle: { color }
                }
            })

            const option = {
                tooltip: {
                    formatter: (params) => {
                        const item = displayData[params.value[0]]
                        return `<div style="padding: 8px">
              <div style="font-weight: bold">${item.订单号}</div>
              <div>产品: ${item.产品型号}</div>
              <div>状态: ${item.状态文本}</div>
              <div>计划: ${this.formatDate(item.计划开始时间)}</div>
            </div>`
                    }
                },
                grid: {
                    left: '120',
                    right: '30',
                    top: '20',
                    bottom: '30'
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        formatter: (value) => {
                            const date = new Date(value)
                            return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
                        }
                    }
                },
                yAxis: {
                    type: 'category',
                    data: categories,
                    axisLabel: { fontSize: 10 }
                },
                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: Math.max(end[0] - start[0], 10),
                                height: height,
                                r: 4
                            },
                            style: api.style()
                        }
                    },
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data
                }]
            }
            this.ganttChartInstance.setOption(option)
        },
        formatDate(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')}`
        },
        getStatusType(status) {
            switch (status) {
                case 0: return 'info'
                case 1: return 'primary'
                case 2: return 'success'
                default: return 'info'
            }
        },
        tableRowClassName({ row }) {
            if (row.是否延期 === 1) return 'delay-row'
            if (row.执行状态 === 2) return 'completed-row'
            return ''
        },
        resetSearch() {
            this.statusFilter = -1
            this.showDelayedOnly = false
            this.setDefaultDate()
            this.queryData()
        }
    }
}
</script>

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

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

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

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

.status-card.waiting {
    border-left: 4px solid #909399;
}

.status-card.producing {
    border-left: 4px solid #1890ff;
}

.status-card.completed {
    border-left: 4px solid #52c41a;
}

.status-card.delayed {
    border-left: 4px solid #ff4d4f;
}

.status-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
}

.status-card.waiting .status-icon {
    background: linear-gradient(135deg, #909399, #b1b3b8);
}

.status-card.producing .status-icon {
    background: linear-gradient(135deg, #1890ff, #69c0ff);
}

.status-card.completed .status-icon {
    background: linear-gradient(135deg, #52c41a, #95de64);
}

.status-card.delayed .status-icon {
    background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.status-icon i {
    font-size: 24px;
    color: #fff;
}

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

.status-label {
    font-size: 14px;
    color: #8c8c8c;
}

.status-indicator {
    position: absolute;
    right: -30px;
    bottom: -30px;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    opacity: 0.1;
}

.status-card.waiting .status-indicator {
    background: #909399;
}

.status-card.producing .status-indicator {
    background: #1890ff;
}

.status-card.completed .status-indicator {
    background: #52c41a;
}

.status-card.delayed .status-indicator {
    background: #ff4d4f;
}

/* 搜索卡片 */
.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;
}

.table-card,
.chart-card,
.gantt-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;
}

.header-count {
    font-size: 13px;
    color: #8c8c8c;
}

.order-id {
    font-weight: 600;
    color: #1890ff;
}

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

.delay-warning {
    color: #ff4d4f;
    font-size: 18px;
    animation: pulse 1.5s infinite;
}

.normal-status {
    color: #52c41a;
    font-size: 16px;
}

@keyframes pulse {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }
}

/* 图表区域 */
.chart-section {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.pie-chart-container {
    height: 250px;
}

.gantt-chart-container {
    height: 280px;
}

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

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