package org.example.controller;

import org.example.entity.HospitalOverview;
import org.example.service.AdminUserService;
import org.example.service.YonghuService;
import org.example.service.HospitalOverviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class LoginController {
    
    @Autowired
    private YonghuService yonghuService;
    
    @Autowired
    private AdminUserService adminUserService;
    
    @Autowired
    private HospitalOverviewService hospitalOverviewService;
    
    // Logo文件保存路径
    private static final String LOGO_UPLOAD_DIR = System.getProperty("user.dir") + "/src/main/resources/static/img/";
    
    public LoginController() {
        // 无参构造函数
        // 确保目录存在
        File uploadDir = new File(LOGO_UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }
    
    /**
     * 用户登录接口
     * @param credentials 登录凭证
     * @param session HttpSession
     * @return 登录结果
     */
    @PostMapping("/user/login")
    public Map<String, Object> userLogin(@RequestBody Map<String, String> credentials, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = credentials.get("username");
        String password = credentials.get("password");
        
        // 验证用户
        boolean authenticated = yonghuService.authenticate(username, password);
        
        if (authenticated) {
            // 登录成功，将用户信息存储到session中
            session.setAttribute("userType", "yonghu");
            session.setAttribute("username", username);
            result.put("success", true);
            result.put("message", "用户登录成功");
        } else {
            // 登录失败
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        
        return result;
    }
    
    /**
     * 管理员登录接口
     * @param credentials 登录凭证
     * @param session HttpSession
     * @return 登录结果
     */
    @PostMapping("/admin/login")
    public Map<String, Object> adminLogin(@RequestBody Map<String, String> credentials, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = credentials.get("username");
        String password = credentials.get("password");
        
        // 验证管理员
        boolean authenticated = adminUserService.authenticate(username, password);
        
        if (authenticated) {
            // 登录成功，将管理员信息存储到session中
            session.setAttribute("userType", "admin");
            session.setAttribute("username", username);
            result.put("success", true);
            result.put("message", "管理员登录成功");
        } else {
            // 登录失败
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        
        return result;
    }
    
    /**
     * 用户登出接口
     * @param session HttpSession
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 清除session
        session.invalidate();
        result.put("success", true);
        result.put("message", "登出成功");
        
        return result;
    }
    
    /**
     * 检查登录状态
     * @param session HttpSession
     * @return 登录状态
     */
    @GetMapping("/status")
    public Map<String, Object> status(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = (String) session.getAttribute("username");
        String userType = (String) session.getAttribute("userType");
        
        if (username != null && userType != null) {
            result.put("loggedIn", true);
            result.put("username", username);
            result.put("userType", userType);
        } else {
            result.put("loggedIn", false);
        }
        
        return result;
    }
    
    /**
     * 获取医院概况信息
     * @return 医院概况信息
     */
    @GetMapping("/hospital-overview")
    public Map<String, Object> getHospitalOverview() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            HospitalOverview hospitalOverview = hospitalOverviewService.getHospitalOverview();
            result.put("success", true);
            result.put("data", hospitalOverview);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取医院概况信息失败");
        }
        
        return result;
    }
    
    /**
     * 保存医院概况信息
     * @param data 医院概况数据
     * @return 保存结果
     */
    @PostMapping("/hospital-overview")
    public Map<String, Object> saveHospitalOverview(@RequestBody Map<String, String> data) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            HospitalOverview hospitalOverview = new HospitalOverview();
            hospitalOverview.setDizhi(data.get("dizhi"));
            hospitalOverview.setDianhua(data.get("dianhua"));
            hospitalOverview.setJieshao(data.get("jieshao"));
            
            boolean success = hospitalOverviewService.saveHospitalOverview(hospitalOverview);
            if (success) {
                result.put("success", true);
                result.put("message", "保存成功");
            } else {
                result.put("success", false);
                result.put("message", "保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "保存医院概况信息失败");
        }
        
        return result;
    }
    
    /**
     * 上传医院Logo
     * @param file 上传的文件
     * @return 上传结果
     */
    @PostMapping("/upload-logo")
    public Map<String, Object> uploadLogo(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "上传文件不能为空");
            return result;
        }
        
        try {
            // 检查文件类型
            String contentType = file.getContentType();
            if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
                result.put("success", false);
                result.put("message", "只支持JPG和PNG格式的图片");
                return result;
            }
            
            // 检查文件大小 (10MB)
            if (file.getSize() > 10 * 1024 * 1024) {
                result.put("success", false);
                result.put("message", "图片大小不能超过10M");
                return result;
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            
            // 创建保存目录
            File uploadDir = new File(LOGO_UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 保存文件
            File destFile = new File(LOGO_UPLOAD_DIR + uniqueFilename);
            file.transferTo(destFile);
            
            result.put("success", true);
            result.put("message", "上传成功");
            result.put("filename", uniqueFilename);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "上传失败：" + e.getMessage());
            return result;
        }
    }
}