WebReconciliationController.java 11.9 KB
package com.lhcredit.project.webbusiness.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.lhcredit.common.utils.StringUtils;
import com.lhcredit.framework.web.controller.BaseController;
import com.lhcredit.framework.web.domain.AjaxResult;
import com.lhcredit.framework.web.page.TableDataInfo;
import com.lhcredit.project.business.apiFinance.domain.ApiFinance;
import com.lhcredit.project.business.apiFinance.service.IApiFinanceService;
import com.lhcredit.project.business.bCreditReport.domain.BCreditReport;
import com.lhcredit.project.business.bCreditReport.mapper.BCreditReportMapper;
import com.lhcredit.project.business.bCreditReport.service.IBCreditReportService;
import com.lhcredit.project.business.frontDept.domain.FrontDept;
import com.lhcredit.project.business.frontDept.service.IFrontDeptService;
import com.lhcredit.project.business.frontUser.domain.FrontUser;
import com.lhcredit.project.business.frontUser.service.IFrontUserService;
import com.lhcredit.project.business.templateConfiguration.domain.TemplateConfiguration;
import com.lhcredit.project.business.templateConfiguration.service.ITemplateConfigurationService;
import com.lhcredit.project.business.templateConfigurationParameters.domain.TemplateConfigurationParameters;
import com.lhcredit.project.business.templateConfigurationParameters.service.ITemplateConfigurationParametersService;
import com.lhcredit.project.system.dict.domain.DictData;
import com.lhcredit.project.system.dict.service.IDictDataService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "对账信息")
@Controller
@RequestMapping("/api-V2.0/reconciliation")
@RequiredArgsConstructor
public class WebReconciliationController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WebReconciliationController.class);
    @Autowired
    private IBCreditReportService bCreditReportService;

    @Autowired
    private IFrontDeptService frontDeptService;
    
    @Autowired
    private ITemplateConfigurationParametersService templateConfigurationParametersService;

    @Autowired
    private IFrontUserService frontUserService;

    @Autowired
    private IDictDataService dictDataService;

    @Autowired
    private IApiFinanceService apiFinanceService;



    @PostMapping("/getReconciliationList")
    @ResponseBody
    public TableDataInfo getReconciliationList(@RequestBody BCreditReport bCreditReport) {

        startPage(bCreditReport.getPageNum(),bCreditReport.getPageSize());
        bCreditReport.setSubmitBegin(bCreditReport.getVerifyStartDate());
        bCreditReport.setSubmitEnd(bCreditReport.getVerifyEndDate());
        List<BCreditReport> bCreditReports = bCreditReportService.getBcreditReportList1(bCreditReport);
        return getDataTable(bCreditReports);
    }

    @GetMapping("/condition")
    @ResponseBody
    public AjaxResult condition(String contractId) {
        if (contractId == null){
            return AjaxResult.error("合同不能为空");
        }
        //获取部门信息
        FrontDept frontDept = new  FrontDept();
        frontDept.setContractNum(Long.valueOf(contractId));
        List<FrontDept> frontDepts = frontDeptService.selectFrontDeptList(frontDept);
        if (frontDepts.isEmpty()){
            return AjaxResult.error("该合同未绑定部门");
        }

        Long orgId = frontDepts.stream()
                .filter(front -> front != null && front.getParentId() == 0)
                .map(FrontDept::getId)
                .findFirst()
                .orElse(null);
        TemplateConfigurationParameters templateConfigurationParameters = new TemplateConfigurationParameters();
        templateConfigurationParameters.setOrgId(orgId);
        templateConfigurationParameters.setClientType(String.valueOf(0));
        List<TemplateConfigurationParameters> templateConfigurationParametersList = templateConfigurationParametersService.selectTemplateConfigurationParametersList(templateConfigurationParameters);

        //获取用户信息
        List<FrontUser> frontUsers = new ArrayList<>();
        FrontUser user = new FrontUser();
        frontDepts.forEach(item -> {
            user.setOrgId(item.getId());
            List<FrontUser> frontUser = frontUserService.selectFrontUserList(user);
            frontUsers.addAll(frontUser);
        });
        List<DictData> reportProgressDicts = dictDataService.selectDictDataByType("report_progress");

        JSONObject resp = new JSONObject();

        resp.put("templateConfigurationParametersList",templateConfigurationParametersList);
        resp.put("frontUsers",frontUsers);
        resp.put("frontDepts" ,frontDepts);
        resp.put("reportProgressDicts",reportProgressDicts);

        return AjaxResult.success(resp);
    }

    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestBody BCreditReport bCreditReport, HttpServletResponse response) throws IOException {
        bCreditReport.setSubmitBegin(bCreditReport.getVerifyStartDate());
        bCreditReport.setSubmitEnd(bCreditReport.getVerifyEndDate());
        List<BCreditReport> list = bCreditReportService.getBcreditReportList(bCreditReport);
        /*List<JSONObject> mvs = list.stream().map(item -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", item.getId());
            jsonObject.put("客户名称", item.getEnterpriseName());
            jsonObject.put("委托客户名称", item.getOrgName());
            jsonObject.put("委托类型", item.getReportTypeStr());
            jsonObject.put("报告翻译语种", item.getTranslateTypeStr());
            jsonObject.put("项目金额(元)", item.getProjectPrice());
            jsonObject.put("当前状态", item.getReportTypeStr());
            jsonObject.put("下单日期", item.getCreateTime());
            jsonObject.put("报告交付时间", item.getSubmitDate());
            // 提取字段并做空指针检查
            Date submitDate = item.getSubmitDate();
            Date deliveryTime = item.getDeliveryTime();

            jsonObject.put("是否对账", "Y".equals(item.getReconciliation()) ? "是" : "否");
            jsonObject.put("是否按时交付", deliveryTime != null && submitDate != null && !submitDate.after(deliveryTime) ? "是" : "否");
            return jsonObject; // ⚠️ 注意:必须返回构建好的 jsonObject
        }).collect(Collectors.toList());*/

        // 设置响应头
        //configureResponseHeader(response, "对账数据");

        // 导出数据到Excel
       // exportToExcel(mvs, response.getOutputStream());

    return AjaxResult.success(list);
    }

    @PostMapping("/getFinance")
    @ResponseBody
    public TableDataInfo getFinance(@RequestBody ApiFinance apiFinance) {
        startPage(apiFinance.getPageNum(),apiFinance.getPageSize());
       List<ApiFinance> apiFinances =  apiFinanceService.getAllByContractId(apiFinance);
        apiFinances.forEach(item -> {
            if (item.getUId() != null) {
                FrontUser user = frontUserService.selectFrontUserById(Long.valueOf(item.getUId()));
                item.setUserName(user.getUserName());
            }
            if (item.getOrgId() != null) {
                FrontDept frontDept = frontDeptService.selectFrontDeptById(Long.valueOf(item.getOrgId()));
                item.setOrgName(frontDept.getDeptName());
                item.setOrgParentName(getTopLevelDeptName(frontDept.getId()));
            }
        });
        return getDataTable(apiFinances);
    }

    @PostMapping("/financeExport")
    @ResponseBody
    private AjaxResult financeExport(HttpServletResponse response,@RequestBody ApiFinance apiFinance) throws IOException {
        List<ApiFinance> apiFinances =  apiFinanceService.getAllByContractId(apiFinance);
        apiFinances.forEach(item -> {
            if (item.getUId() != null) {
                FrontUser user = frontUserService.selectFrontUserById(Long.valueOf(item.getUId()));
                item.setUserName(user.getUserName());
            }
            if (item.getOrgId() != null) {
                FrontDept frontDept = frontDeptService.selectFrontDeptById(Long.valueOf(item.getOrgId()));
                item.setOrgName(frontDept.getDeptName());
                item.setOrgParentName(getTopLevelDeptName(frontDept.getId()));
            }
        });
        /*List<JSONObject> mvs = apiFinances.stream().map(item -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", item.getId());
            jsonObject.put("用户名称", item.getUserName());
            jsonObject.put("部门名称", item.getOrgName());
            jsonObject.put("公司名称", item.getOrgParentName());
            jsonObject.put("纳税人名称", item.getBaseName());
            jsonObject.put("申请时间", item.getApplicationTime());
            jsonObject.put("完成时间", item.getCompletionTime());
            if (item.getProgress() == 0) {
                jsonObject.put("进度", "生成中");
            } else if (item.getProgress() == 1) {
                jsonObject.put("进度", "已完成");
            } else if (item.getProgress() == 2) {
                jsonObject.put("进度", "生成失败");
            }
            jsonObject.put("类型", item.getType().equals("ZX301") ? "发票指标" : "税务指标");
            jsonObject.put("是否对账", "Y".equals(item.getReconciliation()) ? "是" : "否");
            return jsonObject;
        }).collect(Collectors.toList());
        // 设置响应头
        configureResponseHeader(response, "税务数据");

        // 导出数据到Excel
        exportToExcel(mvs, response.getOutputStream());*/
        return AjaxResult.success(apiFinances);
    }

    private String getTopLevelDeptName(Long deptId) {
        if (deptId == null) return null;

        FrontDept currentDept = frontDeptService.selectFrontDeptById(deptId);
        while (currentDept != null && currentDept.getParentId() != 0) {
            currentDept = frontDeptService.selectFrontDeptById(currentDept.getParentId());
        }
        return currentDept != null ? currentDept.getDeptName() : null;
    }


    private void configureResponseHeader(HttpServletResponse response, String fileName) {
        try {
            if (StrUtil.isBlank(fileName)) {
                fileName = "企业数据导出";
            }
            // 确保文件名不包含非法字符
            fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
            // 进行URL编码,防止中文乱码
            String encodedFileName = URLEncoder.encode(fileName + ".xlsx", String.valueOf(StandardCharsets.UTF_8));

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
        } catch (Exception e) {
            log.error("设置响应头失败", e);
        }
    }

    private void exportToExcel(List<JSONObject> list, ServletOutputStream outputStream) {
    // 创建ExcelWriter
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            // 写入数据到Sheet
            writer.write(list, true);

            // 输出到流并关闭writer
            writer.flush(outputStream, true);
        }
    }


}