WebApiFinanceController.java 52.5 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
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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhcredit.common.utils.DateUtils;
import com.lhcredit.common.utils.LocalDateUtils;
import com.lhcredit.common.utils.StringUtils;
import com.lhcredit.common.utils.http.DBHttpTemplate;
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.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.project.business.BasicInformation.service.BasicInformationService;
import com.lhcredit.project.business.TianYC.entity.param.RequestParams;
import com.lhcredit.project.business.apiFinance.domain.ApiFinance;
import com.lhcredit.project.business.apiFinance.service.IApiFinanceService;
import com.lhcredit.project.business.apiZhKhxsdqxxlistList.domain.ApiZhKhxsdqxxlistList;
import com.lhcredit.project.business.apiZhKhxsdqxxlistList.service.IApiZhKhxsdqxxlistListService;
import com.lhcredit.project.business.apiZhKphzxxList.domain.ApiZhKphzxxList;
import com.lhcredit.project.business.apiZhKphzxxList.service.IApiZhKphzxxListService;
import com.lhcredit.project.business.apiZhLrbxxList.domain.ApiZhLrbxxList;
import com.lhcredit.project.business.apiZhLrbxxList.service.IApiZhLrbxxListService;
import com.lhcredit.project.business.apiZhQsggList.domain.ApiZhQsggList;
import com.lhcredit.project.business.apiZhQsggList.service.IApiZhQsggListService;
import com.lhcredit.project.business.apiZhQyxxList.domain.ApiZhQyxxList;
import com.lhcredit.project.business.apiZhQyxxList.service.IApiZhQyxxListService;
import com.lhcredit.project.business.apiZhSbxxList.domain.ApiZhSbxxList;
import com.lhcredit.project.business.apiZhSbxxList.service.IApiZhSbxxListService;
import com.lhcredit.project.business.apiZhSpxsxxList.domain.ApiZhSpxsxxList;
import com.lhcredit.project.business.apiZhSpxsxxList.service.IApiZhSpxsxxListService;
import com.lhcredit.project.business.apiZhSykphzxxList.domain.ApiZhSykphzxxList;
import com.lhcredit.project.business.apiZhSykphzxxList.service.IApiZhSykphzxxListService;
import com.lhcredit.project.business.apiZhWfxwList.domain.ApiZhWfxwList;
import com.lhcredit.project.business.apiZhWfxwList.service.IApiZhWfxwListService;
import com.lhcredit.project.business.apiZhXykphzxxList.domain.ApiZhXykphzxxList;
import com.lhcredit.project.business.apiZhXykphzxxList.service.IApiZhXykphzxxListService;
import com.lhcredit.project.business.apiZhZcfzbxxList.domain.ApiZhZcfzbxxList;
import com.lhcredit.project.business.apiZhZcfzbxxList.service.IApiZhZcfzbxxListService;
import com.lhcredit.project.business.apiZhZsxxList.domain.ApiZhZsxxList;
import com.lhcredit.project.business.apiZhZsxxList.service.IApiZhZsxxListService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * 财务数据信息对外接口
 *
 * @author lhcredit
 * @date 2025-05-12
 */
@RestController
@RequestMapping("/web/apiFinance")
@Log4j2
public class WebApiFinanceController extends BaseController {
    @Autowired
    private IApiFinanceService apiFinanceService;

    @Autowired
    private BasicInformationService basicInformationService;

    @Autowired
    private IApiZhKhxsdqxxlistListService apiZhKhxsdqxxlistListService;
    @Autowired
    private IApiZhQyxxListService apiZhQyxxListService;
    @Autowired
    private IApiZhKphzxxListService apiZhKphzxxListService;
    @Autowired
    private IApiZhSykphzxxListService apiZhSykphzxxListService;
    @Autowired
    private IApiZhXykphzxxListService apiZhXykphzxxListService;
    @Autowired
    private IApiZhSpxsxxListService apiZhSpxsxxListService;
    @Autowired
    private IApiZhSbxxListService apiZhSbxxListService;
    @Autowired
    private IApiZhZsxxListService apiZhZsxxListService;
    @Autowired
    private IApiZhLrbxxListService apiZhLrbxxListService;
    @Autowired
    private IApiZhZcfzbxxListService apiZhZcfzbxxListService;
    @Autowired
    private IApiZhQsggListService apiZhQsggListService;
    @Autowired
    private IApiZhWfxwListService apiZhWfxwListService;

    @Autowired
    private RedisTemplate redisTemplate;

//    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    // 使用ConcurrentHashMap存储运行中的任务
//    private final Map<String, ScheduledFuture<?>> runningTasks = new ConcurrentHashMap<>();

    @Value("${DB.url}")
    private String dbUrl;

