ContractServiceImpl.java 50.8 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
package vion.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.collection.set.SetUtil;
import org.dromara.hutool.core.comparator.CompareUtil;
import org.dromara.hutool.core.date.DateUnit;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.http.client.HttpDownloader;
import org.dromara.hutool.http.client.Request;
import org.dromara.hutool.http.meta.Method;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vion.dto.ContractDTO;
import vion.dto.RContractTeamDTO;
import vion.mapper.ContractMapper;
import vion.mapper.SettlementDiffMapper;
import vion.model.*;
import vion.model.Dictionary;
import vion.service.*;
import vion.third.DingMod;
import vion.vo.*;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author HlQ
 * @date 2023/11/29
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Contract> implements IContractService {

    private final IFileService fileService;
    private final IContractPaymentService contractPaymentService;
    private final IRContractStoreService contractStoreService;
    private final IContractLogService contractLogService;
    private final IRContractTeamService contractTeamService;
    private final IRContractUserService contractUserService;
    private final IRContractProductService contractProductService;
    // 引入 settlementDiffService 会循环依赖
    private final SettlementDiffMapper settlementDiffMapper;
    private final DingMod dingMod;
    private final Converter converter;

    @Value("${fileUrl:}")
    private String fileUrl;
    @Value("${xbongbong.corpid}")
    private String corpId;
    @Value("${xbongbong.token}")
    private String token;

    @Override
    public Page<ContractVO> list(ContractDTO dto) {
        Result result = getResult(dto);

        Page<ContractVO> page = Page.of(dto.getPageNum(), dto.getPageSize());
        Opt.ofNullable(dto.getOrderItem())
                .ifPresent(page::addOrder);
        Page<ContractVO> contractVOList = this.selectJoinListPage(page, ContractVO.class, result.wrapper);

        var idList = Opt.ofEmptyAble(contractVOList.getRecords())
                .map(r -> r.stream().map(ContractVO::getId).collect(Collectors.toList()))
                .orElse(ListUtil.empty());

        // 结算差异
        Opt.ofEmptyAble(idList)
                .map(l -> settlementDiffMapper.selectList(Wrappers.<SettlementDiff>lambdaQuery()
                        .in(SettlementDiff::getContractId, l)))
                .map(list -> list.stream().collect(Collectors.groupingBy(SettlementDiff::getContractId, Collectors.reducing(BigDecimal.ZERO, SettlementDiff::getSettlementDiff, BigDecimal::add))))
                .ifPresent(map -> contractVOList.getRecords().forEach(vo -> vo.setDiffAmount(map.getOrDefault(vo.getId(), BigDecimal.ZERO))));
        // 合同绑定销售
        Opt.ofEmptyAble(idList)
                .map(l -> contractUserService.lambdaQuery()
                        .in(RContractUser::getContractId, l)
                        .list())
                .map(list -> list.stream().collect(Collectors.groupingBy(RContractUser::getContractId)))
                .ifPresent(map -> contractVOList.getRecords().forEach(vo -> map.getOrDefault(vo.getId(), ListUtil.empty()).stream()
                        .max(Comparator.comparing(RContractUser::getEnterDate))
                        .map(RContractUser::getUsername)
                        .ifPresent(vo::setSaleName)));

        if (!result.roleCodeList.contains("admin") && !result.roleCodeList.contains("xiaoshou") && !result.roleCodeList.contains("caiwu")) {
            contractVOList.getRecords().forEach(vo -> {
                vo.setTotalAmount(null);
                vo.setPaidAmount(null);
                vo.setReceivableAmount(null);
                vo.setOutstandingAmount(null);
                vo.setInvoiceAmount(null);
                vo.setDiffAmount(null);
            });
        }
        completeStoreName(contractVOList.getRecords());
        return contractVOList;
    }

    @Override
    public Page<ContractVO> listPart(ContractDTO dto) {
        List<Long> ids = Opt.ofNullable(dto.getStoreId())
                .map(storeId -> contractStoreService.listObjs(Wrappers.<RContractStore>lambdaQuery().select(RContractStore::getContractId).eq(RContractStore::getStoreId, dto.getStoreId()), o -> Long.valueOf(o.toString())))
                .filter(CollUtil::isNotEmpty)
                .orElse(ListUtil.of(0L));

        Page<Contract> contractList = this.lambdaQuery(converter.convert(dto, Contract.class))
                .select(Contract::getId, Contract::getName, Contract::getContractNo, Contract::getType, Contract::getSignDate, Contract::getWarrantyPeriod, Contract::getFinalDate, Contract::getStatus, Contract::getSaleName, Contract::getCustomerName, Contract::getMaintainSdate, Contract::getMaintainEdate)
                .in(ObjUtil.isNotNull(dto.getStoreId()), Contract::getId, ids)
                .orderByDesc(Contract::getEntryTime)
                .page(Page.of(dto.getPageNum(), dto.getPageSize()));
        List<ContractVO> contractVOList = converter.convert(contractList.getRecords(), ContractVO.class);
        completeStoreName(contractVOList);
        return Page.<ContractVO>of(contractList.getCurrent(), contractList.getSize(), contractList.getTotal()).setRecords(contractVOList);
    }

    /**
     * 查出合同关联的项目名
     *
     * @param contractVOList list
     */
    private void completeStoreName(List<ContractVO> contractVOList) {
        Map<Long, List<Long>> contractStoreIdsMap = Opt.ofEmptyAble(contractVOList)
                .map(list -> list.stream().map(ContractVO::getId).collect(Collectors.toList()))
                .map(contractIds -> contractStoreService.list(Wrappers.<RContractStore>lambdaQuery().in(RContractStore::getContractId, contractIds)))
                .map(contractStoreList -> contractStoreList.stream().collect(Collectors.groupingBy(RContractStore::getContractId, Collectors.mapping(RContractStore::getStoreId, Collectors.toList()))))
                .orElse(MapUtil.empty());

        Opt.of(contractStoreIdsMap)
                .filter(MapUtil::isNotEmpty)
                .map(map -> map.values().stream().flatMap(List::stream).collect(Collectors.toList()))
                .map(storeIds -> Db.listByIds(storeIds, Store.class))
                .map(storeList -> storeList.stream().collect(Collectors.toMap(Store::getId, Function.identity())))
                .ifPresent(storeId2StoreMap -> contractVOList.forEach(contractVO -> {
                    if (contractStoreIdsMap.containsKey(contractVO.getId())) {
                        List<StoreVO> storeVOS = converter.convert(contractStoreIdsMap.get(contractVO.getId()).stream().map(storeId2StoreMap::get).collect(Collectors.toList()), StoreVO.class);
                        contractVO.setStoreVOS(storeVOS);
                    }
                }));
    }

    @Override
    public ContractVO getVOById(Long id) {
        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
        Set<String> roleCodeList = Opt.ofEmptyAble(userVO.getRoleVOList())
                .map(l -> l.stream().map(RoleVO::getCode).collect(Collectors.toSet()))
                .orElse(SetUtil.zero());
        MPJLambdaWrapper<Contract> wrapper = new MPJLambdaWrapper<Contract>()
                .selectAll(Contract.class)
                .selectCollection(ContractLog.class, ContractVO::getContractLogs)
                .leftJoin(ContractLog.class, ContractLog::getContractNo, Contract::getContractNo)
                .eq(Contract::getId, id);
        ContractVO contractVO = this.selectJoinOne(ContractVO.class, wrapper);
        if (!roleCodeList.contains("admin") && !roleCodeList.contains("xiaoshou") && !roleCodeList.contains("caiwu")) {
            contractVO.setTotalAmount(null);
            contractVO.setPaidAmount(null);
            contractVO.setReceivableAmount(null);
            contractVO.setOutstandingAmount(null);
            contractVO.setInvoiceAmount(null);
        }
        // 合同关联产品
        var contractProducts = contractProductService.lambdaQuery()
                .eq(RContractProduct::getContractNo, contractVO.getContractNo())
                .list();
        contractVO.setContractProducts(contractProducts);
        return contractVO;
    }

    @Override
    public ContractVO getByNo(String no) {
        Contract contract = this.lambdaQuery()
                .select(Contract::getId, Contract::getName, Contract::getContractNo, Contract::getType, Contract::getSignDate, Contract::getWarrantyPeriod, Contract::getFinalDate, Contract::getStatus, Contract::getSaleName, Contract::getCustomerName)
                .eq(Contract::getContractNo, no)
                .one();
        ContractVO contractVO = converter.convert(contract, ContractVO.class);
        Assert.notNull(contractVO, "合同不存在");
        MPJLambdaWrapper<RContractStore> wrapper = new MPJLambdaWrapper<RContractStore>()
                .select(Store::getId, Store::getName)
                .leftJoin(Store.class, Store::getId, RContractStore::getStoreId)
                .eq(RContractStore::getContractId, contract.getId());
        List<StoreVO> storeVOS = contractStoreService.selectJoinList(StoreVO.class, wrapper);
        contractVO.setStoreVOS(storeVOS);
        return contractVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateById(Long id, String contractNo, ContractDTO dto) {
        Contract existContract = new Contract();
        if (ObjUtil.isNotNull(id)) {
            existContract = this.getById(id);
        } else if (StrUtil.isNotBlank(contractNo)) {
            existContract = this.lambdaQuery().eq(Contract::getContractNo, contractNo).one();
        }
        Assert.isFalse(BeanUtil.isEmpty(existContract), "合同不存在");

        // todo 如果当前合同进度在要修改的进度前,此时不能修改合同进度。e.g 当前合同进度是项目验收,此时传参过来到货,那么不能修改

        Contract contract = converter.convert(dto, Contract.class);
        Long contractId = existContract.getId();
        String existContractNo = existContract.getContractNo();
        contract.setId(contractId);
        contractPaymentService.calMoney(existContract, contract);
        if (this.updateById(contract)) {
            Opt.ofNullable(dto.getNodeDate())
                    .ifPresent(date -> contractPaymentService.lambdaUpdate()
                            .set(ContractPayment::getNodeDate, date)
                            .eq(ContractPayment::getContractId, contractId)
                            .eq(ContractPayment::getPaymentType, dto.getStatus())
                            .update(new ContractPayment()));

            UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
            Contract finalExistContract = existContract;
            Opt.ofNullable(dto.getStatus())
                    .ifPresent(status -> {
                        String useridStr = Opt.ofEmptyAble(contractUserService.lambdaQuery()
                                        .eq(RContractUser::getContractNo, existContractNo).list())
                                .map(l -> l.stream().map(RContractUser::getContractNo).collect(Collectors.joining(",")))
                                .orElse("");

                        ContractLog contractLog = new ContractLog();
                        contractLog.setContractNo(existContractNo);
                        if (status == 1) {
                            contractLog.setContent("合同:已签订");
                        } else if (status == 2) {
                            contractLog.setContent("合同:已到货");
                        } else if (status == 3) {
                            contractLog.setContent("合同:系统验收");
                            dingMod.workMsg(buildMsg(useridStr, dto, finalExistContract, "系统验收(初验)"));
                        } else if (status == 4) {
                            contractLog.setContent("合同:项目验收");
                            dingMod.workMsg(buildMsg(useridStr, dto, finalExistContract, "项目验收(终验)"));
                        } else if (status == 5) {
                            contractLog.setContent("合同:质保");
                        } else if (status == 6) {
                            contractLog.setContent("合同:第一笔维保款");
                        } else if (status == 7) {
                            contractLog.setContent("合同:第二笔维保款");
                        } else if (status == 8) {
                            contractLog.setContent("合同:第三笔维保款");
                        } else if (status == 9) {
                            contractLog.setContent("合同:维保进度款");
                        } else if (status == 10) {
                            contractLog.setContent("合同:维保验收款");
                        }
                        contractLog.setOperator(userVO.getId());
                        contractLogService.save(contractLog);
                    });

            Opt.ofNullable(dto.getFiles())
                    .ifPresent(fileList ->
                            Arrays.stream(fileList).forEach(infile -> {
                                //上传url地址
                                String orgName = infile.getOriginalFilename();
                                String mainName = FileNameUtil.mainName(orgName);
                                String fileExt = FileNameUtil.extName(orgName);
                                String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS"), fileExt);
                                String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contract.getId() + FileUtil.FILE_SEPARATOR + filename;
                                File file = FileUtil.touch(path);
                                try {
                                    infile.transferTo(file);
                                } catch (IOException e) {
                                    log.error("保存文件出错", e);
                                }

                                FileInfo fileInfo = new FileInfo();
                                fileInfo.setStoreId(-1L);
                                fileInfo.setSourceId(contract.getId());
                                fileInfo.setSourceType(dto.getSourceType());
                                fileInfo.setContractId(contract.getId());
                                fileInfo.setName(filename);
                                fileInfo.setUrl(path);
                                fileInfo.setType(fileExt);
                                fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                                fileInfo.setUploader(userVO.getUsername());
                                fileService.save(fileInfo);
                            }));
            return "更新成功";
        } else {
            return "更新失败";
        }
    }

    @Override
    public JSONObject calAmount(ContractDTO dto) {
        Result result = getResult(dto);

        JSONObject obj = JSONUtil.ofObj()
                .set("totalAmount", 0)
                .set("paidAmount", 0)
                .set("recAmount", 0)
                .set("outAmount", 0)
                .set("invoiceAmount", 0);
        if (!result.roleCodeList.contains("admin") && !result.roleCodeList.contains("xiaoshou") && !result.roleCodeList.contains("caiwu")) {
            return obj;
        }
        List<Contract> contracts = this.selectJoinList(Contract.class, result.wrapper);

        Opt.ofEmptyAble(contracts)
                .ifPresent(list -> {
                    BigDecimal totalAmount = list.stream().map(Contract::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal paidAmount =
                            list.stream().map(v -> CompareUtil.max(BigDecimal.ZERO, v.getPaidAmount())).reduce(BigDecimal.ZERO,
                                    BigDecimal::add);
                    BigDecimal recAmount = list.stream().map(v -> CompareUtil.max(BigDecimal.ZERO, v.getReceivableAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal outAmount = list.stream().map(Contract::getOutstandingAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

                    List<String> noList = list.stream().map(Contract::getContractNo).collect(Collectors.toList());
                    List<BigDecimal> invoices = Db.listObjs(Wrappers.lambdaQuery(Invoice.class).select(Invoice::getInvoiceAmount).in(BeanUtil.isNotEmpty(dto), Invoice::getContractNo, noList), Invoice::getInvoiceAmount);
                    BigDecimal invoiceAmount = invoices.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

                    obj.set("totalAmount", totalAmount)
                            .set("paidAmount", paidAmount)
                            .set("recAmount", recAmount)
                            .set("outAmount", outAmount)
                            .set("invoiceAmount", invoiceAmount);
                });
        return obj;
    }

    @Override
    public Map<String, Object> analyze(ContractDTO dto) {
        List<Contract> contractList = this.lambdaQuery(converter.convert(dto, Contract.class))
                .gt(Contract::getReceivableAmount, 0)
                .gt(Contract::getTotalAmount, 0)
                .between(ArrayUtil.isAllNotNull(dto.getSignDateStart(), dto.getSignDateEnd()), Contract::getSignDate, dto.getSignDateStart(), dto.getSignDateEnd())
                .list();
        if (CollUtil.isEmpty(contractList)) {
            return new JSONObject();
        }

        Map<Long, List<ContractPayment>> id2PaymentMap = Opt.ofEmptyAble(contractPaymentService
                        .lambdaQuery().gt(ContractPayment::getPaymentRatio, 0)
                        .list())
                .map(list -> list.stream().collect(Collectors.groupingBy(ContractPayment::getContractId)))
                .orElse(MapUtil.empty());
        if (MapUtil.isEmpty(id2PaymentMap)) {
            return new JSONObject();
        }
        List<FinancialAgeVO> financialAgeVOList = new ArrayList<>();

        contractList.forEach(c -> {
            List<ContractPayment> contractPaymentList = id2PaymentMap.get(c.getId());
            if (CollUtil.isEmpty(contractPaymentList)) {
                return;
            }
            BigDecimal totalAmount = c.getTotalAmount();
            BigDecimal paidAmount = c.getPaidAmount();
            Map<Integer, Date> type2DateMap = contractPaymentList.stream().filter(cp -> cp.getPaymentType() <= c.getStatus()).collect(HashMap::new, (m, v) -> m.put(v.getPaymentType(), v.getPaymentDate()), HashMap::putAll);

            Map<Integer, BigDecimal> type2AmountMap = contractPaymentList.stream().filter(cp -> cp.getPaymentType() <= c.getStatus()).collect(Collectors.toMap(ContractPayment::getPaymentType, v -> NumberUtil.mul(v.getPaymentRatio(), totalAmount)));
            TreeMap<Integer, BigDecimal> sortMap = MapUtil.sort(type2AmountMap, Comparator.comparingInt(Integer::intValue));

            for (Map.Entry<Integer, BigDecimal> entry : sortMap.entrySet()) {
                Integer type = entry.getKey();
                BigDecimal curAmount = entry.getValue();
                if (CompareUtil.gt(paidAmount, BigDecimal.ZERO)) {
                    paidAmount = NumberUtil.sub(paidAmount, curAmount);
                    if (NumberUtil.equals(paidAmount, BigDecimal.ZERO)) {
                        continue;
                    }
                }
                if (CompareUtil.le(paidAmount, BigDecimal.ZERO)) {
                    FinancialAgeVO financialAgeVO = new FinancialAgeVO();
                    financialAgeVO.setContractNo(c.getContractNo());
                    financialAgeVO.setContractName(c.getName());
                    financialAgeVO.setStatus(type);
                    financialAgeVO.setAmount(NumberUtil.equals(paidAmount, BigDecimal.ZERO) ? curAmount : BigDecimal.valueOf(Math.abs(paidAmount.doubleValue())));
                    Opt.ofNullable(type2DateMap.get(type)).ifPresent(
                            date -> {
                                financialAgeVO.setPayableDate(date);
                                long age = DateUtil.between(date, new Date(), DateUnit.DAY, true);
                                financialAgeVO.setAge(((int) age));
                            }
                    );
                    financialAgeVOList.add(financialAgeVO);
                    paidAmount = BigDecimal.ZERO;
                }
            }
        });
        Map<String, Object> map = MapUtil.<String, Object>builder()
                .put("totalAmount", financialAgeVOList.stream().map(FinancialAgeVO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add)).build();
        // 手动分页 todo hutool 6.0 暂时没有
        int[] transToStartEnd = {(dto.getPageNum() - 1) * dto.getPageSize(),
                (dto.getPageNum() - 1) * dto.getPageSize() + dto.getPageSize()};
        Page<FinancialAgeVO> financialAgeVOPage = Page.<FinancialAgeVO>of(dto.getPageNum(), dto.getPageSize(), financialAgeVOList.size())
                .setRecords(CollUtil.sub(financialAgeVOList, transToStartEnd[0], transToStartEnd[1]));
        map.put("list", financialAgeVOPage);
        return map;
    }

    @Override
    public String dispatch(RContractTeamDTO dto) {
        RContractTeam rContractTeam = converter.convert(dto, RContractTeam.class);
        if (contractTeamService.save(rContractTeam)) {
            // todo 推送钉钉消息到王平川,要支持可配置吗?
            Contract contract = this.getById(dto.getContractId());
            dingMod.workMsg(buildMsg("01005444040832705136", contract, dto.getApplicantName()));
            return "派工成功,待分配施工队。";
        }
        return "派工失败";
    }

    @Override
    public Page<RContractUser> getSaleList(RContractUser dto) {
        return contractUserService.lambdaQuery(dto).orderByDesc(RContractUser::getEnterDate).page(Page.of(dto.getPageNum(), dto.getPageSize()));
    }

    @Override
    public String assignSale(RContractUser contractUser) {
        return contractUserService.save(contractUser) ? "分配成功" : "分配失败";
    }

    @Override
    public String unbindSale(RContractUser contractUser) {
        return contractUserService.remove(Wrappers.<RContractUser>lambdaQuery().eq(RContractUser::getContractId, contractUser.getContractId()).eq(RContractUser::getUserId, contractUser.getUserId())) ? "解绑成功" : "解绑失败";
    }

    @Override
    public List<RContractProduct> getProduct(String contractNo) {
        return contractProductService.lambdaQuery().eq(RContractProduct::getContractNo, contractNo).list();
    }

    @Override
    public String createContract(String contractJson) {
        var sha256 = SecureUtil.sha256(contractJson + token);
        var res = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                .header("sign", sha256)
                .body(contractJson)
                .method(Method.POST)
                .send();
        var body = res.bodyStr();
        var jobj = JSONUtil.parseObj(body);
        if (jobj.getInt("code") != 1) {
            log.error("调用CRM接口创建合同失败,错误原因:{}", body);
            return "创建合同失败";
        }
        return "合同创建成功";
    }

    @Override
    public JSONObject getCRMProduct(String name, String code, Integer page, Integer pageSize) {
        var conditions = JSONUtil.ofArray().put(JSONUtil.ofObj()
                .set("attr", "num_3")
                .set("symbol", "noequal")
                .set("value", new int[]{0}));
        if (StrUtil.isNotBlank(name)) {
            conditions.put(JSONUtil.ofObj().set("attr", "text_1").set("symbol", "like").set("value", new String[]{name}));
        }
        if (StrUtil.isNotBlank(code)) {
            conditions.put(JSONUtil.ofObj().set("attr", "serialNo").set("symbol", "like").set("value", new String[]{code}));
        }
        var json = JSONUtil.ofObj()
                .set("corpid", "ding6bb660048f7ae2dcee0f45d8e4f7c288")
                .set("page", page)
                .set("pageSize", pageSize)
                .set("conditions", conditions);

        var res = Request.of("https://proapi.xbongbong.com/pro/v2/api/product/list")
                .header("sign", SecureUtil.sha256(json.toString() + token))
                .body(json.toString())
                .method(Method.POST)
                .send();
        var body = res.bodyStr();
        var jobj = JSONUtil.parseObj(body);
        if (jobj.getInt("code") != 1) {
            log.error("调用CRM接口获取产品列表失败,错误原因:{}", body);
            return JSONUtil.ofObj();
        }
        return JSONUtil.ofObj().set("records", jobj.getJSONObject("result").getJSONArray("list"))
                .set("current", page)
                .set("size", pageSize)
                .set("total", jobj.getJSONObject("result").getInt("totalCount"))
                .set("pages", jobj.getJSONObject("result").getInt("totalPage"));
    }

    @Override
    public String syncContractFile(String[] contractNoList) {
        log.info("同步销帮帮合同文件[开始]");
        // 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同
        var conditions = JSONUtil.ofArray()
                .put(JSONUtil.ofObj()
                        .set("attr", "date_3")
                        .set("symbol", "greaterequal")
                        .set("value", new String[]{"1715356800"}));
        if (ArrayUtil.isNotEmpty(contractNoList)) {
            conditions.put(JSONUtil.ofObj()
                    .set("attr", "serialNo")
                    .set("symbol", "in")
                    .set("value", contractNoList));
        }
        var json = JSONUtil.ofObj()
                .set("conditions", conditions)
                .set("corpid", corpId)
                .set("formId", 8429903)
                .set("pageSize", 100);
        var res = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                .header("sign", SecureUtil.sha256(json.toString() + token))
                .body(json.toString())
                .method(Method.POST)
                .send();
        var jobO = JSONUtil.parseObj(res.bodyStr());
        if (jobO.getInt("code") != 1) {
            var errorInfo = StrUtil.format("获取合同列表失败,错误原因:{}", jobO);
            log.error(errorInfo);
            return errorInfo;
        }
        Integer cnt = jobO.getJSONObject("result").getInt("totalCount");
        Integer page = jobO.getJSONObject("result").getInt("totalPage");
        if (NumberUtil.equals(cnt, 0)) {
            return "没有需要插入或更新的合同";
        }
        var jsonArray = jobO.getJSONObject("result").getJSONArray("list");
        var fileList = jsonArray.stream().map(v -> {
            var fileArr = JSONUtil.parseObj(v).getJSONObject("data").getJSONArray("file_1");
            var contractNo = JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo");
            return JSONUtil.ofObj().set("contractNo", contractNo).set("fileArr", fileArr);
        }).collect(Collectors.toList());

        for (int i = 2; i <= page; i++) {
            var jsonR = JSONUtil.ofObj()
                    .set("conditions", conditions)
                    .set("corpid", corpId)
                    .set("formId", 8429903)
                    .set("page", i)
                    .set("pageSize", 100);
            var resR = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                    .header("sign", SecureUtil.sha256(jsonR.toString() + token))
                    .body(jsonR.toString())
                    .method(Method.POST)
                    .send();
            var jobR = JSONUtil.parseObj(resR.bodyStr());
            var jsonArrR = jobR.getJSONObject("result").getJSONArray("list");
            var fileListR = jsonArrR.stream().map(v -> {
                var fileArr = JSONUtil.parseObj(v).getJSONObject("data").getJSONArray("file_1");
                var contractNo = JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo");
                return JSONUtil.ofObj().set("contractNo", contractNo).set("fileArr", fileArr);
            }).toList();
            fileList.addAll(fileListR);
        }

        var contractList = this.lambdaQuery().likeRight(Contract::getContractNo, "SC").list();
        var contractNo2IdMap = contractList.stream().collect(Collectors.toMap(Contract::getContractNo, Contract::getId));
        var fileInfoList = fileService.lambdaQuery().in(FileInfo::getContractId, contractNo2IdMap.values()).eq(FileInfo::getSourceType, 5).list();
        // 合同id -> sha256 的 List
        var contractId2Sha256Map = fileInfoList.stream().collect(Collectors.groupingBy(FileInfo::getContractId,
                Collectors.mapping(FileInfo::getSha256, Collectors.toList())));

        List<FileInfo> saveFileInfoList = new ArrayList<>();
        for (JSONObject entries : fileList) {
            var contractNo = entries.getStr("contractNo");
            var fileArr = entries.getJSONArray("fileArr");
            if (ObjUtil.isNull(fileArr) || fileArr.isEmpty()) {
                log.info("合同:{},没有文件", contractNo);
                continue;
            }
            var contractId = contractNo2IdMap.get(contractNo);
            if (ObjUtil.isNull(contractId)) {
                log.info("合同:{},不存在,还未同步", contractNo);
                continue;
            }

            for (Object o : fileArr) {
                var fileObj = JSONUtil.parseObj(o);
                var filename = fileObj.getStr("filename");
                String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contractId + FileUtil.FILE_SEPARATOR + filename;
                var bytes = HttpDownloader.downloadBytes(fileObj.getStr("attachIndex"));
                var sha256 = SecureUtil.sha256().digestHex(bytes).toUpperCase();
                // sha256 对应的文件不存在已有的文件列表,才保存
                if (contractId2Sha256Map.getOrDefault(contractId, ListUtil.empty()).contains(sha256)) {
                    log.info("合同:{},文件已存在", contractNo);
                    continue;
                }
                var file = FileUtil.writeBytes(bytes, path);
                log.info("合同:{},文件存入路径:{}", contractNo, path);
                FileInfo fileInfo = new FileInfo();
                fileInfo.setStoreId(-1L);
                fileInfo.setSourceId(contractId);
                fileInfo.setSourceType(5);
                fileInfo.setContractId(contractId);
                fileInfo.setName(filename);
                fileInfo.setUrl(path);
                fileInfo.setType(FileNameUtil.extName(file));
                fileInfo.setSha256(sha256);
                fileInfo.setUploader("销帮帮同步");
                saveFileInfoList.add(fileInfo);
            }
        }
        fileService.saveBatch(saveFileInfoList);
        log.info("同步销帮帮合同文件[完成]");
        return "销帮帮合同文件同步完成,请核对已同步文件!";
    }

    private Result getResult(ContractDTO dto) {
        // 查询已关联项目的合同id
        List<Long> contractIdList = dto.getSwitchFlag() == 1 ?
                contractStoreService.listObjs(Wrappers.<RContractStore>lambdaQuery()
                        .select(RContractStore::getContractId), o -> Long.valueOf(o.toString()))
                : ListUtil.empty();
        // 根据产品线查出关联的合同
        List<Long> lineContractIdList = Opt.ofEmptyAble(dto.getProductLines())
                .map(pl -> Db.listObjs(Wrappers.lambdaQuery(Store.class).in(Store::getProductLine, pl), Store::getId))
                .map(storeIds -> contractStoreService.listObjs(Wrappers.<RContractStore>lambdaQuery().select(RContractStore::getContractId).in(RContractStore::getStoreId, storeIds), o -> Long.valueOf(o.toString())))
                .orElse(new ArrayList<>());
        // 根据当前登录用户的角色获取用户名
        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
        Set<String> roleCodeList = Opt.ofEmptyAble(userVO.getRoleVOList())
                .map(l -> l.stream().map(RoleVO::getCode).collect(Collectors.toSet()))
                .orElse(SetUtil.zero());
        Assert.notEmpty(roleCodeList, "当前用户角色不详,请联系管理员");
        String curName = "";
        boolean isPerm = !roleCodeList.contains("admin") && !roleCodeList.contains("shangwu") && !roleCodeList.contains("caiwu");
        if (isPerm) {
            // 不是以上三个角色,只能访问自己相关的合同
            curName = userVO.getUsername();
        }

        // 根据查询条件的销售人查询关联的合同
        List<Long> contractUserIdList1 = Opt.ofBlankAble(dto.getSaleName())
                .map(name -> contractUserService.listObjs(Wrappers.<RContractUser>lambdaQuery()
                        .select(RContractUser::getContractId).eq(RContractUser::getUsername, name), o -> Long.valueOf(o.toString())))
                .orElse(new ArrayList<>());
        // 根据查询条件的销售人查询其销售的合同
        List<Long> contractUserIdList2 = Opt.ofBlankAble(dto.getSaleName())
                .map(name -> this.listObjs(Wrappers.<Contract>lambdaQuery()
                        .select(Contract::getId).eq(Contract::getSaleName, name), o -> Long.valueOf(o.toString())))
                .orElse(new ArrayList<>());
        // 查询共同销售人为当前用户的关联合同
        List<Long> contractUserIdList3 = Opt.ofBlankAble(curName)
                .map(name -> contractUserService.listObjs(Wrappers.<RContractUser>lambdaQuery()
                        .select(RContractUser::getContractId).eq(RContractUser::getUsername, name), o -> Long.valueOf(o.toString())))
                .orElse(new ArrayList<>());
        // 查询合同销售人为当前用户的合同
        List<Long> contractUserIdList4 = Opt.ofBlankAble(curName)
                .map(name -> this.listObjs(Wrappers.<Contract>lambdaQuery()
                        .select(Contract::getId).eq(Contract::getSaleName, name), o -> Long.valueOf(o.toString())))
                .orElse(new ArrayList<>());
        Collection<Long> queryContractUserIdList = ListUtil.addAllIfNotContains(contractUserIdList1, contractUserIdList2);
        Collection<Long> curContractUserIdList = ListUtil.addAllIfNotContains(contractUserIdList3, contractUserIdList4);
        Set<Long> allContractUserIdList;
        if (StrUtil.isNotBlank(curName) && StrUtil.isNotBlank(dto.getSaleName())) {
            // 当前用户和查询条件的销售人都存在,取交集
            allContractUserIdList = CollUtil.intersectionDistinct(queryContractUserIdList, curContractUserIdList);
        } else {
            allContractUserIdList = CollUtil.unionDistinct(queryContractUserIdList, curContractUserIdList);
        }

        Set<Long> finalIdSet;
        if (isPerm) {
            // 不是以上三个角色,只能访问自己相关的合同或自己产品线相关的合同
            if (CollUtil.isNotEmpty(dto.getProductLines())) {
                finalIdSet = CollUtil.intersectionDistinct(lineContractIdList, allContractUserIdList);
            } else {
                finalIdSet = CollUtil.unionDistinct(lineContractIdList, allContractUserIdList);
            }
            if (CollUtil.isEmpty(finalIdSet)) {
                // 根据条件筛选要查询的合同为空,集合补元素 -1,防止数据库查询出错
                finalIdSet.add(-1L);
            }
        } else {
            if (StrUtil.isNotBlank(dto.getSaleName()) && CollUtil.isNotEmpty(dto.getProductLines())) {
                finalIdSet = CollUtil.intersectionDistinct(lineContractIdList, allContractUserIdList);
            } else {
                finalIdSet = CollUtil.unionDistinct(lineContractIdList, allContractUserIdList);
            }
            if ((StrUtil.isNotBlank(dto.getSaleName()) || CollUtil.isNotEmpty(dto.getProductLines())) && CollUtil.isEmpty(finalIdSet)) {
                finalIdSet.add(-1L);
            }
        }

        // 前端传参中的 saleName 字段已单独处理,这里置空,不参与下一步的 converter.convert
        dto.setSaleName(null);
        MPJLambdaWrapper<Contract> wrapper = new MPJLambdaWrapper<>(converter.convert(dto, Contract.class))
                .selectAll(Contract.class)
                .in(CollUtil.isNotEmpty(finalIdSet), Contract::getId, finalIdSet)
                .notIn(CollUtil.isNotEmpty(contractIdList), Contract::getId, contractIdList)
                .between(ArrayUtil.isAllNotNull(dto.getSignDateStart(), dto.getSignDateEnd()), Contract::getSignDate, dto.getSignDateStart(), dto.getSignDateEnd());
        if (StrUtil.isNotBlank(dto.getOperator()) && ObjUtil.isNotNull(dto.getAmount())) {
            String ope = dto.getOperator();
            if (">".equals(ope)) {
                wrapper.gt(getCol(dto), dto.getAmount());
            } else if ("<".equals(ope)) {
                wrapper.lt(getCol(dto), dto.getAmount());
            } else {
                wrapper.eq(getCol(dto), dto.getAmount());
            }
        }
        return new Result(roleCodeList, wrapper);
    }

    private SFunction<Contract, Object> getCol(ContractDTO dto) {
        if (dto.getTotalAmount() != null) {
            return Contract::getTotalAmount;
        } else if (dto.getPaidAmount() != null) {
            return Contract::getPaidAmount;
        } else if (dto.getReceivableAmount() != null) {
            return Contract::getReceivableAmount;
        } else {
            return Contract::getOutstandingAmount;
        }
    }

    JSONObject buildMsg(String userid, Contract contract, String applicantName) {
        var jsonObj = JSONUtil.ofObj()
                .set("agent_id", 2358374016L)
                .set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "合同施工申请,请及时处理哦~_~");
        String template = """
                #### 合同编号: **{}**" +
                #### 合同名称:**{}**
                #### 申请人:{}
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                contract.getContractNo(), contract.getName(), applicantName, DateUtil.now());
        content.set("markdown", markdown);

        msg.set("msgtype", "action_card").set("action_card", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    JSONObject buildMsg(String userid, ContractDTO dto, Contract contract, String statusStr) {
        var jsonObj = JSONUtil.ofObj()
                .set("agent_id", 2358374016L)
                .set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "验收提醒");
        String template = """
                #### 验收提醒" +
                #### 合同编号:**{}**" +
                #### 合同名称:**{}**" +
                #### 状态:{}" +
                #### 验收时间:{}" +
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                contract.getContractNo(), contract.getName(), statusStr, DateUtil.formatDate(dto.getNodeDate()), DateUtil.now());
        content.set("text", markdown);

        msg.set("msgtype", "markdown").set("markdown", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    private record Result(Set<String> roleCodeList, MPJLambdaWrapper<Contract> wrapper) {
    }

    /*
     * todo
     * 1.校验合同数量,以及合同编号
     * 2.校验合同金额
     * */
    public JSONObject ver() {
        var contractNoList = this.listObjs(v -> ((Contract) v).getContractNo());

        var json = JSONUtil.ofObj()
                .set("sortMap", JSONUtil.ofObj()
                        .set("field", "updateTime")
                        .set("sort", "desc"))
                .set("conditions", JSONUtil.ofArray()
                        .put(JSONUtil.ofObj()
                                .set("attr", "date_3")
                                .set("symbol", "greaterequal")
                                .set("value", new String[]{"1715356800"}))
                )
                .set("corpid", corpId)
                .set("formId", 8429903)
                .set("pageSize", 100);
        var res = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                .header("sign", SecureUtil.sha256(json.toString() + token))
                .body(json.toString())
                .method(Method.POST)
                .send();
        var jobO = JSONUtil.parseObj(res.bodyStr());
        if (jobO.getInt("code") != 1) {
            log.error("获取合同列表失败,错误原因:{}", jobO);
            return json;
        }
        Integer cnt = jobO.getJSONObject("result").getInt("totalCount");
        Integer page = jobO.getJSONObject("result").getInt("totalPage");
        if (NumberUtil.equals(cnt, 0)) {
            log.info("没有需要插入或更新的合同");
            return json;
        }
        var jsonArray = jobO.getJSONObject("result").getJSONArray("list");
        // 合同编号
        var dataIdSet =
                jsonArray.stream().map(v -> JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo")).collect(Collectors.toSet());

        for (int i = 2; i <= page; i++) {
            var jsonR = JSONUtil.ofObj()
                    .set("sortMap", JSONUtil.ofObj()
                            .set("field", "updateTime")
                            .set("order", "desc"))
                    .set("conditions", JSONUtil.ofArray()
                            .put(JSONUtil.ofObj()
                                    .set("attr", "date_3")
                                    .set("symbol", "greaterequal")
                                    .set("value", new String[]{"1715356800"}))
                    )
                    .set("corpid", corpId)
                    .set("formId", 8429903)
                    .set("page", i)
                    .set("pageSize", 100);
            var resR = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                    .header("sign", SecureUtil.sha256(jsonR.toString() + token))
                    .body(jsonR.toString())
                    .method(Method.POST)
                    .send();
            var jobR = JSONUtil.parseObj(resR.bodyStr());
            var jsonArrR = jobR.getJSONObject("result").getJSONArray("list");
            var dataIdSetR = jsonArrR.stream().map(v -> JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo")).collect(Collectors.toSet());
            dataIdSet.addAll(dataIdSetR);
        }

        // 返回销帮帮存在,但项目运维管理平台不存在的合同
        var unsyncedList = CollUtil.subtractToList(dataIdSet, contractNoList);
        // 返回项目运维管理平台存在,但销帮帮不存在的合同(可能销帮帮对该合同删除了)
        var extraList = CollUtil.subtractToList(contractNoList, dataIdSet);
        return JSONUtil.ofObj().set("unsynced", unsyncedList).set("extra", extraList);
    }

    public JSONObject contractDiff(String contractNo) {
        var platContract = this.lambdaQuery().eq(Contract::getContractNo, contractNo).one();

        var json = JSONUtil.ofObj()
                .set("conditions", JSONUtil.ofArray()
                        .put(JSONUtil.ofObj()
                                .set("attr", "serialNo")
                                .set("symbol", "equal")
                                .set("value", new String[]{contractNo}))
                )
                .set("corpid", corpId)
                .set("formId", 8429903)
                .set("pageSize", 100);
        var res = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/list")
                .header("sign", SecureUtil.sha256(json.toString() + token))
                .body(json.toString())
                .method(Method.POST)
                .send();
        var jobO = JSONUtil.parseObj(res.bodyStr());
        if (jobO.getInt("code") != 1) {
            log.error("获取合同列表失败,错误原因:{}", jobO);
            return json;
        }
        var jsonArray = jobO.getJSONObject("result").getJSONArray("list");
        // 合同记录唯一 dataId
        var dataIdSet = jsonArray.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet());

        var json1 = JSONUtil.ofObj()
                .set("corpid", corpId)
                .set("dataId", CollUtil.getFirst(dataIdSet));
        var res1 = Request.of("https://proapi.xbongbong.com/pro/v2/api/contract/detail")
                .header("sign", SecureUtil.sha256(json1.toString() + token))
                .body(json1.toString())
                .method(Method.POST)
                .send();
        var jobj1 = JSONUtil.parseObj(res1.bodyStr());
        if (jobj1.getInt("code") != 1) {
            log.error("获取合同详情失败,错误原因:{}", jobj1);
            return json;
        }
        var result = jobj1.getJSONObject("result");
        var jsonObj1 = result.getJSONObject("data");

        Map<String, Integer> contractTypeMap = Db.list(Wrappers.<Dictionary>lambdaQuery().eq(Dictionary::getType, "contract_type"))
                .stream()
                .collect(Collectors.toMap(Dictionary::getValue, Dictionary::getKey));

        Contract xbongContract = new Contract();
        xbongContract.setName(jsonObj1.getStr("text_14"));
        xbongContract.setContractNo(jsonObj1.getStr("serialNo"));
        xbongContract.setType(contractTypeMap.getOrDefault(jsonObj1.getJSONObject("text_17").getStr("text"), 0));
        xbongContract.setSignDate(DateUtil.date(jsonObj1.getLong("date_1") * 1000));
        xbongContract.setMaintainSdate(Opt.ofNullable(jsonObj1.getLong("date_4")).map(sec -> DateUtil.date(sec * 1000)).orElse(null));
        xbongContract.setMaintainEdate(Opt.ofNullable(jsonObj1.getLong("date_5")).map(sec -> DateUtil.date(sec * 1000)).orElse(null));
        String warrantyPeriod = Opt.ofNullable(jsonObj1.getJSONObject("text_23")).map(wp -> wp.getStr("text")).orElse("");
        if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) {
            String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2));
            xbongContract.setWarrantyPeriod(Integer.parseInt(substring));
        }
        xbongContract.setStatus(1);
        xbongContract.setTotalAmount(jsonObj1.getBigDecimal("num_1"));
        xbongContract.setPaidAmount(BigDecimal.ZERO);
        xbongContract.setReceivableAmount(BigDecimal.ZERO);
        xbongContract.setOutstandingAmount(jsonObj1.getBigDecimal("num_1"));
        var paymentForm = jsonObj1.getJSONArray("subForm_1");
        if (!paymentForm.isEmpty()) {
            paymentForm.forEach(pf -> {
                var pfObj = JSONUtil.parseObj(pf);
                var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pfObj.getStr("text_1"))), 100);
                var date = DateUtil.date(pfObj.getLong("date_1") * 1000);
                var stage = pfObj.getJSONObject("text_2").getStr("text");
                if (StrUtil.equals(stage, "预付款")) {
                    xbongContract.setSignRatio(ratio);
                    xbongContract.setSignDate1(date);
                } else if (StrUtil.equals(stage, "到货款")) {
                    xbongContract.setArriveRatio(ratio);
                    xbongContract.setArriveDate(date);
                } else if (StrUtil.equals(stage, "系统验收款")) {
                    xbongContract.setSystemCheckRatio(ratio);
                    xbongContract.setSystemCheckDate(date);
                } else if (StrUtil.equals(stage, "项目终验款")) {
                    xbongContract.setProjectCheckRatio(ratio);
                    xbongContract.setProjectCheckDate(date);
                } else if (StrUtil.equals(stage, "质保款")) {
                    xbongContract.setWarrantyRatio(ratio);
                    xbongContract.setWarrantyDate(date);
                } else if (StrUtil.equals(stage, "维保第一笔款")) {
                    xbongContract.setMaintainRatio1(ratio);
                    xbongContract.setMaintainDate1(date);
                } else if (StrUtil.equals(stage, "维保第二笔款")) {
                    xbongContract.setMaintainRatio2(ratio);
                    xbongContract.setMaintainDate2(date);
                } else if (StrUtil.equals(stage, "维保第三笔款")) {
                    xbongContract.setMaintainRatio3(ratio);
                    xbongContract.setMaintainDate3(date);
                } else if (StrUtil.equals(stage, "维保进度款")) {
                    xbongContract.setMaintainProgressRatio(ratio);
                    xbongContract.setMaintainProgressDate(date);
                } else if (StrUtil.equals(stage, "维保验收款")) {
                    xbongContract.setMaintainAcceptanceRatio(ratio);
                    xbongContract.setMaintainAcceptanceDate(date);
                }
            });
        }
        xbongContract.setSubject("北京文安智能技术股份有限公司");
        xbongContract.setCustomerName(jsonObj1.getJSONObject("text_2").getStr("name"));
        xbongContract.setSaleName(jsonObj1.getJSONObject("text_8").getStr("name"));
        xbongContract.setCreateUser(-1L);
        xbongContract.setModifyUser(-1L);
        xbongContract.setEntryTime(DateUtil.date(result.getLong("addTime") * 1000));
        xbongContract.setOriginalModTime(DateUtil.date(result.getLong("updateTime") * 1000));

        return JSONUtil.ofObj().set("platform", platContract).set("xbongbong", xbongContract);
    }

}