package com.zt.plat.module.qms.resource.record.controller.admin.onlyOffice.controller.admin;


import com.zt.plat.framework.business.controller.AbstractFileUploadController;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.common.enums.UserTypeEnum;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.framework.tenant.core.aop.TenantIgnore;
import com.zt.plat.module.qms.resource.record.controller.admin.onlyOffice.controller.vo.OnlyOfficeEditorConfigRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.onlyOffice.service.OnlyOfficeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.zt.plat.framework.common.pojo.CommonResult.success;


@Slf4j
@Tag(name = "管理后台 - 文件、模板、记录")
@RestController
@RequestMapping("/qms/common/only-office")
@Validated
@DeptDataPermissionIgnore(enable = "true")
//@FileUploadController(source = "qms.only-office", codeKey = "data.fileUploadBusinessCode")
public class OnlyOfficeController extends AbstractFileUploadController implements BusinessControllerMarker {

//    static {
//        FileUploadController annotation = RecordRecordController.class.getAnnotation(FileUploadController.class);
//        if (annotation != null) {
//            setFileUploadInfo(annotation);
//        }
//    }

    @Resource
    private OnlyOfficeService onlyOfficeService;

    @GetMapping("/editor-config")
    @Operation(summary = "获取 OnlyOffice 编辑器配置")
//    @PreAuthorize("@ss.hasPermission('infra:doc:edit')")
    public CommonResult<OnlyOfficeEditorConfigRespVO> getEditorConfig(@RequestParam("id") Long id) {
        return success(onlyOfficeService.getEditorConfig(id));
    }

    @GetMapping("/file-content")
    @Operation(summary = "获取文档文件内容")
    @PermitAll
    @TenantIgnore
    public void getFileContent(@RequestParam("fileId") Long fileId,
                               @RequestParam("token") String token,
                               HttpServletResponse response) {
        onlyOfficeService.getDocFileContent(fileId, token, response);
    }

    @PostMapping("/callback")
    @Operation(summary = "OnlyOffice 回调接口")
    @PermitAll
    @TenantIgnore
    public Map<String,Object> callback(@RequestParam("fileId") Long fileId,
                                       @RequestParam(value = "userId", required = false) Long triggerUserId,
                                       @RequestBody Map<String,Object> body,
                                       HttpServletRequest request) {
        try {
            log.info("=== OnlyOffice 回调接口被调用 ===");
            log.info("请求URL: {}", request.getRequestURL());
            log.info("请求URI: {}", request.getRequestURI());
            log.info("请求方法: {}", request.getMethod());
            log.info("Content-Type: {}", request.getContentType());
            log.info("User-Agent: {}", request.getHeader("User-Agent"));
//            log.info("客户端IP: {}", getClientIpAddress(request));
            log.info("OnlyOffice 回调请求: fileId={}, triggerUserId={}, body={}", fileId, triggerUserId, body);

            // 如果传入了triggerUserId，设置当前请求的登录用户为该用户
            if (triggerUserId != null) {
                LoginUser mockUser = new LoginUser();
                mockUser.setId(triggerUserId);
                mockUser.setUserType(UserTypeEnum.ADMIN.getValue());
                mockUser.setTenantId(1L); // 默认租户
                SecurityFrameworkUtils.setLoginUser(mockUser, request);
                log.info("已设置登录用户上下文: userId={}", triggerUserId);
            }

            Integer status = (Integer) body.get("status");
            String downloadUrl = (String) body.get("url");

            // 扩展保存策略：更多状态下进行保存
            boolean shouldSave = false;
            String saveReason = "";

            if (status != null) {
                switch (status) {
                    case 1:
                        // 文档正在编辑中 - 记录活动但不保存
                        log.info("文档编辑中: fileId={}, users={}", fileId, body.get("users"));
                        break;
                    case 2:
                        // 文档已准备保存（用户主动保存或停止编辑）- 立即保存
                        shouldSave = true;
                        saveReason = "用户主动保存";
                        break;
                    case 3:
                        // 保存时出错 - 记录错误但不重试保存，避免循环
                        log.warn("OnlyOffice保存出错: fileId={}, url={}", fileId, downloadUrl);
                        break;
                    case 4:
                        // 文档关闭且无错误 - 只在有实际内容时保存
                        if (downloadUrl != null && !downloadUrl.trim().isEmpty()) {
                            shouldSave = true;
                            saveReason = "文档关闭保存";
                        }
                        break;
                    case 6:
                        // 强制保存（通常是协作冲突解决） - 立即保存
                        shouldSave = true;
                        saveReason = "协作保存";
                        break;
                    case 7:
                        // 保存时出错但继续编辑 - 记录错误但不重试
                        log.warn("OnlyOffice编辑中保存出错: fileId={}, url={}", fileId, downloadUrl);
                        break;
                    default:
                        log.info("OnlyOffice未处理的回调状态: fileId={}, status={}", fileId, status);
                }
            }

            if (shouldSave) {
                if (downloadUrl == null || downloadUrl.trim().isEmpty()) {
                    log.error("OnlyOffice 回调 URL 为空: fileId={}, status={}, reason={}", fileId, status, saveReason);
                    return Map.of("error", 1, "message", "下载URL为空");
                }

                log.info("开始保存文档: fileId={}, triggerUserId={}, status={}, reason={}, url={}",
                        fileId, triggerUserId, status, saveReason, downloadUrl);
                //TODO
//                docFileService.saveDocumentContent(fileId, downloadUrl, saveReason, triggerUserId);
                log.info("文档保存成功: fileId={}, triggerUserId={}, reason={}", fileId, triggerUserId, saveReason);
            }

            // 按 OnlyOffice 协议返回 {error:0}
            return Map.of("error", 0);
        } catch (Exception e) {
            log.error("OnlyOffice 回调处理失败: fileId={}, body={}", fileId, body, e);
            return Map.of("error", 1, "message", e.getMessage());
        }
    }
}
