package com.jeeplus.finance.projectReport.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.finance.invoice.controller.CwFinanceInvoiceController;
import com.jeeplus.finance.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.finance.invoice.util.FreemarkerUtil;
import com.jeeplus.finance.invoice.util.SignaturePostUtil;
import com.jeeplus.finance.projectReport.domain.CwProjectReport;
import com.jeeplus.finance.projectReport.domain.CwProjectReportData;
import com.jeeplus.finance.projectReport.domain.CwProjectReportSignature;
import com.jeeplus.finance.projectReport.domain.CwSignatureAnnotator;
import com.jeeplus.finance.projectReport.mapper.CwSignatureAnnotatorMapper;
import com.jeeplus.finance.projectReport.mapper.ProjectReportWorkAttachmentMapper;
import com.jeeplus.finance.projectReport.service.CwProjectReportNumberApplyService;
import com.jeeplus.finance.projectReport.service.CwProjectReportService;
import com.jeeplus.finance.projectReport.service.dto.CwProjectReportDTO;
import com.jeeplus.finance.projectReport.service.dto.CwProjectReportSignatureDTO;
import com.jeeplus.finance.projectReport.service.dto.NumberReplaceDTO;
import com.jeeplus.finance.projectReport.service.dto.ProjectReportWorkAttachmentDTO;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportArchiveDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
//import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.DictValueInfoDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.DictUtils;
//import com.jeeplus.sys.utils.UserUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-16 14:15
 **/
@RestController
@Api("财务报告信息")
@RequestMapping(value = "/cwProjectReport")
public class CwProjectReportController {
    private static Logger log = LoggerFactory.getLogger(CwProjectReportController.class);


    @Resource
    private CwProjectReportService projectReportService;
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private ProjectReportWorkAttachmentMapper attachmentMapper;
    @Autowired
    private IFlowableApi flowTaskService;
    @Resource
    private CwProjectReportNumberApplyService cwProjectReportNumberApplyService;


