WebBCreditReportController.java 55.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
package com.lhcredit.project.webbusiness.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.google.common.util.concurrent.RateLimiter;
import com.google.common.util.concurrent.Runnables;
import com.lhcredit.common.utils.*;
import com.lhcredit.common.utils.file.FileUtils;
import com.lhcredit.common.utils.mail.SendMailUtil;
import com.lhcredit.common.utils.security.ShiroUtils;
import com.lhcredit.framework.aspectj.lang.annotation.CheckToken;
import com.lhcredit.framework.aspectj.lang.annotation.Log;
import com.lhcredit.framework.aspectj.lang.annotation.OrderCountCheck;
import com.lhcredit.framework.aspectj.lang.annotation.ReportCount;
import com.lhcredit.framework.aspectj.lang.enums.BusinessType;
import com.lhcredit.framework.aspectj.lang.enums.OperatorType;
import com.lhcredit.framework.web.controller.BaseController;
import com.lhcredit.framework.web.domain.AjaxResult;
import com.lhcredit.framework.web.page.TableDataInfo;
import com.lhcredit.framework.web.service.FastDFSClient;
import com.lhcredit.project.business.BasicInformation.service.BasicInformationService;
import com.lhcredit.project.business.HolidayWorkday.domain.HolidayWorkday;
import com.lhcredit.project.business.HolidayWorkday.mapper.HolidayWorkdayMapper;
import com.lhcredit.project.business.TianYC.entity.param.RequestParams;
import com.lhcredit.project.business.bCreditReport.domain.BCreditReport;
import com.lhcredit.project.business.bCreditReport.domain.ReportStatus;
import com.lhcredit.project.business.bCreditReport.mapper.BCreditReportMapper;
import com.lhcredit.project.business.bCreditReport.service.BCreditReportServiceImpl;
import com.lhcredit.project.business.bCreditReport.service.IBCreditReportService;
import com.lhcredit.project.business.bReportTable.domain.BReportTable;
import com.lhcredit.project.business.bReportTable.service.IBReportTableService;
import com.lhcredit.project.business.contractReportBusinessType.domain.ContractReportBusinessType;
import com.lhcredit.project.business.contractReportBusinessType.mapper.ContractReportBusinessTypeMapper;
import com.lhcredit.project.business.frontDept.domain.FrontDept;
import com.lhcredit.project.business.frontDept.mapper.FrontDeptMapper;
import com.lhcredit.project.business.frontDept.service.IFrontDeptService;
import com.lhcredit.project.business.frontUser.domain.FrontUser;
import com.lhcredit.project.business.frontUser.domain.FrontUserMon;
import com.lhcredit.project.business.frontUser.mapper.FrontUserMapper;
import com.lhcredit.project.business.frontUser.service.FrontUserServiceImpl;
import com.lhcredit.project.business.overseaCompanyInfoVerify.domain.OverseaCompanyInfoVerify;
import com.lhcredit.project.business.reportDirectoryData.service.QxbHttpUtils;
import com.lhcredit.project.business.reportFinanceData.domain.ReportFinanceData;
import com.lhcredit.project.business.reportFinanceData.service.IReportFinanceDataService;
import com.lhcredit.project.business.reportMake.ReportMakeService;

import com.lhcredit.project.business.templateConfigurationParameters.domain.TemplateConfigurationParameters;
import com.lhcredit.project.business.templateConfigurationParameters.service.ITemplateConfigurationParametersService;
import com.lhcredit.project.business.userDownloadCountLog.domain.UserDownloadCountLog;
import com.lhcredit.project.business.userDownloadCountLog.service.UserDownloadCountLogServiceImpl;
import com.lhcredit.project.business.worldboxlog.domain.Worldboxlog;
import com.lhcredit.project.system.dict.domain.DictData;
import com.lhcredit.project.system.dict.service.DictDataServiceImpl;
import com.lhcredit.project.system.dict.service.IDictDataService;
import com.lhcredit.project.system.user.domain.User;
import com.lhcredit.project.webbusiness.domain.ShangTouModel;
import com.lhcredit.project.worldbox.WorldBoxAPI;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.lhcredit.common.utils.HolidayOrWork.getWorkDay;


/**
 * 信用报告信息对外接口
 *
 * @author lhcredit
 * @date 2024-06-03
 */