    @Autowired
    private DBHttpTemplate dbTemplate;
    @ReportCount(reportType = "taxInfo")
    @GetMapping("/reflushedFinance")
    public AjaxResult reflushedFinance(String ename,String creditCode, String authType,String sendType) {
        // 检查是否存在同名的运行中任务
        if (StringUtils.isEmpty(sendType))sendType="1";
        RequestParams requestParams = new RequestParams();
        requestParams.setCreditCode(creditCode);
        JSONObject jsonObject = basicInformationService.baseinfo2(requestParams);
        if (jsonObject != null && "2000".equals(jsonObject.getString("code"))) {
            JSONObject data = jsonObject.getJSONObject("data");
            ApiFinance apiFinance = new ApiFinance();
            apiFinance.setBaseName(data.getString("name"));
            apiFinance.setType(authType);
            apiFinance.setProgress(0);
            apiFinance.setSource(sendType);
            List<ApiFinance> apiFinances = apiFinanceService.selectApiFinanceList(apiFinance);
            if (CollectionUtils.isNotEmpty(apiFinances)){
                return AjaxResult.warn("该企业在查询中!!!");
            }
            creditCode = data.getString("creditNo");
            String url =null;
            JSONObject db = new JSONObject();
            db.put("ename", ename);
            db.put("creditCode", creditCode);
            db.put("authType", authType);
            if (sendType.equals("1")){
                url=  dbUrl + "/lhdb/zhFinanceData/xygj";
                LocalDateUtils localDateUtils = LocalDateUtils.of(new Date());
                db.put("authTimeEnd", localDateUtils.getFormatStr("yyyy")+"-12-31");
                db.put("authTimeBeg",localDateUtils.time_addOrSub(-3, LocalDateUtils.TimeUnit.Year).getFormatStr("yyyy")+"-01-01");
            } else if (sendType.equals("2")) {
                url=  dbUrl + "/lhdb/kdTaxData/xygj";
            } else if (sendType.equals("3")) {
                url=  dbUrl + "/lhdb/brzhXcFinance/xygj";
                db.put("uscCode", creditCode);
                db.remove("creditCode");
            } else if (sendType.equals("4")) {
                url=  dbUrl + "/lhdb/cqycFinance/xygj";
                db.put("type", authType.equals("ZX302")?1:2);
                LocalDateUtils localDateUtils = LocalDateUtils.of(new Date());
                db.put("authTimeEnd", localDateUtils.getYMD()+" 23:59:59");
                db.put("authTimeBeg",localDateUtils.time_addOrSub(-3, LocalDateUtils.TimeUnit.Year).getYMD()+" 00:00:00");

            }else{
                return toAjax("请选择正确的数据来源");
            }

            try {

                JSONObject jsonObject1 = dbTemplate.getPost(url, db);
                System.out.println(jsonObject1.toJSONString());
                if (jsonObject1 == null || !"2000".equals(jsonObject1.getString("code"))) {
                    return toAjax("获取数据失败");
                }

                String authCode = jsonObject1.getJSONObject("data").getString("authCode");
                apiFinance.setAuthCode(authCode);
                apiFinance.setApplicationTime(new Date());
                apiFinance.setUId(String.valueOf(getUserInfo().getId()));
                apiFinance.setProgress(0);
                apiFinance.setCreditCode(creditCode);
                apiFinance.setOrgId(Math.toIntExact(getUserInfo().getOrgId()));
                apiFinanceService.insertApiFinance(apiFinance);
                String finalCreditCode = creditCode;
                return success();
            } catch (Exception e) {
                log.error("获取认证码异常", e);
                return toAjax("系统异常,请稍后再试");
            }
        }

        return toAjax("该企业不存在");
    }
    public static boolean tag=false;

    /**
     * 中登task
     */
    @Scheduled(fixedDelay = 1000*60*5)
    public  void  checkAndUpdateData2(){
        if (tag== true){
          return;
        }
        tag=true;//执行中
        ApiFinance apiFinance = new ApiFinance();
        apiFinance.setProgress(0);
        List<ApiFinance> apiFinances = apiFinanceService.selectApiFinanceList(apiFinance);
        for (ApiFinance finance : apiFinances) {
            checkAndUpdateData2(finance.getAuthCode(),finance.getCreditCode(),finance);
        }
        tag=false;//执行完毕
    }
    private void checkAndUpdateData2(String authCode, String creditCode, ApiFinance apiFinance) {
        String url1 = dbUrl + "/lhdb/getCallback/xygj";
        JSONObject getCallback = new JSONObject();
        getCallback.put("authCode", authCode);
        getCallback.put("nsrsbh", creditCode);
        try {
            JSONObject firstResult = dbTemplate.getPost(url1, getCallback);
            log.info("查询状态URL: {}", url1);
            log.info("查询状态结果: {}", firstResult);

            if (firstResult == null || !"2000".equals(firstResult.getString("code"))) {
                log.warn("获取状态失败,停止任务: {}", firstResult);
                apiFinance.setProgress(2);
                apiFinanceService.updateApiFinance(apiFinance);
                return;
            }
            System.out.println(firstResult.toJSONString());
            String status = firstResult.getJSONObject("data").getString("status");
            switch (status) {
                case "2000":
                    // 处理成功状态
                    log.info("开始处理财务数据,任务ID: {}", apiFinance.getId());
                    processData(firstResult, apiFinance);
                    apiFinance.setProgress(1);
                    apiFinance.setCompletionTime(new Date());
                    apiFinanceService.updateApiFinance(apiFinance);
                    break;
                case "2010":
                    // 处理进行中状态
                    log.info("任务处理中,继续等待,任务ID: {}", apiFinance.getId());
                    apiFinance.setProgress(2);
                    apiFinance.setCompletionTime(new Date());
                    apiFinanceService.updateApiFinance(apiFinance);
                    break;
                default:
                    // 其他状态视为失败
                    //申请日期超过1天时间  置为失效
                    Date completionTime = apiFinance.getApplicationTime();
                    Date date = LocalDateUtils.of(completionTime).time_addOrSub(1, LocalDateUtils.TimeUnit.Day).getDate();
                    if (new Date().getTime()>date.getTime()){
                        apiFinance.setProgress(2);
                        apiFinanceService.updateApiFinance(apiFinance);
                    }
                    log.warn("获取中: {}, 任务ID: {}", status, apiFinance.getId());
            }
        } catch (Exception e) {
            log.error("检查状态异常,停止任务,任务ID: {}", apiFinance.getId(), e);
        }
    }

