<template>
  <div class="background-config-container">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="title">登录背景图片配置</span>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            保存配置
          </el-button>
        </div>
      </template>

      <el-form :model="configForm" label-width="120px" class="config-form">
        <el-form-item label="当前背景图片">
          <div class="image-preview-container">
            <div class="image-preview">
             <!--   {{VITE_API_URL+configForm.backgroundImage}} -->
              <el-image
                v-if="configForm.backgroundImage"
                :src="configForm.backgroundImage"
                fit="contain"
                class="preview-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
              <div v-else class="no-image">
                <el-icon class="no-image-icon"><Picture /></el-icon>
                <span>未设置背景图片</span>
              </div>
            </div>
          </div>
        </el-form-item>
<!-- /api/system/device/upload-image/ handleCustomUpload-->
        <el-form-item label="选择图片">
          <el-upload
            class="avatar-uploader"
            :action="VITE_API_URL+'/api/system/upload/'"
            :headers="{ Authorization: 'JWT '+ Cookies.get('token') }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作历史 -->
    <el-card class="history-card" v-if="configHistory.length > 0">
      <template #header>
        <span class="title">配置历史</span>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in configHistory"
          :key="index"
          :timestamp="item.updateTime"
          placement="top"
        >
          <el-card class="history-item">
            <div class="history-content">
              <div class="history-image">
                <el-image
                  v-if="item.backgroundImage"
                  :src="`${item.backgroundImage}`"
                  fit="cover"
                  class="history-thumbnail"
                >
                  <template #error>
                    <div class="thumbnail-error">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div v-else class="no-thumbnail">
                  <el-icon><Picture /></el-icon>
                </div>
              </div>
              <div class="history-info">
                <p class="history-desc">{{ item.description || '无描述' }}</p>
                <p class="history-status">
                  状态：
                  <el-tag :type="item.enabled ? 'success' : 'info'" size="small">
                    {{ item.enabled ? '启用' : '禁用' }}
                  </el-tag>
                </p>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { useLoginBackgroundApi } from '/@/api/system/loginBackground';
import Cookies from 'js-cookie';
import { request } from '/@/utils/service';
import { Plus } from '@element-plus/icons-vue';

// 类型定义
interface ConfigForm {
  backgroundImage: string;
  description: string;
  enabled: boolean;
}

interface HistoryItem {
  backgroundImage: string;
  description: string;
  enabled: boolean;
  updateTime: string;
}

const fileList = ref<any[]>([]);
const imageUrl = ref('');
const VITE_API_URL=ref(import.meta.env.VITE_API_URL);

const handleCustomUpload = async ({ file, onProgress, onSuccess, onError }: any) => {
  const token = Cookies.get('token'); 
  const formData = new FormData();
  formData.append('file', file);
  console.log("token::::",token);

  try {
    const res = await request({
		url: `/api/system/upload/`,
		method: 'post',
		headers: {
			'Content-Type': 'multipart/form-data',
			Authorization: 'JWT '+ token,
		},
		data: formData,
		timeout: 60000,
		onUploadProgress: (p: any) => {
                            onProgress({percent: Math.round((p.loaded / p.total) * 100)});
		}
    });

    // 根据API响应格式兼容性规范处理响应数据
    let uploadData = null;
    if (res.code === 200 || res.code === 2000) {
      uploadData = res.data;
    } else if (res.data) {
      uploadData = res.data;
    } else if (res.results) {
      uploadData = res.results;
    } else {
      uploadData = res;
    }

	// 构造 Element Plus 需要的 file 对象
	const fileObj = {
      name: uploadData.name || file.name,
      url: uploadData.url || uploadData,
      status: 'success',
      response: uploadData
    };

    // 更新配置表单的背景图片
	configForm.backgroundImage = fileObj.url;
    // 更新头像显示URL
    imageUrl.value = fileObj.url;
    // 更新文件列表用于回显
    fileList.value = [fileObj];

    ElMessage.success('上传成功');
    onSuccess(fileObj); 
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
    onError(error);
  }
};

// 头像上传成功处理
const handleAvatarSuccess = (response: any, file: any) => {
  // 根据API响应格式兼容性规范处理响应数据
  let uploadData = null;
  if (response.code === 200 || response.code === 2000) {
    uploadData = response.data;
  } else if (response.data) {
    uploadData = response.data;
  } else if (response.results) {
    uploadData = response.results;
  } else {
    uploadData = response;
  }

  // 更新配置表单的背景图片和显示的图片URL
  configForm.backgroundImage = uploadData.url || uploadData;
  imageUrl.value = uploadData.url || uploadData;
  
  ElMessage.success('上传成功');
};