@RestController
@RequestMapping("/web/report")
public class WebBCreditReportController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(WebBCreditReportController.class);
    @Autowired
    private IBCreditReportService bCreditReportService;
    @Autowired
    private IDictDataService iDictDataService;
    @Autowired
    private IBReportTableService bReportTableService;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private ReportMakeService reportMakeService;

    @Autowired
    private BCreditReportMapper bCreditReportMapper;

    @Autowired
    private DictDataServiceImpl dictDataService;

    @Autowired
    private ContractReportBusinessTypeMapper contractReportBusinessTypeMapper;

    @Autowired
    private IFrontDeptService frontDeptService;

    @Autowired
    private FrontUserMapper frontUserMapper;

    @Autowired
    private ITemplateConfigurationParametersService templateConfigurationParametersService;

    @Autowired
    private HolidayWorkdayMapper holidayWorkdayMapper;

    @Autowired
    private UserDownloadCountLogServiceImpl userDownloadCountLogService;
    @Autowired
    private BasicInformationService basicInformationService;

    @Value("${fdfs.web-server-url}")
    private String fdfsUrl;


    private final RateLimiter rateLimiter = RateLimiter.create(1.0);

    @RequestMapping("/web/update")
    public String sssss(MultipartFile file,String path) throws Exception{
        FileInputStream fileInputStream=new FileInputStream(new File(path));
        String s1 = OssUtils.standardAnnax(file).getUrl();
        return JSONObject.parseObject(s1).getString("url");

    }


    @ReportCount(reportType = "sFAssist")
    @RequestMapping("/getSFExcel")
    public void getSFExcelStream(String ename,HttpServletRequest request,HttpServletResponse response) throws IOException {

        try (InputStream sfExcelStream = ReportMakeService.getSFExcelStream(ename)) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, ename + "司法数据.xlsx"));

            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = sfExcelStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

            //记录日志
            setUserDownloadLog(ename);

        } catch (IOException e) {
            logger.error("文件下载失败: {}", e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
        }
//        return "";
    }

    /**
     * 插入 日志表
     * @param ename
     */
    public void setUserDownloadLog(String ename){
        FrontUserMon userInfo = getUserInfo();
        UserDownloadCountLog sf = UserDownloadCountLog.builder()
                .userId(userInfo.getId())
                .userName(userInfo.getUserName())
                .enterpriseName(ename)
//                .userId(226l)
//                .userName("新宇1")
//                .enterpriseName("济南比亚迪汽车有限公司")
                .type("SF")
                .uri("/web/report/getSFExcel")
                .build();
        sf.setCreateTime(new Date());
        userDownloadCountLogService.insertUserDownloadCountLog(sf);
    }


    @ApiOperation(value = "搜索多选框")
    @GetMapping("/reportTypeList")
    public AjaxResult reportTypeList() {
        //报告类型多选框
        BReportTable table = new BReportTable();
        table.setIsDel(1);
        List<BReportTable> allReportTable = bReportTableService.selectBReportTableList(table);
        //报告进度多选框
        List<DictData> reportProgress = iDictDataService.selectDictDataByType("report_progress");
        reportProgress=reportProgress.stream().sorted(Comparator.comparing(DictData::getDictSort)).collect(Collectors.toList());
        //委托类型多选框
        List<DictData> entrustType = iDictDataService.selectDictDataByType("entrust_type");
        JSONObject jsonObject=new JSONObject();
        for(int i=0;i<reportProgress.size();i++){
            DictData dd=reportProgress.get(i);
            if(dd.getDictValue().equals("2")) reportProgress.remove(i);
            if(dd.getDictValue().equals("4")) reportProgress.remove(i);
            if(dd.getDictValue().equals("8")) reportProgress.remove(i);
        }
        jsonObject.put("allReportTable", allReportTable);
        jsonObject.put("reportProgress", reportProgress);
        jsonObject.put("entrustType", entrustType);
        return toAjax(jsonObject);
    }
    /**
     * 查询信用报告列表接口
     */
    @ApiOperation("查询信用报告列表")
    @Log(title = "信用报告", businessType = BusinessType.LIST, operatorType = OperatorType.WEB)
    @PostMapping("/accessQuery")
    @CheckToken
    public AjaxResult list(@RequestBody BCreditReport bCreditReport) {
        FrontUserMon userInfo = super.getUserInfo();
        bCreditReport.setOrgId(userInfo.getOrgId());
        if(StringUtils.isNotEmpty(bCreditReport.getReportProgress())){
            List<String> stringList = Arrays.asList(bCreditReport.getReportProgress().split(","));
            bCreditReport.setReportProgressList(stringList);
        }
        if(StringUtils.isNotEmpty(bCreditReport.getEntrustType())){
            List<String> stringList = Arrays.asList(bCreditReport.getEntrustType().split(","));
            bCreditReport.setEntrustTypeList(stringList);
        }
        startPage(bCreditReport.getPageNum(), bCreditReport.getPageSize());
        List<BCreditReport> list = bCreditReportService.findAllByCondition(bCreditReport);
        return toAjax(list);
    }



    /**
     * 查询信用报告列表接口
     */
    @ApiOperation("查询信用报告列表")
    @Log(title = "信用报告", businessType = BusinessType.LIST, operatorType = OperatorType.WEB)
    @PostMapping("/accessQueryVx")
    @CheckToken
    public AjaxResult listVx(@RequestBody BCreditReport bCreditReport) {
        FrontUserMon userInfo = super.getUserInfo();
        bCreditReport.setUserId(userInfo.getId());
        if(StringUtils.isNotEmpty(bCreditReport.getReportProgress())){
            List<String> stringList = Arrays.asList(bCreditReport.getReportProgress().split(","));
            bCreditReport.setReportProgressList(stringList);
        }
        if(StringUtils.isNotEmpty(bCreditReport.getEntrustType())){
            List<String> stringList = Arrays.asList(bCreditReport.getEntrustType().split(","));
            bCreditReport.setEntrustTypeList(stringList);
        }
        startPage(bCreditReport.getPageNum(), bCreditReport.getPageSize());
        List<BCreditReport> list = bCreditReportService.findAllByConditionVx(bCreditReport);
        return toAjax(list);
    }

    @ApiOperation("查询待审核信用报告列表")
    @Log(title = "信用报告", businessType = BusinessType.LIST, operatorType = OperatorType.WEB)
    @PostMapping("/findAllAudit")
    @CheckToken
    public AjaxResult findAllAudit(@RequestBody BCreditReport bCreditReport) {
        FrontUserMon userInfo = super.getUserInfo();
        bCreditReport.setOrgId(userInfo.getOrgId());
        startPage();
        if(StringUtils.isNotEmpty(bCreditReport.getEntrustType())){
            List<String> stringList = Arrays.asList(bCreditReport.getEntrustType().split(","));
            bCreditReport.setEntrustTypeList(stringList);
        }
        List<BCreditReport> list = bCreditReportService.findAllAudit(bCreditReport);
        return toAjax(list);
    }



    /**
     * 新增保存信用报告接口
     */