    private void checkAndUpdateData(String authCode, String creditCode, ApiFinance apiFinance, String taskKey, ScheduledFuture<?> future) {
        String url1 = dbUrl + "/lhdb/getCallback/xygj";
        JSONObject getCallback = new JSONObject();
        getCallback.put("authCode", authCode);
        getCallback.put("nsrsbh", creditCode);
        try {
            JSONObject firstResult = dbTemplate.getPost(url1, getCallback);
            log.info("查询状态URL: {}", url1);
            log.info("查询状态结果: {}", firstResult);

            if (firstResult == null || !"2000".equals(firstResult.getString("code"))) {
                log.warn("获取状态失败,停止任务: {}", firstResult);
                markTaskCompleted(apiFinance, 2, taskKey, future);
                return;
            }
            System.out.println(firstResult.toJSONString());
            String status = firstResult.getJSONObject("data").getString("status");

            switch (status) {
                case "2000":
                    // 处理成功状态
                    log.info("开始处理财务数据,任务ID: {}", apiFinance.getId());
                    processData(firstResult, apiFinance);
                    markTaskCompleted(apiFinance, 1, taskKey, future);
                    break;
                case "2010":
                    // 处理进行中状态
                    log.info("任务处理中,继续等待,任务ID: {}", apiFinance.getId());
                    markTaskCompleted(apiFinance, 2, taskKey, future);
                    break;
                default:
                    // 其他状态视为失败
                    log.warn("获取中: {}, 任务ID: {}", status, apiFinance.getId());
            }
        } catch (Exception e) {
            log.error("检查状态异常,停止任务,任务ID: {}", apiFinance.getId(), e);
        }
    }

    private void processData(JSONObject firstResult, ApiFinance apiFinance) {

        processDataType(firstResult, "zhKhxsdqxxlistLists", ApiZhKhxsdqxxlistList.class, apiZhKhxsdqxxlistListService, apiFinance);
        processDataType(firstResult, "zhQyxxLists", ApiZhQyxxList.class, apiZhQyxxListService, apiFinance);
        processDataType(firstResult, "zhKphzxxLists", ApiZhKphzxxList.class, apiZhKphzxxListService, apiFinance);
        processDataType(firstResult, "zhSykphzxxLists", ApiZhSykphzxxList.class, apiZhSykphzxxListService, apiFinance);
        processDataType(firstResult, "zhXykphzxxLists", ApiZhXykphzxxList.class, apiZhXykphzxxListService, apiFinance);
        processDataType(firstResult, "zhSpxsxxLists", ApiZhSpxsxxList.class, apiZhSpxsxxListService, apiFinance);
        processDataType(firstResult, "zhSbxxLists", ApiZhSbxxList.class, apiZhSbxxListService, apiFinance);
        processDataType(firstResult, "zhZsxxLists", ApiZhZsxxList.class, apiZhZsxxListService, apiFinance);
        processDataType(firstResult, "zhLrbxxLists", ApiZhLrbxxList.class, apiZhLrbxxListService, apiFinance);
        processDataType(firstResult, "zhZcfzbxxLists", ApiZhZcfzbxxList.class, apiZhZcfzbxxListService, apiFinance);
        processDataType(firstResult, "zhQsggLists", ApiZhQsggList.class, apiZhQsggListService, apiFinance);
        processDataType(firstResult, "zhWfxwLists", ApiZhWfxwList.class, apiZhWfxwListService, apiFinance);

        log.info("财务数据处理完成,任务ID: {}", apiFinance.getId());
    }




    private <T> void processDataType(JSONObject firstResult, String key, Class<T> clazz, Object service, ApiFinance apiFinance) {
        try {
            saveListData(firstResult, key, clazz, service);
            log.info("成功处理数据类型: {}, 任务ID: {}", key, apiFinance.getId());
        } catch (Exception e) {
            log.error("处理数据类型 {} 失败,任务ID: {}", key, apiFinance.getId(), e);
        }
    }

    private <T> void saveListData(JSONObject firstResult, String key, Class<T> clazz, Object service) {
        JSONArray list = firstResult.getJSONObject("data").getJSONArray(key);
        if (CollectionUtils.isNotEmpty(list)) {
            List<T> dataList = list.stream()
                    .map(item -> mapJsonToObject((JSONObject) item, clazz))
                    .filter(Objects::nonNull) // 过滤空对象
                    .collect(Collectors.toList());

            if (!dataList.isEmpty()) {
                try {
                    log.info("未找到批量方法,使用单条插入: {}", key);
                    for (T item : dataList) {
                        try {
                            // 使用单条插入方法
                            invokeServiceMethod(service, item);
                            log.info("成功保存单条 {} 数据", key);
                        } catch (Exception ex) {
                            log.error("保存单条 {} 数据失败", key, ex);
                        }
                    }
                } catch (Exception e) {
                    log.error("保存单条 {} 数据失败", key,  e);
                }
            }
        }
    }

    private <T> void invokeServiceMethod(Object service, T item) {
        try {
            Method method = service.getClass().getMethod("insert" + item.getClass().getSimpleName(), item.getClass());
            log.info("调用服务方法: {}", method);
            method.invoke(service, item);
        } catch (Exception e) {
            log.error("调用服务方法失败,类名: {}", item.getClass().getSimpleName(), e);
        }
    }

