package com.zhentao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.Banner;
import com.zhentao.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 轮播图管理控制器
 */
@RestController
@RequestMapping("/admin/banner")
@CrossOrigin(origins = "*", maxAge = 3600)
public class BannerController {
    
    @Autowired
    private BannerService bannerService;
    
    // 图片存储路径
    private static final String UPLOAD_DIR = "uploads/banners/";
    
    /**
     * 分页查询轮播图列表
     */
    @GetMapping("/list")
    public Result<Page<Banner>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            Page<Banner> bannerPage = bannerService.getBannerList(page, pageSize, keyword);
            return Result.success(bannerPage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取轮播图列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询轮播图详情
     */
    @GetMapping("/detail/{bannerId}")
    public Result<Banner> detail(@PathVariable Integer bannerId) {
        try {
            Banner banner = bannerService.getBannerById(bannerId);
            if (banner == null) {
                return Result.error("轮播图不存在");
            }
            return Result.success(banner);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取轮播图详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建轮播图
     */
    @PostMapping("/create")
    public Result<String> create(@RequestBody Banner banner) {
        try {
            boolean success = bannerService.createBanner(banner);
            if (success) {
                return Result.success("创建成功");
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建轮播图失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新轮播图
     */
    @PutMapping("/update/{bannerId}")
    public Result<String> update(@PathVariable Integer bannerId, @RequestBody Banner banner) {
        try {
            banner.setBannerId(bannerId);
            boolean success = bannerService.updateBanner(banner);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新轮播图失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除轮播图
     */
    @DeleteMapping("/delete/{bannerId}")
    public Result<String> delete(@PathVariable Integer bannerId) {
        try {
            boolean success = bannerService.deleteBanner(bannerId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除轮播图失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传轮播图图片
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }
            
            // 创建上传目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null && originalFilename.contains(".")
                    ? originalFilename.substring(originalFilename.lastIndexOf("."))
                    : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            Path filePath = Paths.get(UPLOAD_DIR + filename);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回访问URL
            Map<String, String> result = new HashMap<>();
            result.put("url", "/uploads/banners/" + filename);
            
            return Result.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}