    /**
     * 保存财务报告信息-流程
     * @param reportData
     * @return
     */
    @ApiLog(value = "保存财务报告信息-流程", type = LogTypeEnum.SAVE)
    //@PreAuthorize("hasAnyAuthority('cwProjectReport:add','cwProjectReport:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody CwProjectReportData reportData) throws Exception {
        String id = projectReportService.saveForm(reportData);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report").add("businessId", id).ok ("操作成功");
    }

    /**
     * 修改报告审定金额
     * @param reportData
     * @return
     */
    @ApiLog(value = "修改报告审定金额", type = LogTypeEnum.SAVE)
    @PostMapping("updateAmount")
    public ResponseEntity updateAmount(@Valid @RequestBody CwProjectReportData reportData) throws Exception {
        String id = projectReportService.updateAmount(reportData);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report").add("businessId", id).ok ("操作成功");
    }


    /**
     * 报告号申请所用
     * 保存财务报告信息-流程
     * @param reportData
     * @return
     */
    @ApiLog(value = "保存财务报告信息-流程", type = LogTypeEnum.SAVE)
    //@PreAuthorize("hasAnyAuthority('cwProjectReport:add','cwProjectReport:edit')")
    @PostMapping("saveForm2")
    public ResponseEntity saveForm2(@Valid @RequestBody CwProjectReportData reportData) throws Exception {
        String id = projectReportService.saveForm2(reportData);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report").add("businessId", id).ok ("操作成功");
    }

    /**
     * 签章附件保存
     * @return
     */
    @ApiLog(value = "签章附件保存", type = LogTypeEnum.SAVE)
    @PostMapping("saveSignFiles")
    public ResponseEntity saveSignFiles(@RequestBody CwProjectReportData reportData) {
        System.out.println("进入controller前");
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
//        UserDTO userDTO = new UserDTO();
        if (CollectionUtil.isEmpty(reportData.getCwFileInfoList())) {
            reportData.setCwFileInfoList(new ArrayList<>());
        }
        System.out.println("进入controller中");
        projectReportService.updateSignatureFiles(reportData.getCwFileInfoList(),userDTO,reportData.getId());
        System.out.println("进入controller后");
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 查询财务项目信息列表
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询财务报告信息列表")
    @PreAuthorize("hasAuthority('cwProjectReport:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwProjectReportData>> data(CwProjectReportData projectReportData, Page<CwProjectReportData> page) throws Exception {
        IPage<CwProjectReportData> result = new Page<CwProjectReportData>();
        result = projectReportService.findList (page,projectReportData);
        result.getRecords().stream().forEach(i -> {

            //当项目经理是跨租户的人员时，则特殊处理
            if (StringUtils.isBlank(i.getProjectMasterName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId());
                    if(null != byId)
                    i.setProjectMasterName(byId.getName());
                }
            }
            if (StringUtils.isBlank(i.getRealHeaderName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId2())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId2());
                    if(null != byId)
                    i.setRealHeaderName(byId.getName());
                }

            }

            // 复核
            if (StringUtils.isNotBlank(i.getRevTaskId()) && StringUtils.isNotBlank(i.getReviewStatus())) {
                if ("2".equals(i.getReviewStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsRev(flowTaskService.getTaskAuditUsers(i.getRevTaskId()));  // 获取数据审核人
                }
            }
            // 签章
            if (StringUtils.isNotBlank(i.getSignatureType())) {
                // 电子章
                if ("1".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId1()) && StringUtils.isNotBlank(i.getStatus1())) {
                        if ("2".equals(i.getStatus1())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign1(flowTaskService.getTaskAuditUsers(i.getSignTaskId1()));  // 获取数据审核人
                        }
                    }
                }
                // 公章+执业章
                if ("2".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId2()) && StringUtils.isNotBlank(i.getStatus2())) {
                        if ("2".equals(i.getStatus2())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign2(flowTaskService.getTaskAuditUsers(i.getSignTaskId2()));  // 获取数据审核人
                        }
                    }
                }
                // 实体章
                if ("3".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId3()) && StringUtils.isNotBlank(i.getStatus3())) {
                        if ("2".equals(i.getStatus3())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign3(flowTaskService.getTaskAuditUsers(i.getSignTaskId3()));  // 获取数据审核人
                        }
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }

    /**
     * 查询财务项目信息列表(开票选择)
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询财务报告信息列表(开票选择)")
    @PreAuthorize("hasAuthority('cwProjectReport:list')")
    @GetMapping("chooseList")
    public ResponseEntity<IPage<CwProjectReportData>> data2(CwProjectReportData projectReportData, Page<CwProjectReportData> page) throws Exception {
        IPage<CwProjectReportData> result = new Page<CwProjectReportData>();
        result = projectReportService.findList2 (page,projectReportData);
        result.getRecords().stream().forEach(i -> {

            //当项目经理是跨租户的人员时，则特殊处理
            if (StringUtils.isBlank(i.getProjectMasterName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId());
                    if(null != byId)
                        i.setProjectMasterName(byId.getName());
                }
            }
            if (StringUtils.isBlank(i.getRealHeaderName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId2())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId2());
                    if(null != byId)
                        i.setRealHeaderName(byId.getName());
                }

            }

            // 复核
            if (StringUtils.isNotBlank(i.getRevTaskId()) && StringUtils.isNotBlank(i.getReviewStatus())) {
                if ("2".equals(i.getReviewStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsRev(flowTaskService.getTaskAuditUsers(i.getRevTaskId()));  // 获取数据审核人
                }
            }
            // 签章
            if (StringUtils.isNotBlank(i.getSignatureType())) {
                // 电子章
                if ("1".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId1()) && StringUtils.isNotBlank(i.getStatus1())) {
                        if ("2".equals(i.getStatus1())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign1(flowTaskService.getTaskAuditUsers(i.getSignTaskId1()));  // 获取数据审核人
                        }
                    }
                }
                // 公章+执业章
                if ("2".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId2()) && StringUtils.isNotBlank(i.getStatus2())) {
                        if ("2".equals(i.getStatus2())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign2(flowTaskService.getTaskAuditUsers(i.getSignTaskId2()));  // 获取数据审核人
                        }
                    }
                }
                // 实体章
                if ("3".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId3()) && StringUtils.isNotBlank(i.getStatus3())) {
                        if ("2".equals(i.getStatus3())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign3(flowTaskService.getTaskAuditUsers(i.getSignTaskId3()));  // 获取数据审核人
                        }
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }

    /**
     * 根据人员id查询签章报告数据
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("根据人员id查询签章报告数据")
    @GetMapping("getSignatureScribeList")
    public ResponseEntity<IPage<CwProjectReportData>> getSignatureScribeList(CwProjectReportData projectReportData, Page<CwProjectReportData> page) throws Exception {
        IPage<CwProjectReportData> result = new Page<CwProjectReportData>();
        result = projectReportService.getSignatureScribeList (page,projectReportData);
        result.getRecords().stream().forEach(i -> {

            //当项目经理是跨租户的人员时，则特殊处理
            if (StringUtils.isBlank(i.getProjectMasterName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId());
                    if(null != byId)
                        i.setProjectMasterName(byId.getName());
                }
            }
            if (StringUtils.isBlank(i.getRealHeaderName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId2())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId2());
                    if(null != byId)
                        i.setRealHeaderName(byId.getName());
                }

            }

            // 复核
            if (StringUtils.isNotBlank(i.getRevTaskId()) && StringUtils.isNotBlank(i.getReviewStatus())) {
                if ("2".equals(i.getReviewStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsRev(flowTaskService.getTaskAuditUsers(i.getRevTaskId()));  // 获取数据审核人
                }
            }
            // 签章
            if (StringUtils.isNotBlank(i.getSignatureType())) {
                // 电子章
                if ("1".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId1()) && StringUtils.isNotBlank(i.getStatus1())) {
                        if ("2".equals(i.getStatus1())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign1(flowTaskService.getTaskAuditUsers(i.getSignTaskId1()));  // 获取数据审核人
                        }
                    }
                }
                // 公章+执业章
                if ("2".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId2()) && StringUtils.isNotBlank(i.getStatus2())) {
                        if ("2".equals(i.getStatus2())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign2(flowTaskService.getTaskAuditUsers(i.getSignTaskId2()));  // 获取数据审核人
                        }
                    }
                }
                // 实体章
                if ("3".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId3()) && StringUtils.isNotBlank(i.getStatus3())) {
                        if ("2".equals(i.getStatus3())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign3(flowTaskService.getTaskAuditUsers(i.getSignTaskId3()));  // 获取数据审核人
                        }
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }


    /**
     * 查询财务项目信息列表(移动端)
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询财务报告信息列表")
    @PreAuthorize("hasAuthority('cwProjectReport:list')")
    @GetMapping("listApp")
    public ResponseEntity<IPage<CwProjectReportData>> dataApp(CwProjectReportData projectReportData, Page<CwProjectReportData> page) throws Exception {
        IPage<CwProjectReportData> result = new Page<CwProjectReportData>();
        result = projectReportService.findListApp (page,projectReportData);
        result.getRecords().stream().forEach(i -> {

            //当项目经理是跨租户的人员时，则特殊处理
            if (StringUtils.isBlank(i.getProjectMasterName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId());
                    if(null != byId)
                        i.setProjectMasterName(byId.getName());
                }
            }
            if (StringUtils.isBlank(i.getRealHeaderName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId2())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId2());
                    if(null != byId)
                        i.setRealHeaderName(byId.getName());
                }

            }

            // 复核
            if (StringUtils.isNotBlank(i.getRevTaskId()) && StringUtils.isNotBlank(i.getReviewStatus())) {
                if ("2".equals(i.getReviewStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsRev(flowTaskService.getTaskAuditUsers(i.getRevTaskId()));  // 获取数据审核人
                }
            }
            // 签章
            if (StringUtils.isNotBlank(i.getSignatureType())) {
                // 电子章
                if ("1".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId1()) && StringUtils.isNotBlank(i.getStatus1())) {
                        if ("2".equals(i.getStatus1())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign1(flowTaskService.getTaskAuditUsers(i.getSignTaskId1()));  // 获取数据审核人
                        }
                    }
                }
                // 公章+执业章
                if ("2".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId2()) && StringUtils.isNotBlank(i.getStatus2())) {
                        if ("2".equals(i.getStatus2())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign2(flowTaskService.getTaskAuditUsers(i.getSignTaskId2()));  // 获取数据审核人
                        }
                    }
                }
                // 实体章
                if ("3".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId3()) && StringUtils.isNotBlank(i.getStatus3())) {
                        if ("2".equals(i.getStatus3())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign3(flowTaskService.getTaskAuditUsers(i.getSignTaskId3()));  // 获取数据审核人
                        }
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }
    /**
     * 根据id修改状态值status
     * @param data
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody CwProjectReportData data) {
        String s = projectReportService.updateStatusById(data);
        return ResponseEntity.ok(s);
    }

    /**
     * 查询客户信息数据
     * @param id
     * @return
     */
    @ApiLog("查询财务报告数据")
    // @PreAuthorize ("hasAnyAuthority('cwProjectReport:view','cwProjectReport:add','cwProjectReport:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwProjectReportData projectReportData = projectReportService.queryById ( id );
        return ResponseEntity.ok (projectReportData);
    }

    /**
     * 查询客户信息数据  报告号申请流程所用
     * @param id
     * @return
     */
    @ApiLog("查询财务报告数据")
    // @PreAuthorize ("hasAnyAuthority('cwProjectReport:view','cwProjectReport:add','cwProjectReport:edit')")
    @GetMapping("queryById2")
    public ResponseEntity queryById2(@RequestParam("id") String id) {
        CwProjectReportData projectReportData = projectReportService.queryById2 ( id );
        return ResponseEntity.ok (projectReportData);
    }

    /**
     * 下载报告审核单
     * @param response
     * @param id
     */
    @RequestMapping(value="downloadCwReportAuditTpl")
    @ResponseBody
    public void downloadCwReportAuditTpl(HttpServletResponse response,@RequestParam("id") String id)  {
        Map data = projectReportService.getAuditInfoMap(response, id );

        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("cwAudit.ftl","UTF-8");

            File docFile = new File("报告审核单.xls");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.finance.invoice.util.ResponseUtil.docResponse("报告审核单.xls",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"报告审核单.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"报告审核单.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 删除业务提问
     * @param ids
     * @return
     */
    @ApiLog(value = "删除财务报告信息", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cwProjectReport:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return projectReportService.deleteByIds(ids);
    }

    /**
     * 查询客户信息列表
     * @param cwWorkClientBaseDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询客户信息列表")
    @PreAuthorize("hasAuthority('cwProjectReport:clineList')")
    @GetMapping("clineList")
    public ResponseEntity<IPage<CwWorkClientBaseDTO>> data(CwWorkClientBaseDTO cwWorkClientBaseDTO, Page<CwWorkClientBaseDTO> page, String projectId) throws Exception {
        IPage<CwWorkClientBaseDTO> result = new Page<CwWorkClientBaseDTO>();
        result = projectReportService.findClineList (page,cwWorkClientBaseDTO,projectId);
        return ResponseEntity.ok (result);
    }

    /**
     * 签章链接
     * @param cwProjectReportData
     * @return
     */
    @ApiLog(value = "签章链接", type = LogTypeEnum.SAVE)
    @PostMapping("saveFlowableParam")
    public ResponseEntity<String> saveFlowableParam(@Valid @RequestBody CwProjectReportData cwProjectReportData) {
        //查询报告文件信息（电子章）
//        List<WorkAttachment> fileList = attachmentMapper.selectWorkAttachmentByReportId(cwProjectReportData.getId());
        // 有电子章的附件时，走签章流程
//        if (CollectionUtil.isNotEmpty(fileList)) {
//            CwProjectReportData cwProjectReportDto = projectReportService.queryById(cwProjectReportData.getId());
//            // 获取签章页面url
//            String mobile = UserUtils.getCurrentUserDTO().getMobile();
//            String signatureContractUrl = SignaturePostUtil.getSignatureContractUrl(cwProjectReportDto.getSignatureContractId(), mobile);
//            // 将数据存储到redis中，key为contractId
//            cwProjectReportData.getCommitParamDTO().setVars(cwProjectReportDto);
//            redisUtils.set("cw_report_signature_" + cwProjectReportDto.getSignatureContractId(),cwProjectReportData.getCommitParamDTO());
//            redisUtils.expire("cw_report_signature_" + cwProjectReportDto.getSignatureContractId(),24, TimeUnit.HOURS);
//            return ResponseEntity.ok(signatureContractUrl);
//        } else {
//            // 没有电子章的附件时，走正常审核流程
//            // 流程审核通过
//            projectReportService.commitFlowable(cwProjectReportData);
//            return ResponseEntity.ok("操作成功");
//        }

        CwProjectReportData cwProjectReportDto = projectReportService.queryById(cwProjectReportData.getId());
        // 获取签章页面url
        String mobile = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken()).getMobile();
        String signatureContractUrl = SignaturePostUtil.getSignatureContractUrl(cwProjectReportDto.getSignatureContractId(), mobile);
        // 将数据存储到redis中，key为contractId
        if("1".equals(cwProjectReportDto.getSignatureType())) {
            redisUtils.set("cw_report_signature_" + cwProjectReportDto.getSignatureContractId(),cwProjectReportDto.getSid1());
        }
        if("2".equals(cwProjectReportDto.getSignatureType())) {
            redisUtils.set("cw_report_signature_" + cwProjectReportDto.getSignatureContractId(),cwProjectReportDto.getSid2());
        }
        redisUtils.expire("cw_report_signature_" + cwProjectReportDto.getSignatureContractId(),24, TimeUnit.HOURS);
        return ResponseEntity.ok(signatureContractUrl);
    }

    /**
     * 签章流程送审
     * @param cwProjectReportData
     * @return
     */
    @ApiLog(value = "签章流程送审", type = LogTypeEnum.SAVE)
    @PostMapping("saveData")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> saveData(@Valid @RequestBody CwProjectReportData cwProjectReportData) {
        // 修改报告表的 “签字注师1” 和 “签字注师2”
        if (ObjectUtil.isNotEmpty(cwProjectReportData)) {
            CwProjectReport cwProjectReport = new CwProjectReport();
            cwProjectReport.setId(cwProjectReportData.getId());
            if (StringUtils.isNotBlank(cwProjectReportData.getSignatureAnnotator1())) {
                cwProjectReport.setSignatureAnnotator1(cwProjectReportData.getSignatureAnnotator1());
            }
            if (StringUtils.isNotBlank(cwProjectReportData.getSignatureAnnotator2())) {
                cwProjectReport.setSignatureAnnotator2(cwProjectReportData.getSignatureAnnotator2());
            }
            if (StringUtils.isNotBlank(cwProjectReportData.getIndustry())) {
                cwProjectReport.setIndustry(cwProjectReportData.getIndustry());
            }
            if (StringUtils.isNotBlank(cwProjectReportData.getBusinessObjects())) {
                cwProjectReport.setBusinessObjects(cwProjectReportData.getBusinessObjects());
            }
            projectReportService.updateAnnotatorById(cwProjectReport);
        }
        if ("3".equals(cwProjectReportData.getSignatureType())) {
            // 实体公章流程
            String signatureId = projectReportService.getSignature(cwProjectReportData);
            return ResponseUtil.newInstance().add("businessTable", "cw_project_report_signature").add("businessId", signatureId).ok ("操作成功");
        } else {
            //查询报告文件信息（电子章）
            //List<WorkAttachment> fileList = attachmentMapper.selectWorkAttachmentByReportId(cwProjectReportData.getId());
            List<WorkAttachmentInfo> fileList = SpringUtil.getBean ( IWorkAttachmentApi.class ).selectWorkAttachmentByAttachmentId(cwProjectReportData.getId());
            if (CollectionUtil.isNotEmpty(fileList)) {
                // 有电子章的附件时，走签章流程
                Map<String, Object> signatureContractId = projectReportService.createSignatureContractId(cwProjectReportData);
                boolean bool = (boolean)signatureContractId.get("success");
                if (bool) {
                    String signatureId = projectReportService.getSignature(cwProjectReportData);
                    return ResponseUtil.newInstance().add("businessTable", "cw_project_report_signature").add("businessId", signatureId).ok ("操作成功");
                }
                return ResponseEntity.badRequest().body((String) signatureContractId.get("message"));
            } else {
                // 没有电子章的附件时，走正常审核流程
                String signatureId = projectReportService.getSignature(cwProjectReportData);
                return ResponseUtil.newInstance().add("businessTable", "cw_project_report_signature").add("businessId", signatureId).ok ("操作成功");
            }
        }
    }

    /**
     * 根据签章表id查询报告数据
     * @param id
     * @return
     */
    @ApiLog("根据签章表id查询报告数据")
    @PreAuthorize ("hasAnyAuthority('cwProjectReport:view','cwProjectReport:add','cwProjectReport:edit')")
    @GetMapping("queryBySignatureId")
    public ResponseEntity queryBySignatureId(@RequestParam("id") String id) {
        CwProjectReportData projectReportData = projectReportService.queryBySignatureId ( id );
        return ResponseEntity.ok (projectReportData);
    }

    /**
     * 根据签章表id查询数据
     * @param id
     * @return
     */
    @ApiLog("根据签章表id查询数据")
    @PreAuthorize ("hasAnyAuthority('cwProjectReport:view','cwProjectReport:add','cwProjectReport:edit')")
    @GetMapping("findBySignatureId")
    public ResponseEntity findBySignatureId(@RequestParam("id") String id) {
        CwProjectReportSignature cwProjectReportSignature = projectReportService.findBySignatureId ( id );
        return ResponseEntity.ok (cwProjectReportSignature);
    }

    /**
     * 根据id修改签章表状态值status
     * @param data
     * @return
     */
    @ApiOperation(value = "根据id修改签章表状态值status")
    @PostMapping(value = "/updateSignatureStatusById")
    public ResponseEntity<String> updateSignatureStatusById(@RequestBody CwProjectReportSignatureDTO data) {
        String s = projectReportService.updateSignatureStatusById(data);
        return ResponseEntity.ok(s);
    }

    /**
     * 根据id修改签章表状态值status
     * @return
     */
    @ApiOperation(value = "根据id修改签章表状态值status")
    @PostMapping(value = "/aaa")
    public ResponseEntity<String> updateSignatureStatusById() {
        String s = "projectReportService.updateSignatureStatusById(data);";
        return ResponseEntity.ok(s);
    }

    /**
     * 根据id修改签字注师状态值status
     * @return
     */
    @ApiOperation(value = "根据id修改签字注师状态值status")
    @PostMapping(value = "updateSigStatusById")
    public ResponseEntity<String> updateSigStatusById(@RequestBody CwProjectReport data) {
        String s = projectReportService.updateSigStatusById(data);
        return ResponseEntity.ok(s);
    }



    /**
     * 导出分所报销数据
     * @param cwProjectReportData
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出报告数据信息")
    @GetMapping("export")
    @ApiOperation(value = "导出报告数据信息excel")
    public void exportFile(CwProjectReportData cwProjectReportData, Page <CwProjectReportData> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );

        List<CwProjectReportData> result;
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) {
            result = projectReportService.findList ( page, cwProjectReportData ).getRecords();
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) {
            result = projectReportService.findList ( page, cwProjectReportData ).getRecords().stream ( ).filter ( info ->
                    options.getSelectIds ( ).contains ( info.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize ( -1 );
            page.setCurrent ( 0 );
            result = projectReportService.findList ( page, cwProjectReportData ).getRecords();
        }
        if(result.size()>0){
            String cwStatusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_status");
            Map<String,Object> cwStatusDictValueDTOs = JSON.parseObject(cwStatusDatas, new TypeReference<Map<String,Object>>() {});

            String cwProjectReportSignStatusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_project_report_sign_status");
            Map<String,Object> cwProjectReportSignStatusDictValueDTOs = JSON.parseObject(cwProjectReportSignStatusDatas, new TypeReference<Map<String,Object>>() {});

            //报备类型
            String filingType = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_work_client_report_type");
            Map<String,Object> filingTypeDictValueDTOs = JSON.parseObject(filingType, new TypeReference<Map<String,Object>>() {});
            //项目分类
            String projectClassification = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("project_classification");
            Map<String,Object> projectClassificationDictValueDTOs = JSON.parseObject(projectClassification, new TypeReference<Map<String,Object>>() {});


            for (CwProjectReportData info : result) {
//                if(StringUtils.isNotBlank(info.getStatus())){
//                    info.setStatus(DictUtils.getDictLabel(info.getStatus(), "cw_status", ""));
//                }
                if(StringUtils.isNotBlank(info.getReviewStatus())){
                    for (String key : cwStatusDictValueDTOs.keySet()) {
                        if(info.getReviewStatus().equals(key)){
                            info.setReviewStatus(String.valueOf(cwStatusDictValueDTOs.get(key)));
                            break;
                        }
                    }
                    //info.setReviewStatus(SpringUtil.getBean ( IDictApi.class ).getDictLabel(info.getReviewStatus(), "cw_status", ""));
                }
                if(StringUtils.isNotBlank(info.getStatus())){
                    for (String key : cwStatusDictValueDTOs.keySet()) {
                        if(info.getStatus().equals(key)){
                            info.setApplyStatus(String.valueOf(cwStatusDictValueDTOs.get(key)));
                            break;
                        }
                    }
                    //info.setReviewStatus(SpringUtil.getBean ( IDictApi.class ).getDictLabel(info.getReviewStatus(), "cw_status", ""));
                }
                if ("1".equals(info.getSignatureType())) {
                    if(StringUtils.isNotBlank(info.getStatus1())){
                        for (String key : cwStatusDictValueDTOs.keySet()) {
                            if(info.getStatus1().equals(key)){
                                info.setStatus1(String.valueOf(cwStatusDictValueDTOs.get(key)));
                                break;
                            }
                        }
                        //info.setStatus1(SpringUtil.getBean ( IDictApi.class ).getDictLabel(info.getStatus1(), "cw_status", ""));
                    }
                }
                if ("2".equals(info.getSignatureType())) {
                    if(StringUtils.isNotBlank(info.getStatus2())){
                        for (String key : cwProjectReportSignStatusDictValueDTOs.keySet()) {
                            if(info.getStatus1().equals(key)){
                                info.setStatus1(String.valueOf(cwProjectReportSignStatusDictValueDTOs.get(key)));
                                break;
                            }
                        }
                        //info.setStatus1(SpringUtil.getBean ( IDictApi.class ).getDictLabel(info.getStatus2(), "cw_project_report_sign_status", ""));
                    }
                }
                if ("3".equals(info.getSignatureType())) {
                    if(StringUtils.isNotBlank(info.getStatus3())){
                        for (String key : cwProjectReportSignStatusDictValueDTOs.keySet()) {
                            if(info.getStatus1().equals(key)){
                                info.setStatus1(String.valueOf(cwProjectReportSignStatusDictValueDTOs.get(key)));
                                break;
                            }
                        }
                        //info.setStatus1(SpringUtil.getBean ( IDictApi.class ).getDictLabel(info.getStatus3(), "cw_project_report_sign_status", ""));
                    }
                }

                if(StringUtils.isNotBlank(info.getProjectType())){
                    for (String key : filingTypeDictValueDTOs.keySet()) {
                        if(info.getProjectType().equals(key)){
                            info.setProjectType(String.valueOf(filingTypeDictValueDTOs.get(key)));
                            break;
                        }
                    }
                }

                if(StringUtils.isNotBlank(info.getProjectClassification())){
                    for (String key : projectClassificationDictValueDTOs.keySet()) {
                        if(info.getProjectClassification().equals(key)){
                            info.setProjectClassification(String.valueOf(projectClassificationDictValueDTOs.get(key)));
                            break;
                        }
                    }
                }

            }
        }
        EasyPoiUtil.exportExcel ( result, "报告信息",  options.getSheetName ( ), CwProjectReportData.class, fileName, response );
    }



    /**
     * 根据报告签章id查询签章审核节点信息
     * @param id
     * @return
     */
    @ApiLog("根据报告签章id查询签章审核节点信息")
    @GetMapping("getAuditNodeByReportId")
    public ResponseEntity getAuditNodeByReportId(@RequestParam("id") String id) {
        Map<String, Object> auditNodeByReportId = projectReportService.getAuditNodeByReportId(id);
        return ResponseEntity.ok (auditNodeByReportId);
    }



    /**
     * 根据报告签章id查询签章审核节点信息
     * @param id
     * @return
     */
    @ApiLog("根据报告签章id查询签章审核节点信息")
    @GetMapping("getSignatureTypeById")
    public ResponseEntity getSignatureTypeById(@RequestParam("id") String id,@RequestParam("signatureType") String signatureType) {
        Map<String, Object> signatureTypeById = projectReportService.getSignatureTypeById(id, signatureType);
        return ResponseEntity.ok (signatureTypeById);
    }

    /**
     * 根据客户id查询关联报告
     * @param clientId
     * @param cwProjectReport
     * @return
     * @throws Exception
     */
    @GetMapping("getIdByClientId")
    @ApiOperation(value = "根据客户id查询关联报告")
    public ResponseEntity<List<CwProjectReport>> getIdByClientId(String clientId, CwProjectReport cwProjectReport) throws Exception {
        List<CwProjectReport> cwProjectReportList = projectReportService.getIdByClientId(clientId, cwProjectReport);
        return ResponseEntity.ok(cwProjectReportList);
    }

    /**
     * 根据项目id查询关联报告
     * @param projectId
     * @param cwProjectReport
     * @return
     * @throws Exception
     */
    @GetMapping("getIdByProjectId")
    @ApiOperation(value = "根据项目id查询关联报告")
    public ResponseEntity<List<CwProjectReport>> getIdByProjectId(String projectId, CwProjectReport cwProjectReport) throws Exception {
        List<CwProjectReport> cwProjectReportList = projectReportService.getIdByProjectId(projectId, cwProjectReport);
        return ResponseEntity.ok(cwProjectReportList);
    }

    /**
     * 根据项目id查询关联报告(用于项目登记修改)
     * @param projectId
     * @param cwProjectReport
     * @return
     * @throws Exception
     */
    @GetMapping("getIdByProjectId2")
    @ApiOperation(value = "根据项目id查询关联报告")
    public ResponseEntity<List<CwProjectReport>> getIdByProjectId2(String projectId, CwProjectReport cwProjectReport) throws Exception {
        List<CwProjectReport> cwProjectReportList = projectReportService.getIdByProjectId2(projectId, cwProjectReport);
        return ResponseEntity.ok(cwProjectReportList);
    }

    /**
     * 根据合同id查询关联报告
     * @param contractId
     * @param cwProjectReport
     * @return
     * @throws Exception
     */
    @GetMapping("getIdByContractId")
    @ApiOperation(value = "根据合同id查询关联报告")
    public ResponseEntity<List<CwProjectReport>> getIdByContractId(String contractId, CwProjectReport cwProjectReport) throws Exception {
        List<CwProjectReport> cwProjectReportList = projectReportService.getIdByContractId(contractId, cwProjectReport);
        return ResponseEntity.ok(cwProjectReportList);
    }

    /**
     * 生成报告归档信息
     * @param reportId
     * @return
     * @throws Exception
     */
    @GetMapping("saveReportArchive")
    @ApiOperation(value = "生成报告归档信息")
    public ResponseEntity saveReportArchive(String reportId) throws Exception {
        projectReportService.saveReportArchive(reportId);
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 撤回签章
     * @param reportId
     * @return
     * @throws Exception
     */
    @GetMapping("rebackSign")
    @ApiOperation(value = "撤回签章")
    public ResponseEntity rebackSign(String reportId) throws Exception {
        projectReportService.rebackSign(reportId);
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 撤回复核签章
     * @param reportId
     * @return
     * @throws Exception
     */
    @GetMapping("rebackReviewSign")
    @ApiOperation(value = "撤回签章")
    public ResponseEntity rebackReviewSign(String reportId) throws Exception {
        projectReportService.rebackReviewSign(reportId);
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 数据导入(临时)
     * @param file
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/importExcel")
    @ApiOperation(value = "事务所审计清单表导入")
    public ResponseEntity importExcel(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletResponse response) throws IOException {
        ArrayList<CwProjectReportDTO> arrayList = new ArrayList<>();
        HashMap<String,String> hashMap = new HashMap<>();
        List<CwProjectReportDTO> listA = new ArrayList<>();
        listA=EasyPoiUtil.importExcel(file, 0, 2, CwProjectReportDTO.class);
        projectReportService.importDecide(listA);
        return ResponseEntity.ok(arrayList);
    }


    /**
     * 发起修改签字注师流程
     */
    @ApiOperation(value = "发起修改签字注师流程")
    @PostMapping(value = "saveSignatureAnnotator")
    public ResponseEntity saveSignatureAnnotator(@RequestBody CwProjectReportData reportData) throws Exception {
        String id = projectReportService.saveSignatureAnnotator(reportData);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report_signature_annotator").add("businessId", id).ok ("操作成功");

    }

    /**
     * 报告-修改签字注师   同意
     */
    @ApiOperation(value = "报告-修改签字注师   同意")
    @PostMapping("/updateAgree")
    public ResponseEntity saveReturnAgree(@RequestBody CwProjectReport report) throws Exception{
        String s = projectReportService.updateAgree(report);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report_signature_annotator").add("businessId", report.getId()).ok ("操作成功");
    }



    /**
     * 查找修改签字注师历史记录
     */
    @ApiOperation(value = "查找修改签字注师记录")
    @GetMapping("getSignatureAnnotatorList")
    public ResponseEntity<List<CwSignatureAnnotator>> getSignatureAnnotatorList(String reportId){
        List<CwSignatureAnnotator> cwSignatureAnnotators=projectReportService.getSignatureAnnotatorList(reportId);
        return ResponseEntity.ok(cwSignatureAnnotators);
    }

    /**
     * 根据id查找修改签字注师数据
     */
    @ApiOperation(value = "根据id查找修改签字注师数据")
    @GetMapping("getSigById")
    public ResponseEntity getSigById(@RequestParam("id") String id) {
        CwSignatureAnnotator cwProjectReportSignature = projectReportService.getSigById ( id );
        return ResponseEntity.ok (cwProjectReportSignature);
    }

    /**
     * 修改签字注师退回状态
     */
    @ApiOperation(value = "修改签字注师退回状态")
    @PostMapping("updateStatusByIdSig")
    public ResponseEntity updateStatusByIdSig(@RequestBody CwProjectReport report) {
        projectReportService.updateStatusByIdSig(report);
        return ResponseEntity.ok ("修改成功");
    }

    /**
     * 修改签字注师流程终止
     */
    @ApiOperation(value = "修改签字注师流程终止")
    @PostMapping("/returnRequest")
    public ResponseEntity returnRequest(@RequestBody CwProjectReport report) throws Exception{
        projectReportService.returnRequest(report.getId());
        return ResponseEntity.ok("操作完成");
    }


    /**
     * 批量导出已签章文件
     * @param ids
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportAllSignatureFile")
    public void exportAllSignatureFile(@RequestParam("ids") String ids, HttpServletRequest request, HttpServletResponse response) {
        //将字符串转换成list
        List<String> idList = Arrays.asList(ids.split(","));
        List<ProjectReportWorkAttachmentDTO> listAll = Lists.newArrayList();
        for (String id : idList) {
            List<ProjectReportWorkAttachmentDTO> signatureFileInfoList = projectReportService.getSignatureFileInfoList(id);
            listAll.addAll(signatureFileInfoList);
        }
        String filePathUrl = projectReportService.getSignatureFileZipUrl(listAll);
        String downUrl = filePathUrl + ".zip";

        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        byte[] bytes = new byte[1024];
        File file = new File(downUrl);
        String fileName = file.getName();
        // 获取输出流
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 以流的形式返回文件
            response.setContentType("application/octet-stream;charset=utf-8");
            inputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = response.getOutputStream();
            int i = bufferedInputStream.read(bytes);
            while (i != -1) {
                outputStream.write(bytes, 0, i);
                i = bufferedInputStream.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }

                //根据路径创建文件对象
                File downFile = new File(filePathUrl);
                deleteFile(downFile);

                //根据路径创建文件对象
                File downFileZip = new File(downUrl);
                //路径是个文件且不为空时删除文件
                if(downFileZip.isFile()&&downFileZip.exists()){
                    downFileZip.delete();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void deleteFile(File folder) {
        if(folder.isDirectory()) {
            File[] files = folder.listFiles();
            if(files != null) { // 如果文件夹为空，files可能为null
                for(File file : files) {
                    deleteFile(file); // 递归删除子文件夹和文件
                }
            }
        }
        folder.delete(); // 删除空文件夹或者文件
    }

    /**
     * 保存撤回签章流程
     * @param reportData
     * @return
     */
    @ApiLog(value = "保存撤回签章流程", type = LogTypeEnum.SAVE)
    //@PreAuthorize("hasAnyAuthority('cwProjectReport:add','cwProjectReport:edit')")
    @PostMapping("saveRevocation")
    public ResponseEntity saveRevocation(@Valid @RequestBody CwProjectReportData reportData) throws Exception {
        String id = projectReportService.saveRevocation(reportData);
        return ResponseUtil.newInstance().add("businessTable", "cw_revocation_signature").add("businessId", id).ok ("操作成功");
    }

    /**
     * 撤回签章 根据id修改状态值status
     * @param data
     * @return
     */
    @ApiOperation(value = "撤回签章 根据id修改状态值status")
    @PostMapping(value = "/updateStatusByIdRe")
    public ResponseEntity<String> updateStatusByIdRe(@RequestBody CwProjectReportData data) {
        String s = projectReportService.updateStatusByIdRe(data);
        return ResponseEntity.ok(s);
    }

    /**
     * 查询撤回签章数据
     * @param id
     * @return
     */
    @ApiLog("查询撤回签章数据")
    // @PreAuthorize ("hasAnyAuthority('cwProjectReport:view','cwProjectReport:add','cwProjectReport:edit')")
    @GetMapping("queryByReId")
    public ResponseEntity queryByReId(@RequestParam("id") String id) {
        CwProjectReportData projectReportData = projectReportService.queryByReId ( id );
        return ResponseEntity.ok (projectReportData);
    }

    /**
     * 查询项目下的报告是否已完成关联
     * @param id
     * @return
     */
    @ApiLog("查询项目下的报告是否已完成关联")
    @GetMapping("getCompleteReport")
    public boolean getCompleteReport(@RequestParam("id") String id) {
        boolean data = projectReportService.getCompleteReport ( id );
        return data;
    }

    /**
     * 根据发票编号查询报告
     * @param id
     * @return
     */
    @ApiLog("根据发票编号查询报告")
    @GetMapping("getByInvoiceNumber")
    public boolean getByInvoiceNumber(@RequestParam("invoiceNumber") String invoiceNumber, @RequestParam("id") String id) {
        boolean data = projectReportService.getByInvoiceNumber ( invoiceNumber,id );
        return data;
    }


    /**
     * 报告号替换
     * @param file
     * @param year
     * @return
     */
    @ApiLog("报告号替换")
    @PostMapping("numberReplace")
    public void numberReplace(@RequestParam("file") MultipartFile file,@RequestParam("year") String year, HttpServletRequest request,HttpServletResponse response) throws IOException {
        ArrayList<NumberReplaceDTO> replaceDTOArrayList = new ArrayList<>();

        List<NumberReplaceDTO> listA = new ArrayList<>();
        //获取sheet
        listA = EasyPoiUtil.importExcel(file, 0, 1, NumberReplaceDTO.class);
        //去除excel中的空行
        listA = getExcelList(listA);
        //对报告号进行替换
        cwProjectReportNumberApplyService.replaceNumber(listA,replaceDTOArrayList,year);
        if (CollectionUtil.isNotEmpty(replaceDTOArrayList)){
            //对文件再次进行导出
            String fileName = file.getOriginalFilename ();
            Workbook workbook = WorkbookFactory.create(file.getInputStream()); // 自动识别文件格式

            // 获取第一个 sheet 的名称
            Sheet sheet = workbook.getSheetAt(0);  // 获取第一个 sheet
            String sheetName = sheet.getSheetName();  // 获取 sheet 的名称

            EasyPoiUtil.exportExcel ( replaceDTOArrayList, "报告信息",  sheetName, NumberReplaceDTO.class, fileName, response );

        }
    }


    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<NumberReplaceDTO> getExcelList(List<NumberReplaceDTO> list){

        ArrayList<NumberReplaceDTO> numberReplaceDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                numberReplaceDTOS.add(item);
            }
        });

        return numberReplaceDTOS;
    }

    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    /**
     * 处理报告号模板下载（调整为指定年度的报告号）
     * @return
     */
    @RequestMapping(value = "importDetail/template")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/dot/报告号调整模板.xlsx");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("finance_invoice_detail_template.xlsx", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询未归档的财务报告信息
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询未归档的财务报告信息")
    @PreAuthorize("hasAuthority('cwProjectReport:list')")
    @GetMapping("findNotCompletedList")
    public ResponseEntity<IPage<CwProjectReportData>> findNotCompletedList(CwProjectReportData projectReportData, Page<CwProjectReportData> page) throws Exception {
        IPage<CwProjectReportData> result = new Page<CwProjectReportData>();
        result = projectReportService.findNotCompletedList (page,projectReportData);
        result.getRecords().stream().forEach(i -> {

            //当项目经理是跨租户的人员时，则特殊处理
            if (StringUtils.isBlank(i.getProjectMasterName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId());
                    if(null != byId)
                        i.setProjectMasterName(byId.getName());
                }
            }
            if (StringUtils.isBlank(i.getRealHeaderName())){
                //根据项目经理id去人员表重查数据
                if (StringUtils.isNotBlank(i.getProjectMasterId2())){
                    UserDTO byId = SpringUtil.getBean(IUserApi.class).getById(i.getProjectMasterId2());
                    if(null != byId)
                        i.setRealHeaderName(byId.getName());
                }

            }

            // 复核
            if (StringUtils.isNotBlank(i.getRevTaskId()) && StringUtils.isNotBlank(i.getReviewStatus())) {
                if ("2".equals(i.getReviewStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsRev(flowTaskService.getTaskAuditUsers(i.getRevTaskId()));  // 获取数据审核人
                }
            }
            // 签章
            if (StringUtils.isNotBlank(i.getSignatureType())) {
                // 电子章
                if ("1".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId1()) && StringUtils.isNotBlank(i.getStatus1())) {
                        if ("2".equals(i.getStatus1())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign1(flowTaskService.getTaskAuditUsers(i.getSignTaskId1()));  // 获取数据审核人
                        }
                    }
                }
                // 公章+执业章
                if ("2".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId2()) && StringUtils.isNotBlank(i.getStatus2())) {
                        if ("2".equals(i.getStatus2())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign2(flowTaskService.getTaskAuditUsers(i.getSignTaskId2()));  // 获取数据审核人
                        }
                    }
                }
                // 实体章
                if ("3".equals(i.getSignatureType())) {
                    if (StringUtils.isNotBlank(i.getSignTaskId3()) && StringUtils.isNotBlank(i.getStatus3())) {
                        if ("2".equals(i.getStatus3())) { // “审核中”的数据要获取数据审核人
                            i.setAuditUserIdsSign3(flowTaskService.getTaskAuditUsers(i.getSignTaskId3()));  // 获取数据审核人
                        }
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }

}