    // 优化后的反射实现,使用更健壮的类型转换
    private <T> T mapJsonToObject(JSONObject jsonItem, Class<T> clazz) {
        try {
            T obj = clazz.getDeclaredConstructor().newInstance();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();

                if (jsonItem.containsKey(fieldName)) {
                    Object value = jsonItem.get(fieldName);
                    if (value == null) continue;

                    try {
                        // 处理不同类型的字段赋值
                        Class<?> fieldType = field.getType();

                        if (fieldType == String.class) {
                            field.set(obj, value.toString());
                        } else if (fieldType == Integer.class || fieldType == int.class) {
                            field.set(obj, Integer.valueOf(value.toString()));
                        } else if (fieldType == Long.class || fieldType == long.class) {
                            field.set(obj, Long.valueOf(value.toString()));
                        } else if (fieldType == BigDecimal.class) {
                            field.set(obj, new BigDecimal(value.toString()));
                        } else if (fieldType == Date.class) {
                            if (value instanceof String) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                field.set(obj, sdf.parse((String) value));
                            } else if (value instanceof Long) {
                                field.set(obj, new Date((Long) value));
                            }
                        } else if (fieldType.isEnum()) {
                            @SuppressWarnings("unchecked")
                            Object enumValue = Enum.valueOf((Class<Enum>) fieldType, value.toString());
                            field.set(obj, enumValue);
                        } else {
                            // 其他类型直接设置
                            field.set(obj, value);
                        }
                    } catch (Exception e) {
                        log.warn("字段映射失败: {} -> {}, 值: {}", fieldName, field.getType(), value, e);
                    }
                }
            }