// 上传前验证
const beforeAvatarUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 处理文件移除
const handleFileRemove = (file: any) => {
  // 清空配置表单中的背景图片
  configForm.backgroundImage = '';
  // 清空文件列表
  fileList.value = [];
  ElMessage.info('已移除图片');
};

// API实例
const loginBackgroundApi = useLoginBackgroundApi();

// 响应式数据
const saveLoading = ref(false);
const configForm = reactive<ConfigForm>({
  backgroundImage: '',
  description: '',
  enabled: true,
});
const configHistory = ref<HistoryItem[]>([]);

// 加载配置数据
const loadConfig = async () => {
  try {
    const response = await loginBackgroundApi.getConfig();
    
    // 根据API响应格式兼容性规范处理响应数据
    let data = null;
    if (response.code === 200 || response.code === 2000) {
      data = response.data;
      console.log(data);
    } else if (response.data) {
      data = response.data;
    } else if (response.results) {
      data = response.results;
    } else {
      data = response;
    }
    
    if (data) {
      // 回显当前配置
        configForm.backgroundImage = data.image_url || '';
        configForm.description = data.description || '';
        // 同步文件列表回显
        updateFileListFromConfig();
      
      // 加载历史记录
      if (data.history && Array.isArray(data.history)) {
        configHistory.value = data.history;
      }
    }
  } catch (error) {
    console.error('加载配置失败:', error);
    ElMessage.error('加载配置失败，请稍后重试');
  }
};

// 根据配置更新文件列表回显
const updateFileListFromConfig = () => {
  if (configForm.backgroundImage) {
    // 从URL中提取文件名
    const urlParts = configForm.backgroundImage.split('/');
    const fileName = urlParts[urlParts.length - 1] || 'background-image';
    
    const fileObj = {
      name: fileName,
      url: configForm.backgroundImage,
      status: 'success',
      response: { url: configForm.backgroundImage }
    };
    
    fileList.value = [fileObj];
    // 更新头像显示URL
    imageUrl.value = configForm.backgroundImage;
  } else {
    fileList.value = [];
    imageUrl.value = '';
  }
};

// 保存配置
const handleSave = async () => {
  if (!configForm.backgroundImage) {
    ElMessage.warning('请选择背景图片');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      '确定要保存当前配置吗？',
      '确认保存',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    saveLoading.value = true;
    
    const configData = {
      image_url: configForm.backgroundImage,
      description: configForm.description,
    };
    
    const response = await loginBackgroundApi.setConfig(configData);
    
    // 检查保存结果
    if (response.code === 200 || response.code === 2000 || response.success) {
      ElMessage.success('配置保存成功');
      // 重新加载配置以更新历史记录
      await loadConfig();
      // 更新文件列表回显
      updateFileListFromConfig();
    } else {
      ElMessage.error(response.message || '保存失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('保存配置失败:', error);
      ElMessage.error(error.message || '保存配置失败，请稍后重试');
    }
  } finally {
    saveLoading.value = false;
  }
};

// 组件挂载时加载配置
onMounted(() => {
  loadConfig();
});
</script>

<style lang="scss" scoped>
.background-config-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  
  .config-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .config-form {
      .image-preview-container {
        .image-preview {
          width: 300px;
          height: 200px;
          border: 2px dashed #d9d9d9;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #fafafa;
          
          .preview-image {
            width: 100%;
            height: 100%;
            border-radius: 6px;
          }
          
          .image-error,
          .no-image {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #999;
            
            .el-icon {
              font-size: 48px;
              margin-bottom: 10px;
            }
            
            span {
              font-size: 14px;
            }
          }
          
          .no-image-icon {
            font-size: 48px;
            color: #c0c4cc;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  
  .history-card {
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
    
    .history-item {
      .history-content {
        display: flex;
        gap: 15px;
        
        .history-image {
          .history-thumbnail {
            width: 80px;
            height: 60px;
            border-radius: 4px;
          }
          
          .thumbnail-error,
          .no-thumbnail {
            width: 80px;
            height: 60px;
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #fafafa;
            color: #c0c4cc;
            
            .el-icon {
              font-size: 24px;
            }
          }
        }
        
        .history-info {
          flex: 1;
          
          .history-desc {
            margin: 0 0 8px 0;
            color: #606266;
            font-size: 14px;
            line-height: 1.4;
          }
          
          .history-status {
            margin: 0;
            color: #909399;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
          }
        }
      }
    }
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

/* 头像上传组件样式 */
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: .3s;

    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  cursor: pointer;
  transition: .3s;

  &:hover {
    border-color: #409eff;
    color: #409eff;
  }
}
</style>