package com.contract.review.controller;

import com.contract.review.entity.Contract;
import com.contract.review.entity.ContractRisk;
import com.contract.review.service.ContractService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同控制器
 */
@RestController
@RequestMapping("/api/contracts")
@Api(tags = "合同管理")
public class ContractController {
    
    @Autowired
    private ContractService contractService;
    
    /**
     * 获取合同列表
     * @param page 页码
     * @param pageSize 每页大小
     * @param name 合同名称
     * @param submitter 提交人
     * @param department 部门
     * @param querySource 查询来源
     * @param riskLevel 风险等级
     * @return 合同列表
     */
    @GetMapping
    @ApiOperation("获取合同列表")
    public Map<String, Object> getContractList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String submitter,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String querySource,
            @RequestParam(required = false) String riskLevel,
            @RequestParam(required = false) String uploadTime,
            @RequestParam(required = false) String finishTime) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", (page - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("name", name);
        params.put("submitter", submitter);
        params.put("department", department);
        params.put("querySource", querySource);
        params.put("riskLevel", riskLevel);
        params.put("uploadTime", uploadTime);
        params.put("finishTime", finishTime);
        
        List<Contract> contractList = contractService.getContractList(params);
        int total = contractService.getContractCount(params);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", contractList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        
        return result;
    }
    
    /**
     * 获取合同详情
     * @param id 合同ID
     * @return 合同详情
     */
    @GetMapping("/{id}")
    @ApiOperation("获取合同详情")
    public Map<String, Object> getContractById(@PathVariable Long id) {
        Contract contract = contractService.getContractById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (contract != null) {
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", contract);
        } else {
            result.put("code", 404);
            result.put("message", "合同不存在");
        }
        
        return result;
    }
    
    /**
     * 获取合同风险详情
     * @param id 合同ID
     * @return 风险详情
     */
    @GetMapping("/{id}/risks")
    @ApiOperation("获取合同风险详情")
    public Map<String, Object> getContractRisks(@PathVariable Long id) {
        List<ContractRisk> riskList = contractService.getContractRiskList(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", riskList);
        
        return result;
    }
    
    /**
     * 提交新合同审查
     * @param contract 合同
     * @return 结果
     */
    @PostMapping
    @ApiOperation("提交新合同审查")
    public Map<String, Object> addContract(@RequestBody Contract contract) {
        Long contractId = contractService.addContract(contract);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", contractId);
        
        return result;
    }
    
    /**
     * 更新合同
     * @param id 合同ID
     * @param contract 合同
     * @return 结果
     */
    @PutMapping("/{id}")
    @ApiOperation("更新合同")
    public Map<String, Object> updateContract(@PathVariable Long id, @RequestBody Contract contract) {
        contract.setId(id);
        int rows = contractService.updateContract(contract);
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "success");
        } else {
            result.put("code", 404);
            result.put("message", "合同不存在");
        }
        
        return result;
    }
    
    /**
     * 删除合同
     * @param id 合同ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除合同")
    public Map<String, Object> deleteContract(@PathVariable Long id) {
        int rows = contractService.deleteContract(id);
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "success");
        } else {
            result.put("code", 404);
            result.put("message", "合同不存在");
        }
        
        return result;
    }
    
    /**
     * 获取合同源文件内容
     * @param id 合同ID
     * @return 源文件内容
     */
    @GetMapping("/{id}/content")
    @ApiOperation("获取合同源文件内容")
    public Map<String, Object> getContractContent(@PathVariable Long id) {
        String content = contractService.getContractContent(id);
        
        Map<String, Object> result = new HashMap<>();
        if (content != null) {
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", content);
        } else {
            result.put("code", 404);
            result.put("message", "合同不存在或源文件无法读取");
        }
        
        return result;
    }
    
    /**
     * 获取合同源文件流
     * @param id 合同ID
     * @param response HTTP响应
     * @throws Exception 异常
     */
    @GetMapping("/{id}/file")
    @ApiOperation("获取合同源文件流")
    public void getContractFile(@PathVariable Long id, HttpServletResponse response) throws Exception {
        Contract contract = contractService.getContractById(id);
        if (contract == null || contract.getSourceFile() == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        String filePath = contract.getSourceFile();
        File file = new File(filePath);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        // 根据文件类型设置Content-Type
        String fileName = file.getName();
        if (fileName.endsWith(".doc")) {
            response.setContentType("application/msword");
        } else if (fileName.endsWith(".docx")) {
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        } else {
            response.setContentType("application/octet-stream");
        }
        
        // 设置响应头，使用inline而不是attachment，这样浏览器会尝试预览文件
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        response.setContentLengthLong(file.length());
        
        // 设置CORS头，允许跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
        
        // 读取文件并写入响应流
        try (FileInputStream fis = new FileInputStream(filePath);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buffer = new byte[4096]; // 增大缓冲区
            int len;
            while ((len = bis.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, len);
            }
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 获取合同文件预览地址
     * @param id 合同ID
     * @return 预览地址
     */
    @GetMapping("/{id}/preview-url")
    @ApiOperation("获取合同文件预览地址")
    public Map<String, Object> getContractPreviewUrl(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Contract contract = contractService.getContractById(id);
            if (contract == null || contract.getSourceFile() == null) {
                result.put("code", 404);
                result.put("message", "合同不存在或源文件无法读取");
                return result;
            }
            
            // 生成预览地址
            String previewUrl = "http://localhost:8081/api/contracts/" + id + "/file";
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", previewUrl);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "生成预览地址失败: " + e.getMessage());
        }
        return result;
    }
}
