<template>
    <el-dialog
        title="调整修改时间"
        :visible.sync="visible"
        width="600px"
        :close-on-click-modal="false"
        class="adjust-time-dialog">
        
        <!-- 格位信息卡片 -->
        <div class="cell-info-card">
            <div class="cell-info-header">
                <i class="el-icon-location"></i>
                <span>格位信息</span>
            </div>
            <div class="cell-info-content">
                <div class="info-item">
                    <span class="info-label">设备名称：</span>
                    <span class="info-value">{{ currentCell.deviceName }}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">格位编号：</span>
                    <span class="info-value">{{ currentCell.cellCode }}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">当前修改时间：</span>
                    <span class="info-value time-value">{{ formatDateTime(currentCell.updateTime) }}</span>
                </div>
            </div>
        </div>

        <!-- 调整表单 -->
        <el-form :model="adjustTimeForm" :rules="adjustTimeRules" ref="adjustTimeForm" class="adjust-form">
            <el-form-item label="调整方式" prop="adjustType">
                <el-radio-group v-model="adjustTimeForm.adjustType" class="adjust-type-group">
                    <el-radio label="set" class="adjust-radio">
                        <i class="el-icon-time"></i>
                        <span>设置为指定时间</span>
                    </el-radio>
                    <el-radio label="add" class="adjust-radio">
                        <i class="el-icon-plus"></i>
                        <span>增加时间</span>
                    </el-radio>
                    <el-radio label="subtract" class="adjust-radio">
                        <i class="el-icon-minus"></i>
                        <span>减少时间</span>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            
            <el-form-item v-if="adjustTimeForm.adjustType === 'set'" label="设置时间" prop="setTime">
                <el-date-picker
                    v-model="adjustTimeForm.setTime"
                    type="datetime"
                    placeholder="选择时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    class="time-picker">
                </el-date-picker>
            </el-form-item>
            
            <el-form-item v-if="adjustTimeForm.adjustType !== 'set'" label="调整时长" prop="adjustHours">
                <div class="hours-input-wrapper">
                    <el-input-number
                        v-model="adjustTimeForm.adjustHours"
                        :min="0"
                        :max="24"
                        :precision="1"
                        :step="0.5"
                        class="hours-input">
                    </el-input-number>
                    <span class="hours-unit">小时</span>
                </div>
            </el-form-item>
            
            <el-form-item v-if="adjustTimeForm.adjustType !== 'set'" label="调整后时间">
                <div class="preview-time">
                    <i class="el-icon-clock"></i>
                    <span>{{ getPreviewTime() }}</span>
                </div>
            </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel" size="medium" class="cancel-btn">取消</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="loading" size="medium" class="confirm-btn">
                <i class="el-icon-check"></i>
                确定调整
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
    name: 'AdjustTimeDialog',
    data() {
        return {
            visible: false,
            loading: false,
            currentCell: {},
            adjustTimeForm: {
                adjustType: 'set',
                setTime: '',
                adjustHours: 0.5
            },
            adjustTimeRules: {
                adjustType: [
                    { required: true, message: '请选择调整方式', trigger: 'change' }
                ],
                setTime: [
                    { required: true, message: '请选择设置时间', trigger: 'change' }
                ],
                adjustHours: [
                    { required: true, message: '请输入调整时长', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        // 打开对话框
        open(cell) {
            this.currentCell = cell;
            this.adjustTimeForm = {
                adjustType: 'set',
                setTime: '',
                adjustHours: 0.5
            };
            this.visible = true;
        },
        
        // 关闭对话框
        handleCancel() {
            this.visible = false;
        },
        
        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) {
                return '--';
            }
            
            const date = new Date(dateTime);
            
            if (isNaN(date.getTime())) {
                return '--';
            }
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        
        // 格式化日期时间给后台（本地时间格式）
        formatDateTimeForBackend(dateTime) {
            if (!dateTime) {
                return null;
            }
            
            const date = new Date(dateTime);
            
            if (isNaN(date.getTime())) {
                return null;
            }
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        
        // 获取预览时间
        getPreviewTime() {
            if (!this.currentCell.updateTime) {
                return '--';
            }
            
            if (this.adjustTimeForm.adjustType === 'set') {
                if (this.adjustTimeForm.setTime) {
                    return this.formatDateTime(new Date(this.adjustTimeForm.setTime));
                }
                return '--';
            }
            
            const currentTime = new Date(this.currentCell.updateTime);
            let newTime;
            
            if (this.adjustTimeForm.adjustType === 'add') {
                newTime = new Date(currentTime.getTime() + this.adjustTimeForm.adjustHours * 60 * 60 * 1000);
            } else if (this.adjustTimeForm.adjustType === 'subtract') {
                newTime = new Date(currentTime.getTime() - this.adjustTimeForm.adjustHours * 60 * 60 * 1000);
            }
            
            return this.formatDateTime(newTime);
        },
        
        // 确认调整时间
        handleConfirm() {
            this.$refs.adjustTimeForm.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    
                    // 计算新的修改时间
                    let newUpdateTime;
                    const currentTime = new Date(this.currentCell.updateTime);
                    
                    console.log('当前格位时间:', this.currentCell.updateTime);
                    console.log('当前时间对象:', currentTime);
                    console.log('调整类型:', this.adjustTimeForm.adjustType);
                    
                    if (this.adjustTimeForm.adjustType === 'set') {
                        newUpdateTime = new Date(this.adjustTimeForm.setTime);
                        console.log('设置时间:', this.adjustTimeForm.setTime);
                    } else if (this.adjustTimeForm.adjustType === 'add') {
                        const addMilliseconds = this.adjustTimeForm.adjustHours * 60 * 60 * 1000;
                        newUpdateTime = new Date(currentTime.getTime() + addMilliseconds);
                        console.log('增加小时:', this.adjustTimeForm.adjustHours);
                        console.log('增加毫秒:', addMilliseconds);
                    } else if (this.adjustTimeForm.adjustType === 'subtract') {
                        const subtractMilliseconds = this.adjustTimeForm.adjustHours * 60 * 60 * 1000;
                        newUpdateTime = new Date(currentTime.getTime() - subtractMilliseconds);
                        console.log('减少小时:', this.adjustTimeForm.adjustHours);
                        console.log('减少毫秒:', subtractMilliseconds);
                    }
                    
                    // 调试信息
                    console.log('原始时间:', this.currentCell.updateTime);
                    console.log('计算后时间:', newUpdateTime);
                    console.log('发送给后台的时间:', this.formatDateTimeForBackend(newUpdateTime));
                    
                    // 调用后台接口调整时间
                    request({
                        url: `/api/Extend/UavDeviceCell/AdjustUpdateTime`,
                        method: 'POST',
                        data: {
                            cellId: this.currentCell.id,
                            newUpdateTime: this.formatDateTimeForBackend(newUpdateTime)
                        }
                    }).then(res => {
                        if (res.code === 200) {
                            this.$message.success('修改时间调整成功！');
                            this.visible = false;
                            this.$emit('success'); // 通知父组件刷新数据
                        } else {
                            this.$message.error(res.msg || '调整失败');
                        }
                    }).catch(error => {
                        console.error('调整时间失败:', error);
                        this.$message.error('调整失败，请重试');
                    }).finally(() => {
                        this.loading = false;
                    });
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
/* 调整时间对话框样式 */
.adjust-time-dialog .el-dialog__header {
    background: #409EFF;
    color: white;
    padding: 20px 20px 15px;
    border-radius: 8px 8px 0 0;
}

.adjust-time-dialog .el-dialog__title {
    color: white;
    font-weight: 600;
    font-size: 18px;
}

.adjust-time-dialog .el-dialog__headerbtn .el-dialog__close {
    color: white;
    font-size: 20px;
}

.adjust-time-dialog .el-dialog__body {
    padding: 30px 20px;
}

/* 格位信息卡片 */
.cell-info-card {
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 12px;
    margin-bottom: 25px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.cell-info-header {
    background: #409EFF;
    color: white;
    padding: 12px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
}

.cell-info-header i {
    font-size: 16px;
}

.cell-info-content {
    padding: 20px;
}

.info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.info-item:last-child {
    margin-bottom: 0;
}

.info-label {
    color: #666;
    font-weight: 500;
    min-width: 100px;
}

.info-value {
    color: #333;
    font-weight: 600;
}

.time-value {
    color: #409EFF;
    font-family: 'Courier New', monospace;
}

/* 调整表单样式 */
.adjust-form .el-form-item__label {
    font-weight: 600;
    color: #333;
}

.adjust-type-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.adjust-radio {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    border: 2px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s ease;
    cursor: pointer;
    width: 100%;
    justify-content: flex-start;
}

.adjust-radio:hover {
    border-color: #409EFF;
    background: rgba(64, 158, 255, 0.05);
}

.adjust-radio.is-checked {
    border-color: #409EFF;
    background: rgba(64, 158, 255, 0.1);
    color: #409EFF;
}

.adjust-radio i {
    font-size: 16px;
}

/* 时间选择器样式 */
.time-picker {
    width: 100%;
}

.time-picker .el-input__inner {
    border-radius: 8px;
    border: 2px solid #e4e7ed;
    transition: all 0.3s ease;
}

.time-picker .el-input__inner:focus {
    border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 小时输入样式 */
.hours-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}

.hours-input {
    width: 200px;
}

.hours-input .el-input__inner {
    border-radius: 8px;
    border: 2px solid #e4e7ed;
    transition: all 0.3s ease;
}

.hours-input .el-input__inner:focus {
    border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.hours-unit {
    color: #666;
    font-weight: 500;
    font-size: 14px;
}

/* 预览时间样式 */
.preview-time {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 8px;
    color: #0369a1;
    font-weight: 600;
    font-family: 'Courier New', monospace;
}

.preview-time i {
    color: #409EFF;
    font-size: 16px;
}

/* 对话框底部按钮样式 */
.dialog-footer {
    text-align: right;
    padding: 20px;
    border-top: 1px solid #e4e7ed;
    background: #fafafa;
}

.dialog-footer .el-button {
    border-radius: 8px;
    font-weight: 500;
    padding: 10px 20px;
}

.dialog-footer .el-button {
    padding: 12px 24px;
    font-size: 14px;
    font-weight: 500;
    border-radius: 6px;
    min-width: 80px;
}

.cancel-btn {
    background: #f5f5f5;
    border-color: #d9d9d9;
    color: #666;
}

.cancel-btn:hover {
    background: #e6f7ff;
    border-color: #409EFF;
    color: #409EFF;
}

.confirm-btn {
    background: #409EFF;
    border: none;
}

.confirm-btn:hover {
    background: #66b1ff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.confirm-btn i {
    margin-right: 6px;
}
</style>
