package com.zt.plat.module.qms.business.reportdoc.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import com.zt.plat.framework.business.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.framework.excel.core.util.ExcelUtils;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigUserSignatureDO;
import com.zt.plat.module.qms.business.config.service.ConfigUserSignatureService;
import com.zt.plat.module.qms.business.reportdoc.controller.vo.*;
import com.zt.plat.module.qms.business.reportdoc.dal.dataobject.ReportDocumentFileDO;
import com.zt.plat.module.qms.business.reportdoc.dal.dataobject.ReportDocumentMainDO;
import com.zt.plat.module.qms.business.reportdoc.dal.dataobject.ReportDocumentTypeDO;
import com.zt.plat.module.qms.business.reportdoc.service.*;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.module.qms.common.data.service.DataTemplateService;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.system.api.iwork.dto.IWorkOperationRespDTO;
import com.zt.plat.module.system.api.iwork.dto.IWorkWorkflowCreateReqDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.zt.plat.framework.common.pojo.CommonResult.error;
import static com.zt.plat.framework.common.pojo.CommonResult.success;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.REPORT_DOCUMENT_TYPE_NOT_EXISTS;

@Tag(name = "管理后台 - 检测报告业务")
@RestController
@RequestMapping("/qms/report-document-main")
@Validated
@Slf4j
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.reportdocumentmain")
public class ReportDocumentMainController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private ReportDocumentMainService reportDocumentMainService;
    @Resource private ReportDocumentDataService reportDocumentDataService;
    @Resource private ReportDocumentTypeService reportDocumentTypeService;
    @Resource private ReportDocumentFileService reportDocumentFileService;
    @Resource private ReportDocumentAssistService reportDocumentAssistService;


    @Resource private DataTemplateService dataTemplateService;

    @RequestMapping("/testAsyncTask")
    public CommonResult<String> testAsyncTask(@RequestParam Long id) {
        ReportDocumentMainSaveReqVO reqVO = new ReportDocumentMainSaveReqVO();
        reqVO.setId(id);
        reqVO.setFlowStatus("async");
        reportDocumentMainService.updateReportDocumentMain(reqVO);

        reportDocumentMainService.testAsyncTask(id);
        return CommonResult.success("success");
    }


    @PostMapping("/create")
    @Operation(summary = "创建检测报告")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:create')")
    public CommonResult<ReportDocumentMainRespVO> createReportDocumentMain(@Valid @RequestBody ReportDocumentMainSaveReqVO createReqVO) {
        return success(reportDocumentMainService.createReportDocumentMain(createReqVO));
    }

    @PostMapping("/createTempData")
    @Operation(summary = "创建临时数据")
    public CommonResult<ReportDocumentMainRespVO> createTempData(@RequestBody ReportDocumentMainSaveReqVO vo) {
        Long reportDocumentTypeId = vo.getReportDocumentTypeId();
        if(reportDocumentTypeId == null){
            return error(REPORT_DOCUMENT_TYPE_NOT_EXISTS, "报告类型ID不能为空，请刷新后重试");
        }
        ReportDocumentTypeDO typeDO = reportDocumentTypeService.getReportDocumentType(reportDocumentTypeId);
        if(typeDO == null){
            return error(REPORT_DOCUMENT_TYPE_NOT_EXISTS, "报告类型不存在，请刷新后重试");
        }
        String dataTemplateKey = typeDO.getReportKey();
        DataTemplateDO dataTemplateDO = dataTemplateService.getLatestDataByKey(dataTemplateKey);
        if(dataTemplateDO == null)
            return error(REPORT_DOCUMENT_TYPE_NOT_EXISTS, "表单编辑器模板不存在，请联系管理员处理");
        vo.setDataTemplateId(dataTemplateDO.getId());
        vo.setDocumentTitle(typeDO.getName());
        vo.setFlowKey(typeDO.getFlowKey());
        vo.setDocumentType(typeDO.getDocumentType());
        vo.setConfigReportTypeId(typeDO.getConfigReportTypeId());
        vo.setDocumentConfig(JSONObject.toJSONString(typeDO));
        vo.setFlowStatus(QmsCommonConstant.NOT_START);
        vo.setCancelFlag("-1");
        return success(reportDocumentMainService.createReportDocumentMain(vo));
    }

    @PostMapping("/createProcessInstance")
    @Operation(summary = "发起流程")
    public CommonResult<ReportDocumentMainRespVO> createProcessInstance(@Valid @RequestBody ReportDocumentMainSaveReqVO createReqVO) {
        return reportDocumentMainService.createProcessInstance(createReqVO);
    }

    @PostMapping("/execAddDataBySample")
    @Operation(summary = "增加数据（按样品）")
    public CommonResult<String> execAddDataBySample(@RequestBody ReportDocumentMainSaveReqVO vo) {
        return reportDocumentMainService.execAddDataBySample(vo);
    }

    @PostMapping("/execAddDataByEntrust")
    @Operation(summary = "增加数据（按委托）")
    public CommonResult<String> execAddDataByEntrust(@RequestBody ReportDocumentMainSaveReqVO vo) {
        return reportDocumentMainService.execAddDataByEntrust(vo);
    }

    @PostMapping("/execRemoveData")
    @Operation(summary = "移除数据")
    public CommonResult<String> execRemoveData(@RequestBody ReportDocumentMainSaveReqVO vo) {
        return reportDocumentMainService.execRemoveData(vo);
    }

    @PutMapping("/doSave")
    @Operation(summary = "更新检测报告业务")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:update')")
    public CommonResult<Boolean> doSave(@Valid @RequestBody ReportDocumentMainSaveReqVO updateReqVO) {
        updateReqVO.setCancelFlag("0");
        reportDocumentMainService.doSave(updateReqVO);
        return success(true);
    }


    @PutMapping("/update")
    @Operation(summary = "更新检测报告业务")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:update')")
    public CommonResult<Boolean> updateReportDocumentMain(@Valid @RequestBody ReportDocumentMainSaveReqVO updateReqVO) {
        updateReqVO.setCancelFlag("0");
        reportDocumentMainService.updateReportDocumentMain(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除检测报告业务")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:delete')")
    public CommonResult<Boolean> deleteReportDocumentMain(@RequestParam("id") Long id) {
        reportDocumentMainService.deleteReportDocumentMain(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除检测报告业务")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:delete')")
    public CommonResult<Boolean> deleteReportDocumentMainList(@RequestBody BatchDeleteReqVO req) {
        reportDocumentMainService.deleteReportDocumentMainListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得检测报告业务")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:query')")
    public CommonResult<ReportDocumentMainRespVO> getReportDocumentMain(@RequestParam("id") Long id, @RequestParam(value = "editFlag", required = false, defaultValue = "false") String editFlag) {
        ReportDocumentMainDO reportDocumentMain = reportDocumentMainService.getReportDocumentMain(id);

        ReportDocumentMainRespVO vo = BeanUtils.toBean(reportDocumentMain, ReportDocumentMainRespVO.class);

        //处理签名
        String docSig = vo.getDocumentSignature();
        String docSigJsonStr = reportDocumentDataService.assembleSignature(docSig);
        if(!ObjectUtils.isEmpty(docSigJsonStr))
            vo.setDocumentSignature(docSigJsonStr);
        return success(vo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得检测报告业务分页")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:query')")
    public CommonResult<PageResult<ReportDocumentMainRespVO>> getReportDocumentMainPage(@Valid ReportDocumentMainPageReqVO pageReqVO) {
        PageResult<ReportDocumentMainRespVO> pageResult = reportDocumentMainService.getReportDocumentMainPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出检测报告业务 Excel")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportReportDocumentMainExcel(@Valid ReportDocumentMainPageReqVO pageReqVO,
                                              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ReportDocumentMainRespVO> list = reportDocumentMainService.getReportDocumentMainPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "检测报告业务.xls", "数据", ReportDocumentMainRespVO.class, list);
    }

    @GetMapping("/testCreateIworkWorkflow")
    @Operation(summary = "测试发起iwork流程")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:query')")
    public CommonResult<IWorkOperationRespDTO> createIworkWorkflow() {
        IWorkWorkflowCreateReqDTO req = new IWorkWorkflowCreateReqDTO();
        req.setJbr("1001");
        req.setYybm("2001");
        req.setFb("3001");
        req.setSqsj("2025-01-01");
        req.setYyqx("对外邮寄");
//        req.setYyfkUrl("https://files.example.com/evidence.pdf");
        req.setYysy("与客户合同用印");
        req.setXyywjUrl("http://172.16.46.63:30002/yudao/20251204/%E6%B5%8B%E8%AF%95pdf_1764818842846.pdf?response-cache-control=no-cache%2C%20no-store%2C%20must-revalidate&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20251209T093343Z&X-Amz-SignedHeaders=host&X-Amz-Credential=EKplIEnbNgfYBAZbEJNa%2F20251209%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Expires=86400&X-Amz-Signature=37d63249667ea855f9a51bdf47bbb044d5860c302721f52fff2ba644985bae4c");
        req.setYysx("检测报告用印");
        req.setYwxtdjbh("JY-20251209-0001");
//        CommonResult<IWorkOperationRespDTO> ret = reportDocumentMainService.createIWorkflow(req);
        return null;
    }


    @GetMapping("/createIWorkflow")
    @Operation(summary = "创建iwork流程-调试用")
    //@PreAuthorize("@ss.hasPermission('qms:report-document-main:query')")
    public CommonResult<IWorkOperationRespDTO> createIWorkflow(HttpServletRequest request) {
        String mainId = request.getParameter("mainId");
        String fileId = request.getParameter("fileId");
        ReportDocumentMainDO mainDO = reportDocumentMainService.getReportDocumentMain(Long.valueOf(mainId));
        ReportDocumentFileDO fileDO = reportDocumentFileService.getReportDocumentFile(Long.valueOf(fileId));
        return reportDocumentAssistService.createIWorkflow(mainDO, fileDO);
    }

}