//    @ReportCount(reportType = "creditReport")
    @ApiOperation("新增信用报告")
    @ApiImplicitParam(name = "bCreditReport", value = "信用报告", dataType = "BCreditReport")
    @Log(title = "信用报告", businessType = BusinessType.INSERT, operatorType = OperatorType.WEB)
    @PostMapping("/add")
    @CheckToken
    @OrderCountCheck(reportType = "frontBatchOrder")
    public AjaxResult addSave(@RequestBody  BCreditReport bCreditReport) {

        if (bCreditReport == null && CollectionUtils.isEmpty(bCreditReport.getEnterpriseList()))
            return AjaxResult.error("参数有误");


        FrontUserMon userInfo = getUserInfo();
        ArrayList<BCreditReport> bCreditReports = new ArrayList<>();
        List<BCreditReport.Enterprise> enterpriseList = bCreditReport.getEnterpriseList();
        //处理 参数属性
        enterpriseList.forEach(ent ->{
            if (ent.getEnterpriseName() !=  null) {
                String[] split = ent.getEnterpriseName().split(",");
                for (String s : split) {
                    BCreditReport report = new BCreditReport();
                    BeanUtils.copyProperties(bCreditReport,report);
                    report.setEnterpriseName(s);
                    bCreditReports.add(report);
                }
            }
        });
        return  bCreditReportService.add(bCreditReports,userInfo,false,
                StringUtils.isEmpty(bCreditReport.getSource())?"2":bCreditReport.getSource());
    }

    /*public AjaxResult addSave(@RequestBody  JSONArray jsonArray) {
        FrontUserMon userInfo = getUserInfo();
        if(jsonArray!=null&&jsonArray.size()>0){
            return bCreditReportService.add(jsonArray,userInfo,false,"2");
        }
        return error();
    }*/

    /*public static void main(String[] args) {
        String aa = "[{\"fileName\":\"北京百度网讯科技有限公司_系统_20250402155107\",\"fileExtension\":\"doc\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943497127620608.doc\"},{\"fileName\":\"北京百度网讯科技有限公司_系统_20250402155107\",\"fileExtension\":\"doc\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943497127620608.doc\"},{\"fileName\":\"北京百度网讯科技有限公司_系统_20250402155107\",\"fileExtension\":\"pdf\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943498788564992.pdf\"},{\"fileName\":\"北京百度网讯科技有限公司_系统_20250402155238\",\"fileExtension\":\"xml\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943498843090944.xml\"},{\"fileName\":\"北京百度网讯科技有限公司_系统_20250402155240\",\"fileExtension\":\"txt\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943498868256768.txt\"},{\"fileName\":\"深圳嘉立创科技集团股份有限公司\",\"fileExtension\":\"xlsx\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943498901811200.xlsx\"},{\"fileName\":\"司法数据\",\"fileExtension\":\"xlsx\",\"fileAttachments\":\"http://filestorage.lhdna.com/creditManager/1913943498901811200.xlsx\"}]";
        JSONObject object = new JSONObject();
        object.put("url",aa);

        try {
            reportConfirm(object.toJSONString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/
    @ApiOperation(value = "确认订单报告信息", notes = "确认订单报告信息")
    @RequestMapping(value = "/reportConfirm")
//    public  AjaxResult reportConfirm(@RequestBody String confirmJson) throws Exception {
    public  AjaxResult reportConfirm(@RequestParam("confirmJson") String confirmJson) throws Exception {
        if(StringUtils.isNotEmpty(confirmJson)){
            BCreditReport b =new BCreditReport();
            JSONObject jsonObject = JSONObject.parseObject(confirmJson);
            JSONArray url = jsonObject.getJSONArray("url");
            JSONArray docArrObj = new JSONArray();
            for (int i = 0; i < url.size(); i++) {
                JSONObject jsonObject1 = url.getJSONObject(i);
                URL urls = new URL(jsonObject1.getString("fileAttachments"));
                InputStream in = urls.openStream();
                String s = FileSysUtils.upLoadFile(in, jsonObject1.getString("fileName")+"."+jsonObject1.getString("fileExtension"), FileSysUtils.DirectoryType.creditManager.directory);
                String fullPath =new FileSysUtils().getPath(s);
                fullPath=FileSysUtils.getFullPath(fullPath);
                jsonObject1.put("fileAttachments",fullPath);
                url.set(i,jsonObject1);
                //设置 报告订单表的 各种报告下载地址
                if (jsonObject1.getString("fileExtension").equals("doc") || jsonObject1.getString("fileExtension").equals("docx")){
                    docArrObj.add(jsonObject1);
                }else {
                    setUrlInfo(jsonObject1,b);
                }
            }
            //设置doc 下载地址
            b.setFinalUrl(docArrObj.toJSONString());
            b.setId(jsonObject.getString("id"));
            b.setEnterpriseName(jsonObject.getString("enterprise_name"));
            b.setUrl(url.toJSONString());
            b.setReportProgress("5");
            b.setUpdateTime(new Date());
            bCreditReportService.updateBCreditReport(b);

            /**
             * 发送邮件
             */
            //查询用户得订单信息
            BCreditReport bCreditReport = bCreditReportService.selectBCreditReportById(b.getId());
            //查询用户信息
            FrontUser user = frontUserMapper.getFrontUserById(bCreditReport.getUserId());
            bCreditReportService.sendAttachEmail(user,bCreditReport);

        }
        return AjaxResult.success("确认成功");
    }


    /**
     * 解析 url中的返回的 报告路径,设置到 报告订单表的对应字段上
     * pdf_url 取 "fileExtension": "pdf",
     * final_url 取 "fileExtension": "doc",
     * annex中的sfExcel  取 "fileExtension": "xlsx",  annex中的其他对象 不设置
     * @param obj
     * @param bCreditReport
     */
    public  void  setUrlInfo(JSONObject obj, BCreditReport bCreditReport){
        //地址
        String fileAttachments = obj.getString("fileAttachments");
        //w文件名
        String fileName = obj.getString("fileName");
        //扩展名
        String fileExtension = obj.getString("fileExtension");
        JSONArray bArr = new JSONArray();
        JSONObject bReportObj = new JSONObject();
        bReportObj.put("fileName",fileName);
        bReportObj.put("fileExtension",fileExtension);
        bReportObj.put("fileAttachments",fileAttachments);
        bArr.add(bReportObj);
        JSONObject annexObj = new JSONObject();
        switch (fileExtension){
            //pdf
            case "pdf" :
                bCreditReport.setPdfUrl(bArr.toJSONString());
                break;
            //excel
            case "xlsx" :
                if ("司法数据".equals(fileName)){
                    annexObj.put("sfExcel",bReportObj);
                    bCreditReport.setAnnex(annexObj.toJSONString());
                }
                break;
            case "xls" :
                if ("司法数据".equals(fileName)){
                    annexObj.put("sfExcel",bReportObj);
                    bCreditReport.setAnnex(annexObj.toJSONString());
                }
                break;
            default:
                break;
        }

    }


    /**
     *
     * 确认撤销订单
     * @param orderNum
     * @return
     */
    @ApiOperation(value = "撤销订单")
    @RequestMapping(value = "/cancel")
    public AjaxResult cancel(String orderNum){
     return bCreditReportService.cancel(orderNum);
    }

    @CheckToken
    @ApiOperation(value = "下载报告")
    @GetMapping("/reportDownload")
    public void reportDownload(String reportId, String ename, HttpServletResponse httpServletResponse) {
        try {
            Map<String, byte[]> files = new HashMap<>();
            BCreditReport bCreditReport = bCreditReportService.selectBCreditReportById(reportId);
            if(bCreditReport!=null){
                //获取用户,并判断用户选择
                long userId=bCreditReport.getUserId();
                String reportType=bCreditReport.getReportType();
                String rt="";
                if(reportType.equals("-11")){//定制报告
                    String templateParamId=bCreditReport.getTemplateParamId();
                    if(StringUtils.isNotEmpty(templateParamId)){
                        rt=bCreditReport.getTemplateParamId().substring(templateParamId.lastIndexOf("-")+1,templateParamId.length());
                    }
                }else {
                    rt=reportType;
                }
                FrontUser user = frontUserMapper.getFrontUserById(userId);
                //判断用户是否选择邮件附件
                String  emailAttachment= user.getEmailAttachment();

                if(StringUtils.isNotEmpty(emailAttachment)){
                    //判断是Y
                    Map<String,byte[]> fileMap=new LinkedHashMap();
                    if(emailAttachment.equals("Y")){
                        //获取用户选中的附件类型
                        String emailAttachmentInfo=user.getEmailAttachmentInfo();
                        JSONArray jsonArray = JSONObject.parseArray(emailAttachmentInfo);
                        for(int i=0;i<jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String type = jsonObject.getString("value");
                            if(rt.equals(type)){
                                String attachmentType = jsonObject.getString("attachmentType");//附件类型
                                String[] file = attachmentType.split(",");
                                for(String value : file){
                                    if(value.equals("1")){//司法
                                       String annex= bCreditReport.getAnnex();
                                       if(StringUtils.isNotEmpty(annex)){
                                           JSONObject annexObj = JSONObject.parseObject(annex);
                                           JSONObject sfExcel=annexObj.getJSONObject("sfExcel");
                                           String sfUrl=sfExcel.getString("fileAttachments");
                                           byte[]  by = fastDFSClient.download2(sfUrl);;
                                           fileMap.put(ename+"司法.xlsx",by);
                                       }
                                    }else if(value.equals("2")){//最终pdf
                                        String pfd= bCreditReport.getPdfUrl();
                                        if(StringUtils.isNotEmpty(pfd)){
                                            JSONArray pdfArr = JSONObject.parseArray(pfd);
                                            JSONObject pdfObj = JSONObject.parseObject(pdfArr.get(0).toString());
                                            String pdfUrl = pdfObj.getString("fileAttachments");
                                            byte[]  by = fastDFSClient.download2(pdfUrl);;
                                            fileMap.put(ename+".pdf",by);
                                        }
                                    }else if(value.equals("3")){
                                        //判断是否是最终doc
                                        String finalDoc= bCreditReport.getFinalUrl();
                                        if(StringUtils.isNotEmpty(finalDoc)){
                                            JSONArray docArr = JSONObject.parseArray(finalDoc);
                                            JSONObject docObj = JSONObject.parseObject(docArr.get(0).toString());
                                            String docUrl = docObj.getString("fileAttachments");
                                            byte[]  by = fastDFSClient.download2(docUrl);;
                                            fileMap.put(ename+".docx",by);
                                        }else {
                                            String firstDoc = bCreditReport.getFirstUrl();
                                            if(StringUtils.isNotEmpty(firstDoc)){
                                                JSONArray docArr = JSONObject.parseArray(firstDoc);
                                                JSONObject docObj = JSONObject.parseObject(docArr.get(0).toString());
                                                String docUrl = docObj.getString("fileAttachments");
                                                byte[]  by = fastDFSClient.download2(docUrl);;
                                                fileMap.put(ename+".docx",by);
                                            }
                                        }
                                    }else if(value.equals("4")){//翻译pdf
                                        String transPfd= bCreditReport.getTransUrl();
                                        if(StringUtils.isNotEmpty(transPfd)){
                                            JSONArray transPfdArr = JSONObject.parseArray(transPfd);
                                            JSONObject transPfdArrObj = JSONObject.parseObject(transPfdArr.get(0).toString());
                                            String transPdfUrl = transPfdArrObj.getString("fileAttachments");
                                            byte[]  by = fastDFSClient.download2(transPdfUrl);;
                                            fileMap.put(ename+"翻译版.pdf",by);
                                        }
                                    }
                                }
                            }
                        }
                        //压缩下载
                        if (fileMap.size() > 0) {
                            downloadBatchByFile(httpServletResponse, fileMap, ename + ".zip");
                        }else {
                            String transPfd= bCreditReport.getTransUrl();
                            String downloadUrl = bCreditReport.getPdfUrl();
                            if(StringUtils.isNotEmpty(transPfd)){
                                JSONArray transPfdArr = JSONObject.parseArray(transPfd);
                                JSONObject transPfdArrObj = JSONObject.parseObject(transPfdArr.get(0).toString());
                                String transPdfUrl = transPfdArrObj.getString("fileAttachments");
                                byte[]  by = fastDFSClient.download2(transPdfUrl);;
                                String fileName = ename + ".pdf";
                                httpServletResponse.setContentType("application/x-msdownload");
                                httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                                ServletOutputStream outputStream = httpServletResponse.getOutputStream();
                                outputStream.write(by);
                                outputStream.close();
                            }else {
                                JSONArray pfdArr = JSONObject.parseArray(downloadUrl);
                                JSONObject pfdArrObj = JSONObject.parseObject(pfdArr.get(0).toString());
                                String pdfUrl = pfdArrObj.getString("fileAttachments");
                                byte[]  by = fastDFSClient.download2(pdfUrl);;
                                String fileName = ename + ".pdf";
                                httpServletResponse.setContentType("application/x-msdownload");
                                httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                                ServletOutputStream outputStream = httpServletResponse.getOutputStream();
                                outputStream.write(by);
                                outputStream.close();
                            }
                        }

                    }else {
                        String transPfd= bCreditReport.getTransUrl();
                        String downloadUrl = bCreditReport.getPdfUrl();
                        if(StringUtils.isNotEmpty(transPfd)){
                            JSONArray transPfdArr = JSONObject.parseArray(transPfd);
                            JSONObject transPfdArrObj = JSONObject.parseObject(transPfdArr.get(0).toString());
                            String transPdfUrl = transPfdArrObj.getString("fileAttachments");
                            byte[]  by = fastDFSClient.download2(transPdfUrl);;
                            String fileName = ename + ".pdf";
                            httpServletResponse.setContentType("application/x-msdownload");
                            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
                            outputStream.write(by);
                            outputStream.close();
                        }else {
                            JSONArray pfdArr = JSONObject.parseArray(downloadUrl);
                            JSONObject pfdArrObj = JSONObject.parseObject(pfdArr.get(0).toString());
                            String pdfUrl = pfdArrObj.getString("fileAttachments");
                            byte[]  by = fastDFSClient.download2(pdfUrl);;
                            String fileName = ename + ".pdf";
                            httpServletResponse.setContentType("application/x-msdownload");
                            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
                            outputStream.write(by);
                            outputStream.close();
                        }
                }


//                    if(StringUtils.isNotEmpty(downloadUrl)){
//                        JSONArray jsonArray = JSONArray.parseArray(downloadUrl);
//                        //判断jsonArray数据是否大于1,大于一条数据  进行压缩下载
//                        if (jsonArray.size() > 1) {
//                            jsonArray.forEach(u -> {
//                                JSONObject url = (JSONObject) u;
//                                //pdf文件下载路径
//                                if (!ObjectUtil.isEmpty(u)) {
//                                    try {
//                                        byte[] by = new byte[0];
//                                        String urls = url.getString("fileAttachments");
//                                        if (!urls.contains("http")&&urls.contains("group")){
//                                            by = fastDFSClient.download(urls);
//                                        }else {
//                                            by = fastDFSClient.download2(urls);
//                                        }
//                                        files.put(url.getString("fileName") + "." + url.getString("fileExtension"), by);
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            });
//                            //压缩下载
//                            downloadBatchByFile(httpServletResponse, files, ename + ".zip");
//                        }else if (jsonArray.size() == 1){//普通下载
//                            //普通下载
//                            JSONObject jsonObject = jsonArray.getJSONObject(0);
//                            byte[] by = new byte[0];
//                            String urls = jsonObject.getString("fileAttachments");
//                            if (!urls.contains("http")&&urls.contains("group")){
//                                by = fastDFSClient.download(urls);
//                            }else {
//                                by = fastDFSClient.download2(urls);
//                            }
//                            String fileName = jsonObject.getString("fileName") + "." + jsonObject.getString("fileExtension");
//
//
//                            httpServletResponse.setContentType("application/x-msdownload");
//                            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//                            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
//                            outputStream.write(by);
//                            outputStream.close();
//                        }
//
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName) {
        try {
            response.setContentType("application/x-msdownload");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, "utf-8"));

            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            for (Map.Entry<String, byte[]> entry : files.entrySet()) {
                String fileName = entry.getKey();            //每个要压缩的文件名
                byte[] file = entry.getValue();            //这个zip文件的字节

                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                zos.putNextEntry(new ZipEntry(fileName));

                int len = 0;
                byte[] buf = new byte[10 * 1024];
                while ((len = bis.read(buf, 0, buf.length)) != -1) {
                    bos.write(buf, 0, len);
                }
                bis.close();
                bos.flush();
            }
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 审核
     * @param bCreditReport
     * @return
     */
    @PostMapping("/audit")
    @CheckToken
    public  AjaxResult audit(@RequestBody BCreditReport bCreditReport){

        if (StringUtils.isEmpty(bCreditReport.getAuditStatus())) {
            return AjaxResult.warn("审核状态不能为空");
        }

        return success(bCreditReportService.doAudit(bCreditReport));
    }
    @Autowired
    private IReportFinanceDataService reportFinanceDataService;
    @RequestMapping(value = "/xcAutoReportCallback",method =RequestMethod.POST)
    public AjaxResult xcAutoReportCallback(@RequestBody String json){
        String id = ServletUtils.getParameter("id");
//        //处理数据 根据id查询信用报告数据
//        BCreditReport bCreditReport = bCreditReportService.selectBCreditReportById(id);
//
//        List<ReportFinanceData> reportFinanceDataArrayList = new ArrayList<>();
//
//
//
//        JSONObject jsonObject = JSONObject.parseObject(json);
//        if (jsonObject.getString("code").equals("2000")){
//            JSONArray jsonArray= jsonObject.getJSONArray("data");
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                String fianceJson = jsonObject1.getString("fianceJson");
//                ReportFinanceData reportFinanceData = JSONObject.parseObject(fianceJson, ReportFinanceData.class);
//                reportFinanceData.setReportTemplate("xc");
//                reportFinanceData.setEname(bCreditReport.getEnterpriseName());
//                reportFinanceData.setLastUpdataTime(new Date());
//                reportFinanceDataArrayList.add(reportFinanceData);
//            }
//            //筛选出月份为12的数据
//            List<ReportFinanceData> financeList = reportFinanceDataArrayList.stream().filter(reportFinanceData -> reportFinanceData.getMonth().equals("12")).collect(Collectors.toList());
//            //刷选出月份不为12的数据
//            List<ReportFinanceData> otherfinanceList = reportFinanceDataArrayList.stream().filter(reportFinanceData -> !reportFinanceData.getMonth().equals("12")).collect(Collectors.toList());
//
//            bAutoReport.setOrgName(bCreditReport.getEnterpriseName());
//            bAutoReport.setCreditReportId(bCreditReport.getId());
//            bAutoReport.setUserId(bCreditReport.getUserId());
//            bAutoReport.setFinanceType("xc");
//            bAutoReport.setFinanceList(financeList);//财务数据
//            bAutoReport.setOtherfinanceList(otherfinanceList);//其他季度财务数据
//            bAutoReport.setApplicationTime(bCreditReport.getCreateTime());
//            bAutoReport.setUserName(bCreditReport.getApplicationName());
//            reportFinanceDataService.saveList(reportFinanceDataArrayList);
//            System.out.println("makeReport  之前============================");
//            new Thread(()->{
//                reportMakeService.makeReport(bAutoReport);
//            }).start();
//
//        } else if (jsonObject.getString("code").equals("5000")) {
//            BCreditReport bCreditReport1 = bCreditReportMapper.selectBCreditReportById(bCreditReport.getId());
//            bCreditReport1.setReportProgress("6");
//            bCreditReportMapper.updateBCreditReport(bCreditReport1);
//        }

        return AjaxResult.success();
    }

    /**
     * 根据合同id 查询订单列表
     * @param bCreditReport
     * @return
     */
    @PostMapping("/getCompanyOrdersByContractId")
    @ResponseBody
    public List<BCreditReport> getCompanyOrdersByContractId(@RequestBody BCreditReport bCreditReport){
        if (bCreditReport.getContractId() == null)
            return Collections.emptyList();
        List<BCreditReport> bCreditReports = bCreditReportService.selectBCreditReportList(bCreditReport);
        //查询字典表
        List<DictData> reportProgressDicts = dictDataService.selectDictDataByType("report_progress");
        Map<String, DictData> dataMap = reportProgressDicts.stream().collect(Collectors.toMap(DictData::getDictValue, Function.identity()));
        //设置 字典值
        for (BCreditReport br : bCreditReports){
            DictData dict = dataMap.get(br.getReportProgress());
            if (dict != null){
                br.setReportProgressStr(dict.getDictLabel());
            }
        }
        return bCreditReports;
    }


    /**
     * 后台代替用户下单
     * @param bCreditReport
     * @return
     */
    @ApiOperation("后台下单信用报告")
    @ApiImplicitParam(name = "bCreditReport", value = "信用报告", dataType = "BCreditReport")
    @Log(title = "信用报告", businessType = BusinessType.INSERT, operatorType = OperatorType.WEB)
    @PostMapping("/backgroundOrder")
    @ResponseBody
    @OrderCountCheck(reportType = "backgroundOrder")
    public AjaxResult backgroundOrder(@RequestBody BCreditReport bCreditReport){

        //设置当前操作人的loginName
        if(rateLimiter.tryAcquire()){
            User sysUser = getSysUser();
            bCreditReport.setCreateBy(sysUser.getLoginName());
            bCreditReport.setCreateTime(bCreditReport.getWebCreateTime());
            //CN : 国内订单.其他  为海外订单
            if (bCreditReport.getCountry().equals("CN")) {
                return bCreditReportService.backgroundOrder(bCreditReport);
            } else {
                return bCreditReportService.overseaBackgroundOrderCommit(bCreditReport);
            }
        }else {
            return error("请求频率太快");
        }

    }


    @RequestMapping(value = "/file")
    public AjaxResult file(BCreditReport bCreditReport) throws IOException {
        //设置当前操作人的loginName
        FrontUserMon loginUser=getUserInfo();
        bCreditReport.setCreateBy(loginUser.getUserName());
        String errName="";
        if(bCreditReport.getFile().isEmpty()){
            return error("请上传文件!");
        }
        String fileName=bCreditReport.getFile().getOriginalFilename();
        long size = bCreditReport.getFile().getSize();
        List<String> nameList = new ArrayList<>();
        List<String> nameNoList = new ArrayList<>();
        if(fileName.contains("xls")||fileName.contains("xlsx")){
            try {
                InputStream in = bCreditReport.getFile().getInputStream();
                ExcelReader reader = ExcelUtil.getReader(in);
                List<Map<String,Object>> readAll = reader.readAll();
                for(int i = 0; i < readAll.size(); i++){
                    Map<String,Object> map=readAll.get(i);
                    String com_name=map.get("企业名称").toString();
                    String name="";
                    RequestParams requestParams = new RequestParams();
                    requestParams.setName(com_name);
                    //根据名称接口查
                    JSONObject jsonObject = basicInformationService.baseinfo3(requestParams);
                    if(jsonObject.getString("code").equals("2000")){
                        JSONObject data=jsonObject.getJSONObject("data");
                        if(data!=null){
                            String name1=data.getString("name");
                            if(StringUtils.isNotEmpty(name1)){
                                name=name1;
                                nameList.add(name);
                            }
                        }
                    }else {
                        nameNoList.add(com_name);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                return error();
            }
        }else {
            return error("请上传xls、xlsx文件!");
        }
        JSONObject result = new JSONObject();
        result.put("nameList",nameList);
        result.put("nameNoList",nameNoList);
        result.put("nameNoListSize",nameNoList.size());
        result.put("nameListSize",nameList.size());
        result.put("size", size);
        return AjaxResult.success(result);
    }


    /**
     * 后台代替用户下单
     * @param bCreditReport
     * @return
     */
    @ApiOperation("后台下单信用报告")
    @ApiImplicitParam(name = "bCreditReport", value = "信用报告", dataType = "BCreditReport")
    @Log(title = "信用报告", businessType = BusinessType.INSERT, operatorType = OperatorType.WEB)
    @PostMapping("/backgroundBatchOrder")
    @ResponseBody
    @OrderCountCheck(reportType = "backgroundBatchOrder")
    public AjaxResult backgroundBatchOrder(BCreditReport bCreditReport){
        //设置当前操作人的loginName
        User sysUser = getSysUser();
        bCreditReport.setCreateBy(sysUser.getLoginName());
        String errName="";
        if(bCreditReport.getFile().isEmpty()){
            return error("请上传文件!");
        }
        String fileName=bCreditReport.getFile().getOriginalFilename();
        if(fileName.contains("xls")||fileName.contains("xlsx")){
            try {
                InputStream in = bCreditReport.getFile().getInputStream();
                ExcelReader reader = ExcelUtil.getReader(in);
                List<Map<String,Object>> readAll = reader.readAll();
                for(int i = 0; i < readAll.size(); i++){
                    Map<String,Object> map=readAll.get(i);
                    String com_name=map.get("企业名称").toString();
                    String code="";
                    //根据名称接口查询
                    Object htmlStr = QxbHttpUtils.sendHttpRequest("http://lhapi.lhdna.com/api/qxb/api/basicInf",new JSONObject(){{put("name",com_name);}} );
                    JSONObject jsonObject = JSONObject.parseObject(htmlStr.toString());
                    if(jsonObject.getString("code").equals("2000")){
                        JSONObject data=jsonObject.getJSONObject("data");
                        if(data!=null){
                            String creditNo=data.getString("creditNo");
                            if(StringUtils.isNotEmpty(creditNo)){
                                code=creditNo;
                            }else {
                                errName+=com_name+",";
                                continue;
                            }
                        }else {
                            errName+=com_name+",";
                            continue;
                        }
                    }else {
                        errName+=com_name+",";
                        continue;
                    }

                    BCreditReport newBcr=new BCreditReport();
                    BeanUtils.copyProperties(bCreditReport,newBcr);
                    newBcr.setEnterpriseName(com_name);
                    newBcr.setEnterpriseCode(code);
                    AjaxResult result=bCreditReportService.backgroundOrder(newBcr);
                    int rcode=Integer.parseInt(result.get("code").toString());
                    System.out.println(rcode);
                    if(rcode!=2000){
                        errName+=com_name+",";
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                return error();
            }
        }else {
            return error("请上传xls、xlsx文件!");
        }


        if(errName.isEmpty()){
            return success();
        }else {
            return error(errName+" 添加失败!");
        }

    }


    /**
     * 文件下载
     */
    public void downloadFile(HttpServletResponse response, String path) {
        try {
            File file = new File(path);
            // 取得文件名
            String filename = file.getName();
            //配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];

            InputStream fis = new FileInputStream(file);
            BufferedInputStream bis = null;

            try {
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("文件下载成功!");
            } catch (Exception e) {
                System.out.println("文件下载失败!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     *修改状态
     * @return
     */
    @PostMapping("/updateStatus")
    @ResponseBody
    public AjaxResult updateStatus(@RequestBody BCreditReport bCreditReport){
        try {
            String auditStatus=bCreditReport.getAuditStatus();
            bCreditReportService.updateStatus(bCreditReport.getId(),auditStatus,getUserInfo().getLoginName(),new Date());
            BCreditReport bcr= bCreditReportService.selectBCreditReportById(bCreditReport.getId());
            ContractReportBusinessType crbtNew = new ContractReportBusinessType();
            crbtNew.setContractId(bcr.getContractId());
            crbtNew.setTypeId(Long.valueOf(bcr.getReportType()));
            ContractReportBusinessType crbt=contractReportBusinessTypeMapper.findByType(crbtNew);
            if(ReportStatus.dzz.getCode().equals(auditStatus)){//审核通过
                if("Y".equals(crbt.getCreateImmediate())){
                    //发送邮件
                    sendEmail(bcr.getEnterpriseName(),bcr,bcr.getReportType());
                    //异步调用 重新生成报告
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            reportMakeService.makeReport(bcr);
                        }
                    }).start();
                }
            }
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return error();
        }


    }

    public  void sendEmail(String enterpriseName, BCreditReport bCreditReport, String reportType) {
        //邮件标题征信报告申请
        String title="征信报告申请";
        //根据orgid获取最顶层数据
        Long orgId = bCreditReport.getOrgId();
        FrontDept topDept = frontDeptService.selectFrontDeptById(orgId);
        //获取报告类型名称
        String reportName = iDictDataService.selectDictLabel("background_report_type", reportType);
        if (!topDept.getDeptName().contains("联合信用")){
            //邮件内容
            String content= "";
            //顶级公司名称与下属分公司名称一致,则不拼接 下属公司
            if (topDept.getDeptName().equals(bCreditReport.getEnterpriseName())){
                content=topDept.getDeptName() + "委托制作" + enterpriseName + "的" + reportName ;
            }else {
                content=topDept.getDeptName() + "下属" + bCreditReport.getEnterpriseName()  + "委托制作" + enterpriseName + "的" + reportName ;
            }
            SendMailUtil.sends(title,content, BCreditReportServiceImpl.sender,BCreditReportServiceImpl.cc);
        }
    }

    @RequestMapping("/addShangtouOrder")
    @ResponseBody
    public AjaxResult addShangtouOrder(ShangTouModel shangTouModel,HttpServletRequest request){
        try {
            logger.info("川商投请求参数"+ JSON.toJSONString(shangTouModel));
            //验证token
//            String authorization = request.getHeader("Authorization");
//            if (StringUtils.isEmpty(authorization) || !authorization.equals(token)) {
//                return error("token验证失败");
//            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //根据orgName,找到orgid
            FrontDept dept = frontDeptService.getFrontDeptByName(shangTouModel.getOrgName());
            FrontUser user=frontUserMapper.selectFrontUserByUserName("四川商投");
            //判断是否有制作中的报告
            BCreditReport bCreditReport=new BCreditReport();
            Long deptId = dept.getId();
            if(dept!=null){
                bCreditReport.setOrgId(deptId);
            }
            bCreditReport.setEnterpriseName(shangTouModel.getQiYeZWMC());
            bCreditReport.setSource("4");//川商投渠道
            bCreditReport.setReportProgress("3");
            List<BCreditReport> list=bCreditReportMapper.selectBCreditReportList(bCreditReport);
            if(list.size()>0){
                return error("该公司有制作中的报告");
            }else {
                //订单入库
                BCreditReport bcr=new BCreditReport();
                bcr.setId("CST-"+UUID.randomUUID().toString().replace("-",""));
                bcr.setCreateTime(new Date());
                bcr.setEnterpriseName(shangTouModel.getQiYeZWMC());
                bcr.setUserId(user.getId());
                bcr.setOrgId(deptId);
                bcr.setEntrustType("3");//委托类型,立即制作
                if(shangTouModel.getRemarks().equals("标准版")){
                    bcr.setReportType("-2");
                }else if(shangTouModel.getRemarks().equals("深度财务版")){
                    bcr.setReportType("-3");
                }
                //根据org_id,type,check查询价格和交付时间
                TemplateConfigurationParameters tcp=new TemplateConfigurationParameters();
                tcp.setOrgId(deptId);
                tcp.setId(bcr.getReportType());
                tcp.setChecked("Y");
                List<TemplateConfigurationParameters> listTcp=templateConfigurationParametersService.selectTemplateConfigurationParametersList(tcp);
                if(listTcp.size()>0){
                    int day=listTcp.get(0).getDeliveryDays();
                    bcr.setDeliveryTime(getWorkDay(day));//应交付日期
                    bcr.setProjectPrice(listTcp.get(0).getPrice());//价格
                }else {
                    bcr.setDeliveryTime(sdf.parse(shangTouModel.getYingJiaoFRQ()));//应交付日期
                    bcr.setProjectPrice(new BigDecimal(shangTouModel.getBaoGaoJG()));//价格
                }
                bcr.setOrgName(shangTouModel.getOrgName());
                bcr.setReportProgress("2");//待制作
                bcr.setApplicationName("四川商投");//申请人
                bcr.setCreateBy("四川商投");//创建人
                bcr.setSource("4");
                bcr.setOrderNum(shangTouModel.getId());
                bCreditReportMapper.insertBCreditReport(bcr);
            }

        }catch (Exception e){
            e.printStackTrace();
            return error();
        }
        return success();
    }


    public Date getWorkDay(int days) {
        Calendar cal = Calendar.getInstance();
        Date time = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(time);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        HolidayWorkday findholiday = holidayWorkdayMapper.findholiday(year + "");
        String holiday = findholiday.getHoliday();
        String workday = findholiday.getWorkday();
        if (12 == month) {
            HolidayWorkday findholiday2 = holidayWorkdayMapper.findholiday((year + 1) + "");
            String workday2 = findholiday2.getWorkday();
            String holiday2 = findholiday2.getHoliday();
            holiday = holiday + "," + holiday2;
            workday = workday + "," + workday2;
        }
        Date workDay = HolidayOrWork.getWorkDay(format, days, workday, holiday);
        return workDay;
    }


}