            return obj;
        } catch (Exception e) {
            log.error("JSON映射异常,目标类: {}", clazz.getName(), e);
            return null;
        }
    }

    private void markTaskCompleted(ApiFinance apiFinance, int progress, String taskKey, ScheduledFuture<?> future) {
        try {
            apiFinance.setProgress(progress);
            apiFinance.setCompletionTime(new Date());
            apiFinanceService.updateApiFinance(apiFinance);

            // 停止任务并从运行列表中移除
            if (future != null && !future.isCancelled()) {
                future.cancel(true);
                log.info("已取消定时任务,任务ID: {}", taskKey);
            }
            if (taskKey != null) {
                log.info("已移除任务记录,任务ID: {}", taskKey);
            }

            String statusMsg = progress == 1 ? "成功" : "失败";
            log.info("任务已完成,状态: {}, 任务ID: {}", statusMsg, apiFinance.getId());
        } catch (Exception e) {
            log.error("更新任务状态异常,任务ID: {}", apiFinance.getId(), e);
        }
    }


    /**
     * 查询财务数据列表接口
     */
    @ApiOperation("查询财务数据列表")
    @Log(title = "财务数据", businessType = BusinessType.LIST, operatorType = OperatorType.WEB)
    @GetMapping
    @CheckToken(type = "2")
    public AjaxResult list(ApiFinance apiFinance) {
        apiFinance.setUId(String.valueOf(getUserInfo().getId()));
        startPage();
        List<ApiFinance> list =apiFinanceService.selectApiFinanceList(apiFinance);
        return toAjax(list);
    }

    @ApiOperation("查询基础财务数据")
    @GetMapping("/finance/{id}")
    public AjaxResult getFinanceById(@PathVariable Long id) {
        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(id)));
        return toAjax(apiFinance);
    }

    /**
     * 查询违法行为信息列表
     */
    @ApiOperation("查询违法行为信息列表")
    @GetMapping("/wfxw/list/{financeId}")
    public TableDataInfo listWfxw(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhWfxwList queryWrapper = new ApiZhWfxwList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhWfxwList> list = apiZhWfxwListService.selectApiZhWfxwListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询欠税信息列表
     */
    @ApiOperation("查询欠税信息列表")
    @GetMapping("/qsgg/list/{financeId}")
    public TableDataInfo listQsgg(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhQsggList queryWrapper = new ApiZhQsggList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhQsggList> list = apiZhQsggListService.selectApiZhQsggListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询资产负债表信息列表
     */
    @ApiOperation("查询资产负债表信息列表")
    @GetMapping("/zcfzbxx/list/{financeId}")
    public TableDataInfo listZcfzbxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhZcfzbxxList queryWrapper = new ApiZhZcfzbxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhZcfzbxxList> list = apiZhZcfzbxxListService.selectApiZhZcfzbxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询利润表信息列表
     */
    @ApiOperation("查询利润表信息列表")
    @GetMapping("/lrbxx/list/{financeId}")
    public TableDataInfo listLrbxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhLrbxxList queryWrapper = new ApiZhLrbxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhLrbxxList> list = apiZhLrbxxListService.selectApiZhLrbxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询税收信息列表
     */
    @ApiOperation("查询税收信息列表")
    @GetMapping("/zsxx/list/{financeId}")
    public TableDataInfo listZsxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhZsxxList queryWrapper = new ApiZhZsxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhZsxxList> list = apiZhZsxxListService.selectApiZhZsxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询设备信息列表
     */
    @ApiOperation("查询设备信息列表")
    @GetMapping("/sbxx/list/{financeId}")
    public TableDataInfo listSbxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhSbxxList queryWrapper = new ApiZhSbxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhSbxxList> list = apiZhSbxxListService.selectApiZhSbxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询商品销售信息列表
     */
    @ApiOperation("查询商品销售信息列表")
    @GetMapping("/spxsxx/list/{financeId}")
    public TableDataInfo listSpxsxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhSpxsxxList queryWrapper = new ApiZhSpxsxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhSpxsxxList> list = apiZhSpxsxxListService.selectApiZhSpxsxxListList(queryWrapper);
        return getDataTable(list);
    }


    /**
     * 查询开票汇总信息列表
     */
    @ApiOperation("查询开票汇总信息列表")
    @GetMapping("/kphzxx/list/{financeId}")
    public TableDataInfo listKphzxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhKphzxxList queryWrapper = new ApiZhKphzxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhKphzxxList> list = apiZhKphzxxListService.selectApiZhKphzxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询企业信息列表
     */
    @ApiOperation("查询企业信息列表")
    @GetMapping("/qyxx/list/{financeId}")
    public TableDataInfo listQyxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhQyxxList queryWrapper = new ApiZhQyxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhQyxxList> list = apiZhQyxxListService.selectApiZhQyxxListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询客户授信申请信息列表
     */
    @ApiOperation("查询客户授信申请信息列表")
    @GetMapping("/khxsdqxx/list/{financeId}")
    public TableDataInfo listKhxsdqxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhKhxsdqxxlistList queryWrapper = new ApiZhKhxsdqxxlistList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
//        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhKhxsdqxxlistList> list = apiZhKhxsdqxxlistListService.selectApiZhKhxsdqxxlistListList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询上游开票汇总信息
     */
    @ApiOperation("查询上游开票汇总信息")
    @GetMapping("/sykphzxx/list/{financeId}")
    public TableDataInfo sykphzxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhSykphzxxList queryWrapper = new ApiZhSykphzxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhSykphzxxList> list = apiZhSykphzxxListService.selectApiZhSykphzxxListList(queryWrapper);
        return getDataTable(list);
    }



    /**
     * 查询下游开票汇总信息
     */
    @ApiOperation("查询下游开票汇总信息")
    @GetMapping("/xykphzxx/list/{financeId}")
    public TableDataInfo xykphzxx(
            @PathVariable Long financeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        ApiFinance apiFinance = apiFinanceService.changeModel(
                apiFinanceService.selectApiFinanceById(Math.toIntExact(financeId)));

        ApiZhXykphzxxList queryWrapper = new ApiZhXykphzxxList();
        queryWrapper.setAuthCode(apiFinance.getAuthCode());
        queryWrapper.setNsrsbh(apiFinance.getCreditCode());
        startPage();
        List<ApiZhXykphzxxList> list = apiZhXykphzxxListService.selectApiZhXykphzxxListList(queryWrapper);
        return getDataTable(list);
    }

    @ApiOperation("数据导出")
    @GetMapping("/export/{id}")
    public void export(@PathVariable Long id, HttpServletResponse response) {
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("无效的ID参数");
            }

            // 获取基础财务数据
            ApiFinance apiFinance = apiFinanceService.changeModel(
                    apiFinanceService.selectApiFinanceById(Math.toIntExact(id)));

            if (apiFinance == null) {
                throw new IllegalArgumentException("未找到对应的财务数据");
            }

            // 构建查询条件
            String authCode = apiFinance.getAuthCode();
            String creditCode = apiFinance.getCreditCode();

            // 查询各类业务数据
            Map<String, List<?>> dataMap = new HashMap<>();
            dataMap.put("违法行为信息", queryWfxwList(authCode, creditCode));
            dataMap.put("欠税信息", queryQsggList(authCode, creditCode));
            dataMap.put("资产负债表信息", queryZcfzbxxList(authCode, creditCode));
            dataMap.put("征收信息", queryZsxxList(authCode, creditCode));
            dataMap.put("申报信息", querySbxxList(authCode, creditCode));
            dataMap.put("利润表信息", queryLrbxxList(authCode, creditCode));
            dataMap.put("商品销售信息", querySpxsxxList(authCode, creditCode));
            dataMap.put("下游开票汇总信息", queryXykphzxxList(authCode, creditCode));
            dataMap.put("上游开票汇总信息", querySykphzxxList(authCode, creditCode));
            dataMap.put("开票信息汇总", queryKphzxxList(authCode, creditCode));
            dataMap.put("企业基本信息", queryQyxxList(authCode, creditCode));
            dataMap.put("客户销售地区信息", queryKhxsdqxxlistList(authCode, creditCode));

            // 设置响应头
            configureResponseHeader(response, apiFinance.getBaseName());

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

        } catch (IllegalArgumentException e) {
            handleExportException(response, e.getMessage(), 400);
        } catch (Exception e) {
            handleExportException(response, "导出数据失败: " + e.getMessage(), 500);
        }
    }

    // 查询违法行为信息
    private List<ApiZhWfxwList> queryWfxwList(String authCode, String creditCode) {
        ApiZhWfxwList queryWrapper = new ApiZhWfxwList();
        queryWrapper.setAuthCode(authCode);

        return apiZhWfxwListService.selectApiZhWfxwListList(queryWrapper);
    }

    // 查询欠税信息
    private List<ApiZhQsggList> queryQsggList(String authCode, String creditCode) {
        ApiZhQsggList qsggQuery = new ApiZhQsggList();
        qsggQuery.setAuthCode(authCode);

        return apiZhQsggListService.selectApiZhQsggListList(qsggQuery);
    }

    // 查询资产负债表信息
    private List<ApiZhZcfzbxxList> queryZcfzbxxList(String authCode, String creditCode) {
        ApiZhZcfzbxxList zcfzbxxQuery = new ApiZhZcfzbxxList();
        zcfzbxxQuery.setAuthCode(authCode);

        return apiZhZcfzbxxListService.selectApiZhZcfzbxxListList(zcfzbxxQuery);
    }

    // 查询利润表信息
    private List<ApiZhLrbxxList> queryLrbxxList(String authCode, String creditCode) {
        ApiZhLrbxxList lrbxxQuery = new ApiZhLrbxxList();
        lrbxxQuery.setAuthCode(authCode);

        return apiZhLrbxxListService.selectApiZhLrbxxListList(lrbxxQuery);
    }

    // 查询税收信息
    private List<ApiZhZsxxList> queryZsxxList(String authCode, String creditCode) {
        ApiZhZsxxList zsxxQuery = new ApiZhZsxxList();
        zsxxQuery.setAuthCode(authCode);

        return apiZhZsxxListService.selectApiZhZsxxListList(zsxxQuery);
    }

    // 查询设备信息
    private List<ApiZhSbxxList> querySbxxList(String authCode, String creditCode) {
        ApiZhSbxxList sbxxQuery = new ApiZhSbxxList();
        sbxxQuery.setAuthCode(authCode);

        return apiZhSbxxListService.selectApiZhSbxxListList(sbxxQuery);
    }

    // 查询商品销售信息
    private List<ApiZhSpxsxxList> querySpxsxxList(String authCode, String creditCode) {
        ApiZhSpxsxxList spxsxxQuery = new ApiZhSpxsxxList();
        spxsxxQuery.setAuthCode(authCode);

        return apiZhSpxsxxListService.selectApiZhSpxsxxListList(spxsxxQuery);
    }

    // 查询信用开票信息
    private List<ApiZhXykphzxxList> queryXykphzxxList(String authCode, String creditCode) {
        ApiZhXykphzxxList xykphzxxQuery = new ApiZhXykphzxxList();
        xykphzxxQuery.setAuthCode(authCode);

        return apiZhXykphzxxListService.selectApiZhXykphzxxListList(xykphzxxQuery);
    }

    // 查询使用开票信息
    private List<ApiZhSykphzxxList> querySykphzxxList(String authCode, String creditCode) {
        ApiZhSykphzxxList sykphzxxQuery = new ApiZhSykphzxxList();
        sykphzxxQuery.setAuthCode(authCode);
        return apiZhSykphzxxListService.selectApiZhSykphzxxListList(sykphzxxQuery);
    }

    // 查询开票汇总信息
    private List<ApiZhKphzxxList> queryKphzxxList(String authCode, String creditCode) {
        ApiZhKphzxxList kphzxxQuery = new ApiZhKphzxxList();
        kphzxxQuery.setAuthCode(authCode);
        return apiZhKphzxxListService.selectApiZhKphzxxListList(kphzxxQuery);
    }

    // 查询企业信息
    private List<ApiZhQyxxList> queryQyxxList(String authCode, String creditCode) {
        ApiZhQyxxList qyxxQuery = new ApiZhQyxxList();
        qyxxQuery.setAuthCode(authCode);
        return apiZhQyxxListService.selectApiZhQyxxListList(qyxxQuery);
    }

    // 查询客户授信申请信息
    private List<ApiZhKhxsdqxxlistList> queryKhxsdqxxlistList(String authCode, String creditCode) {
        ApiZhKhxsdqxxlistList khxsdqxxlistQuery = new ApiZhKhxsdqxxlistList();
        khxsdqxxlistQuery.setAuthCode(authCode);
        return apiZhKhxsdqxxlistListService.selectApiZhKhxsdqxxlistListList(khxsdqxxlistQuery);
    }

    // 配置HTTP响应头
    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(Map<String, List<?>> dataMap, ServletOutputStream outputStream) {
        try (ExcelWriter writer = ExcelUtil.getWriter(true)) {
            // 设置列名别名
            setupHeaderAliases(writer);

            // 过滤出有数据的entry
            List<Map.Entry<String, List<?>>> nonEmptyEntries = dataMap.entrySet().stream()
                    .filter(entry -> CollUtil.isNotEmpty(entry.getValue()))
                    .collect(Collectors.toList());

            if (nonEmptyEntries.isEmpty()) {
                // 如果没有数据,直接返回
                return;
            }

            // 处理第一个sheet(覆盖默认sheet)
            Map.Entry<String, List<?>> firstEntry = nonEmptyEntries.get(0);
            writer.renameSheet(firstEntry.getKey()); // 重命名默认sheet
            writer.write(firstEntry.getValue(), true);

            // 处理剩余sheet
            for (int i = 1; i < nonEmptyEntries.size(); i++) {
                Map.Entry<String, List<?>> entry = nonEmptyEntries.get(i);
                writer.setSheet(entry.getKey()); // 切换到新sheet(不存在则创建)
                writer.write(entry.getValue(), true);
            }

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

    // 设置Excel表头别名
    private void setupHeaderAliases(ExcelWriter writer) {
        // 这里是原代码中的大量headerAlias设置
        writer.addHeaderAlias("nsrsbh", "纳税人识别号");
        writer.addHeaderAlias("djxh", "纳税人登记序号");
        writer.addHeaderAlias("nsrmc", "纳税人名称");
        writer.addHeaderAlias("dlhyDm", "大类行业代码");
        writer.addHeaderAlias("dlhymc", "大类行业名称");
        writer.addHeaderAlias("cyDm", "产业代码");
        writer.addHeaderAlias("cymc", "产业名称");
        writer.addHeaderAlias("scjydz", "生产经营地址");
        writer.addHeaderAlias("dsswjgDm", "地市税务机关代码");
        writer.addHeaderAlias("dsswjgmc", "地市税务机关名称");
        writer.addHeaderAlias("nsrztmc", "纳税人状态");
        writer.addHeaderAlias("zzsnsrlxId", "增值税纳税人类型");
        writer.addHeaderAlias("nsrlx", "纳税人类型");
        writer.addHeaderAlias("nsrxydjId", "纳税人信用等级");
        writer.addHeaderAlias("scjyddhhm", "生产经营地电话号码");
        writer.addHeaderAlias("djzclxDm", "登记注册类型代码");
        writer.addHeaderAlias("djzclxmc", "登记注册类型名称");
        writer.addHeaderAlias("minKprq", "最小开票日期");
        writer.addHeaderAlias("kprqMinMonth", "实际经营月份数");
        writer.addHeaderAlias("dlhyDm", "大类行业代码_销方");
        writer.addHeaderAlias("dlhymc", "大类行业名称_销方");
        writer.addHeaderAlias("dykptsLp", "当月开票天数(蓝票)");
        writer.addHeaderAlias("dykptsQb", "当月开票天数(全部)");
        writer.addHeaderAlias("lpje", "蓝票金额(含税)202311新增,广东、上海、四川暂不包含");
        writer.addHeaderAlias("lpwsje", "蓝票金额(不含税)202311新增,广东、上海、四川暂不包含");
        writer.addHeaderAlias("lpse", "蓝票税额 202311新增,广东、上海、四川暂不包含");
        writer.addHeaderAlias("lpsl", "蓝票数量 202311新增,广东、上海、四川暂不包含");
        writer.addHeaderAlias("fpje", "废票金额(含税)");
        writer.addHeaderAlias("fpsl", "废票数量");
        writer.addHeaderAlias("fpwsje", "废票金额(不含税)(广东、上海、四川可能为空)");
        writer.addHeaderAlias("fpse", "废票税额(广东、上海、四川可能为空)");
        writer.addHeaderAlias("hpje", "红票金额(含税)");
        writer.addHeaderAlias("hpwsje", "红票金额(不含税)(广东、上海、四川可能为空)");
        writer.addHeaderAlias("hpse", "红票税额(广东、上海、四川可能为空)");
        writer.addHeaderAlias("hpsl", "红票数量");
        writer.addHeaderAlias("yxhpje", "有效红票金额");
        writer.addHeaderAlias("yxhpsl", "有效红票数量");
        writer.addHeaderAlias("kpje", "开票金额(含税)");
        writer.addHeaderAlias("wsje", "开票金额(不含税)(广东、上海、四川可能为空)");
        writer.addHeaderAlias("se", "开票税额(广东、上海、四川可能为空)");
        writer.addHeaderAlias("yxwsje", "有效开票金额(不含税)(广东、上海、四川可能为空)");
        writer.addHeaderAlias("kpsl", "开票数量");
        writer.addHeaderAlias("kpqj", "开票期间");
        writer.addHeaderAlias("kpyf", "开票月份");
        writer.addHeaderAlias("lxwjyts", "当前连续无交易记录天数");
        writer.addHeaderAlias("zddzje", "单张最高开票金额");
        writer.addHeaderAlias("zjkpsj", "最近一笔开票时间");
        writer.addHeaderAlias("ppkpje", "普票_含税金额合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("ppwsje", "普票_无税金额合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("ppkpsl", "普票_张数合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("zpkpje", "专票_含税金额合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("zpwsje", "专票_无税金额合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("zpkpsl", "专票_张数合计(广东、上海、四川可能为空)");
        writer.addHeaderAlias("xfhyId", "销方行业代码");
        writer.addHeaderAlias("xfCount", "销方数量");
        writer.addHeaderAlias("xfmc", "销方名称");
        writer.addHeaderAlias("xfDjxh", "销方登记序号");
        writer.addHeaderAlias("zcjeCnt", "开票数量");
        writer.addHeaderAlias("zcjeCntRate", "开票数量占比");
        writer.addHeaderAlias("zcjeSum", "开票金额(含税)");
        writer.addHeaderAlias("zcjeSumRank", "排名");
        writer.addHeaderAlias("zcjeSumRate", "开票金额占比");
        writer.addHeaderAlias("gfCount", "购方数量");
        writer.addHeaderAlias("gfDjxh", "购方登记序号");
        writer.addHeaderAlias("gfhyId", "购方行业代码");
        writer.addHeaderAlias("gfmc", "购方名称");
        writer.addHeaderAlias("gfdsswjgId", "购方地市行政区划代码");
        writer.addHeaderAlias("gfdsmc", "购方地市行政区划名称(广东、上海、四川可能为空)");
        writer.addHeaderAlias("gfsCount", "购方地市税务机关数量");
        writer.addHeaderAlias("zcjeCnt", "交易次数");
        writer.addHeaderAlias("zcjeCntRate", "交易次数占比");
        writer.addHeaderAlias("zcjeSum", "交易金额(含税)");
        writer.addHeaderAlias("zcjeSumRate", "交易金额占比");
        writer.addHeaderAlias("hwbmCount", "该销方下的货物或劳务编码种类数");
        writer.addHeaderAlias("jeSum", "商品总金额(不含税)");
        writer.addHeaderAlias("jeSumRank", "交易金额占比排名");
        writer.addHeaderAlias("seSum", "商品总税额");
        writer.addHeaderAlias("slSum", "商品总数量");
        writer.addHeaderAlias("slv", "税率");
        writer.addHeaderAlias("spbm", "商品编码");
        writer.addHeaderAlias("zcjeCntRate", "商品或劳务总数量占比");
        writer.addHeaderAlias("zcjeSumRate", "商品或劳务总金额占比");
        writer.addHeaderAlias("sbrq", "申报日期");
        writer.addHeaderAlias("jmse", "减免税额");
        writer.addHeaderAlias("ysx", "全部销售收入");
        writer.addHeaderAlias("sbqx", "申报期限");
        writer.addHeaderAlias("skssqq", "所属日期起");
        writer.addHeaderAlias("skssqz", "所属日期止");
        writer.addHeaderAlias("ybtse", "应补退税额");
        writer.addHeaderAlias("yjse", "预缴税额");
        writer.addHeaderAlias("ynse", "应纳税额");
        writer.addHeaderAlias("jsyj", "应税销售收入");
        writer.addHeaderAlias("zsxmmc", "税(费)种类");
        writer.addHeaderAlias("jsyj", "计税金额");
        writer.addHeaderAlias("jkqx", "缴款期限");
        writer.addHeaderAlias("yzpzxh", "应征凭证序号");
        writer.addHeaderAlias("skzlmc", "税款种类");
        writer.addHeaderAlias("sl1", "税率");
        writer.addHeaderAlias("skzt", "税款状态");
        writer.addHeaderAlias("ybtse", "实缴金额");
        writer.addHeaderAlias("yzfsrq", "缴款发生日期");
        writer.addHeaderAlias("zsxmmc", "征收项目");
        writer.addHeaderAlias("rkrq", "入库日期 YYYY-MM-DD");
        writer.addHeaderAlias("ssqq", "所属日期起");
        writer.addHeaderAlias("ssqz", "所属日期止");
        writer.addHeaderAlias("cwbblxDm", "财务报表类型代码");
        writer.addHeaderAlias("zlbsxlmc", "资料报送类型名称");
        writer.addHeaderAlias("xm", "项目名称");
        writer.addHeaderAlias("mc", "序号");
        writer.addHeaderAlias("bys", "本月数");
        writer.addHeaderAlias("bnljje", "本年累计金额");
        writer.addHeaderAlias("sqje", "上期金额");
        writer.addHeaderAlias("zcxmmc", "资产项目名称");
        writer.addHeaderAlias("qmyeZc", "期末余额资产");
        writer.addHeaderAlias("ncyeZc", "年初余额资产");
        writer.addHeaderAlias("qyxmmc", "权益项目名称");
        writer.addHeaderAlias("qmyeQy", "期末余额权益");
        writer.addHeaderAlias("ncyeQy", "年初余额权益");
        writer.addHeaderAlias("dqxzqsje", "当期新增欠税金额");
        writer.addHeaderAlias("zsxmMc", "征收项目名称");
        writer.addHeaderAlias("zspmMc", "征收品目名称");
        writer.addHeaderAlias("qsye", "欠税余额");
        writer.addHeaderAlias("skssqq", "税款所属期起");
        writer.addHeaderAlias("skssqz", "税款所属期止");
        writer.addHeaderAlias("djrq", "登记日期");
        writer.addHeaderAlias("lrrq", "录入日期");
        writer.addHeaderAlias("sswflxmc", "违法违章类型名称");
        writer.addHeaderAlias("wfxwmc", "违法行为名称");
        writer.addHeaderAlias("sswfxwclztmc", "违法违章状态名称");
        writer.addHeaderAlias("sswfsdmc", "税收违法手段名称");
        writer.addHeaderAlias("ssqjq", "所属期间起");
        writer.addHeaderAlias("ssqjz", "所属期间止");
        writer.addHeaderAlias("wfss", "违法事实");
        writer.addHeaderAlias("clcfsj", "处理处罚时间");
    }

    // 异常处理
    private void handleExportException(HttpServletResponse response, String message, int status) {
        try {
            response.reset();
            response.setStatus(status);
            response.setContentType("application/json;charset=utf-8");

            JSONObject errorObj = new JSONObject();
            errorObj.put("code", status);
            errorObj.put("message", message);

            try (ServletOutputStream out = response.getOutputStream()) {
                out.write(errorObj.toString().getBytes(StandardCharsets.UTF_8));
                out.flush();
            }
        } catch (IOException e) {
            log.error("写入错误响应失败", e);
        }
    }

    /**
     * 新增保存财务数据接口
     */
    @ApiOperation("新增财务数据")
    @ApiImplicitParam(name = "apiFinance", value = "财务数据", dataType = "ApiFinance")
    @Log(title = "财务数据", businessType = BusinessType.INSERT, operatorType = OperatorType.WEB)
    @PostMapping
    public AjaxResult addSave(ApiFinance apiFinance) {
        apiFinance.setCreateBy(ShiroUtils.getLoginName());
        apiFinance.setCreateTime(new Date());
        apiFinance.setUpdateBy(ShiroUtils.getLoginName());
        apiFinance.setUpdateTime(new Date());
        return toAjax(apiFinanceService.insertApiFinance(apiFinance));
    }

    /**
     * 修改保存财务数据接口
     */
    @ApiOperation("修改财务数据")
    @ApiImplicitParam(name = "apiFinance", value = "财务数据", dataType = "ApiFinance")
    @Log(title = "财务数据", businessType = BusinessType.UPDATE, operatorType = OperatorType.WEB)
    @PutMapping
    public AjaxResult update(ApiFinance apiFinance) {
        if (StringUtils.isNull(apiFinance) || StringUtils.isNull(apiFinance.getId())) {
            return AjaxResult.error("主键id不能为空");
        }
        apiFinance.setUpdateBy(ShiroUtils.getLoginName());
        apiFinance.setUpdateTime(new Date());
        return toAjax(apiFinanceService.updateApiFinance(apiFinance));
    }

    /**
     * 删除财务数据接口
     */
    @ApiOperation("删除财务数据")
    @ApiImplicitParam(name = "ids", value = "主键id,多条以英文逗号分隔", required = true, dataType = "String", paramType = "path")
    @Log(title = "财务数据", businessType = BusinessType.DELETE, operatorType = OperatorType.WEB)
    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable String ids) {
        return toAjax(apiFinanceService.deleteApiFinanceByIds(ids));
    }


}