ContractRunner.java 41.4 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
package vion.cron;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.lang.Opt;
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.Request;
import org.dromara.hutool.http.meta.Method;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import vion.constant.RedisKeyEnum;
import vion.model.Dictionary;
import vion.model.*;
import vion.service.*;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 从crm系统定时同步合同信息
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ContractRunner {

    private final IContractService contractService;
    private final IDictionaryService dictionaryService;
    private final IContractPaymentService contractPaymentService;
    private final IRContractUserService contractUserService;
    private final IRContractStoreService contractStoreService;
    private final IStoreService storeService;
    private final IPaymentService paymentService;
    private final IRContractProductService contractProductService;
    private final RedissonClient redissonClient;

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

    // @Scheduled(cron = "0 0 * * * *")
    @Transactional(rollbackFor = Exception.class)
    public void contractSync() {
        log.info("【开始】从crm系统同步合同信息");
        Map<String, Contract> no2ContactMap = contractService.list().stream().collect(Collectors.toMap(Contract::getContractNo, Function.identity()));
        Map<String, Integer> contractTypeMap = dictionaryService.lambdaQuery().eq(Dictionary::getType, "contract_type").list()
                .stream().collect(Collectors.toMap(Dictionary::getValue, Dictionary::getKey));

        List<Contract> insOrUpdContractList = new ArrayList<>();
        String modifyTime = Opt.ofNullable((String) redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_TIME.getVal()).get())
                .orElse("1970-01-01 00:00:00");
        String url = "jdbc:sqlserver://47.92.144.255:1433;databaseName=UFDATA_001_2020;encrypt=false";
        String username = "vion-reader";
        String password = "vion-reader";
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            String contractTemplate = """
                    select t5.hetongpingshen_name as name,t1.hetongluru_name as contract_no,t1.hetongluru_char12 as type,t1.hetongluru_date01 as sign_date,t1.hetongluru_char01 as warranty_period,t1.hetongluru_start_date as maintain_sdate,t1.hetongluru_end_date as maintain_edate,t1.hetongluru_dec01 as total_amount,t5.hetongpingshen_dec02 as sign_ratio,t5.hetongpingshen_dec03 as arrive_ratio,t5.hetongpingshen_dec04 as system_check_ratio,t5.hetongpingshen_dec05 as project_check_ratio,t5.hetongpingshen_dec06 as warranty_ratio,t5.hetongpingshen_dec07 as maintain1_ratio,t5.hetongpingshen_dec09 as maintain2_ratio,t5.hetongpingshen_dec10 as maintain3_ratio,t2.cCusAbbName as customer_name,t4.cUser_Name as sale_name,t1.create_time as entry_time,t5.hetongpingshen_date01 as sign_date1,t5.hetongpingshen_date04 as arrive_date,t5.hetongpingshen_date05 as system_check_date,t5.hetongpingshen_date06 as project_check_date,t5.hetongpingshen_date07 as warranty_date,t5.hetongpingshen_date08 as maintain_date1, t6.hetongpingshen_date09 as maintain_date2,t6.hetongpingshen_date10 as maintain_date3,t1.modify_time as original_mod_time 
                    from tcu_hetongluru t1 left join Customer t2 on t1.account_id = t2.cCusCode left join tc_opportunity t3 on t1.hetongluru_char04 = t3.ufcode left join UA_User_Ex t4 on t1.owner_user_id = t4.cUser_Id left join tcu_hetongpingshen t5 on t1.hetongluru_name = t5.hetongpingshen_char05 left join tcu_hetongpingshen_attr t6 on t5.hetongpingshen_id = t6.hetongpingshen_id where t1.modify_time > '{}' order by t1.modify_time desc
                    """;
            String contractSql = StrUtil.format(contractTemplate, modifyTime);
            try (Statement statement = connection.createStatement()) {
                var rs = statement.executeQuery(contractSql);
                while (rs.next()) {
                    String contractNo = rs.getString("contract_no");
                    Contract contract = new Contract();
                    Optional.ofNullable(rs.getString("name"))
                            .filter(StrUtil::isNotBlank)
                            .ifPresentOrElse(contract::setName, () -> contract.setName(contractNo));

                    contract.setContractNo(contractNo);
                    contract.setType(contractTypeMap.getOrDefault(rs.getString("type"), 0));
                    contract.setSignDate(rs.getDate("sign_date"));
                    String warrantyPeriod = rs.getString("warranty_period");
                    if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) {
                        String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2));
                        contract.setWarrantyPeriod(Integer.parseInt(substring));
                    }
                    contract.setMaintainSdate(rs.getDate("maintain_sdate"));
                    contract.setMaintainEdate(rs.getDate("maintain_edate"));
                    contract.setStatus(1);
                    contract.setTotalAmount(rs.getBigDecimal("total_amount"));
                    contract.setSignRatio(rs.getBigDecimal("sign_ratio"));
                    contract.setSignDate1(rs.getDate("sign_date1"));
                    contract.setArriveRatio(rs.getBigDecimal("arrive_ratio"));
                    contract.setArriveDate(rs.getDate("arrive_date"));
                    contract.setSystemCheckRatio(rs.getBigDecimal("system_check_ratio"));
                    contract.setSystemCheckDate(rs.getDate("system_check_date"));
                    contract.setProjectCheckRatio(rs.getBigDecimal("project_check_ratio"));
                    contract.setProjectCheckDate(rs.getDate("project_check_date"));
                    contract.setWarrantyRatio(rs.getBigDecimal("warranty_ratio"));
                    contract.setWarrantyDate(rs.getDate("warranty_date"));
                    contract.setMaintainRatio1(rs.getBigDecimal("maintain1_ratio"));
                    contract.setMaintainDate1(rs.getDate("maintain_date1"));
                    contract.setMaintainRatio2(rs.getBigDecimal("maintain2_ratio"));
                    contract.setMaintainDate2(rs.getDate("maintain_date2"));
                    contract.setMaintainRatio3(rs.getBigDecimal("maintain3_ratio"));
                    contract.setMaintainDate3(rs.getDate("maintain_date3"));
                    contract.setPaidAmount(BigDecimal.ZERO);
                    contract.setReceivableAmount(BigDecimal.ZERO);
                    contract.setOutstandingAmount(rs.getBigDecimal("total_amount"));
                    contract.setSubject("北京文安智能技术股份有限公司");
                    contract.setCustomerName(rs.getString("customer_name"));
                    contract.setSaleName(rs.getString("sale_name"));
                    contract.setCreateUser(-1L);
                    contract.setModifyUser(-1L);
                    contract.setEntryTime(rs.getTimestamp("entry_time"));
                    contract.setOriginalModTime(rs.getTimestamp("original_mod_time"));
                    insOrUpdContractList.add(contract);
                }
                if (CollUtil.isNotEmpty(insOrUpdContractList)) {
                    var noList = insOrUpdContractList.stream().map(Contract::getContractNo).toList();
                    var noStr = insOrUpdContractList.stream().map(Contract::getContractNo).distinct().collect(Collectors.joining("','", "'", "'"));
                    String productTemplate = """
                            SELECT c.cInvName as product_name,c.cInvCode as product_code,c.cInvStd as product_model,a.hetongluru_name as contract_no,b.hetongluru_d_dec01 as num,b.hetongluru_d_dec02 as tax_price,b.hetongluru_d_dec03 as tax_rate,b.hetongluru_d_dec04 as no_tax_price,b.hetongluru_d_dec05 as discount_rate,b.hetongluru_d_dec06 as actual_price,b.hetongluru_d_dec07 as total_price,b.hetongluru_d_dec08 as erase from tcu_hetongluru a left join tcu_hetongluru_d b on a.hetongluru_id=b.m_id LEFT JOIN Inventory c on b.ref_obj_id=c.cInvCode where a.hetongluru_name in ({})
                            """;
                    var productSql = StrUtil.format(productTemplate, noStr);
                    var rs1 = statement.executeQuery(productSql);
                    var productList = new ArrayList<RContractProduct>();
                    while (rs1.next()) {
                        var contractProduct = new RContractProduct();
                        contractProduct.setContractNo(rs1.getString("contract_no"));
                        contractProduct.setProductName(rs1.getString("product_name"));
                        contractProduct.setProductCode(rs1.getString("product_code"));
                        contractProduct.setProductModel(rs1.getString("product_model"));
                        contractProduct.setNum(rs1.getInt("num"));
                        contractProduct.setTaxPrice(rs1.getBigDecimal("tax_price"));
                        contractProduct.setTaxRate(rs1.getBigDecimal("tax_rate"));
                        contractProduct.setNoTaxPrice(rs1.getBigDecimal("no_tax_price"));
                        contractProduct.setDiscountRate(rs1.getBigDecimal("discount_rate"));
                        contractProduct.setActualPrice(rs1.getBigDecimal("actual_price"));
                        contractProduct.setErase(rs1.getBigDecimal("erase"));
                        contractProduct.setTotalPrice(rs1.getBigDecimal("total_price"));
                        productList.add(contractProduct);
                    }
                    contractProductService.lambdaUpdate().in(RContractProduct::getContractNo, noList).remove();
                    contractProductService.saveBatch(productList);
                }
            }
        } catch (SQLException e) {
            log.error("合同信息同步失败:", e);
            return;
        }

        if (CollUtil.isEmpty(insOrUpdContractList)) {
            log.info("没有需要插入或更新的合同");
            return;
        }

        List<Long> updContractIdList = new ArrayList<>();
        insOrUpdContractList.forEach(v -> {
            if (no2ContactMap.containsKey(v.getContractNo())) {
                Long contractId = no2ContactMap.get(v.getContractNo()).getId();
                v.setId(contractId);
                // 已有合同不更新状态
                v.setStatus(null);
                updContractIdList.add(contractId);
            }
        });
        // 合同更新,同步调用一下更新项目的维保状态
        Opt.ofEmptyAble(updContractIdList)
                .map(contractIdList -> contractStoreService.lambdaQuery().in(RContractStore::getContractId, contractIdList).list())
                .map(csList -> csList.stream().map(RContractStore::getStoreId).collect(Collectors.toList()))
                .filter(CollUtil::isNotEmpty)
                .ifPresent(storeService::calMaintainStatus);

        contractService.saveOrUpdateBatch(insOrUpdContractList, 500);
        insOrUpdContractList.forEach(v -> {
            // 合同状态不为空,代表此条记录为新增,需要同步销售人信息到 r_contract_user 表中
            if (ObjUtil.isNotNull(v.getStatus())) {
                RContractUser contractUser = new RContractUser();
                String userId = Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + v.getSaleName()).get())
                        .map(u -> (User) u)
                        .map(User::getUserid)
                        .orElse(null);
                contractUser.setUserId(userId);
                contractUser.setUsername(v.getSaleName());
                contractUser.setEnterDate(v.getSignDate());
                contractUser.setContractId(v.getId());
                contractUser.setContractNo(v.getContractNo());
                contractUserService.save(contractUser);
            }
        });

        List<ContractPayment> existContractPaymentList = contractPaymentService.list();
        Map<Long, Map<Integer, Long>> contractId2PaymentMap = existContractPaymentList.stream().collect(Collectors.groupingBy(ContractPayment::getContractId, Collectors.toMap(ContractPayment::getPaymentType, ContractPayment::getId)));

        // 合同付款比例
        List<ContractPayment> contractPaymentList = new ArrayList<>();
        for (Contract contract : insOrUpdContractList) {
            // 签订
            ContractPayment contractSignPayment = new ContractPayment();
            contractSignPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(1));
            contractSignPayment.setContractId(contract.getId());
            contractSignPayment.setPaymentType(1);
            contractSignPayment.setPaymentRatio(Opt.ofNullable(contract.getSignRatio()).orElse(BigDecimal.ZERO));
            contractSignPayment.setPaymentDate(contract.getSignDate1());
            contractSignPayment.setNodeDate(contract.getSignDate());
            contractPaymentList.add(contractSignPayment);

            // 到货
            ContractPayment contractArrivePayment = new ContractPayment();
            contractArrivePayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(2));
            contractArrivePayment.setContractId(contract.getId());
            contractArrivePayment.setPaymentType(2);
            contractArrivePayment.setPaymentRatio(Opt.ofNullable(contract.getArriveRatio()).orElse(BigDecimal.ZERO));
            contractArrivePayment.setPaymentDate(contract.getArriveDate());
            contractPaymentList.add(contractArrivePayment);

            // 系统验收
            ContractPayment contractSystemCheckPayment = new ContractPayment();
            contractSystemCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(3));
            contractSystemCheckPayment.setContractId(contract.getId());
            contractSystemCheckPayment.setPaymentType(3);
            contractSystemCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getSystemCheckRatio()).orElse(BigDecimal.ZERO));
            contractSystemCheckPayment.setPaymentDate(contract.getSystemCheckDate());
            contractPaymentList.add(contractSystemCheckPayment);

            // 项目验收
            ContractPayment contractProjectCheckPayment = new ContractPayment();
            contractProjectCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(4));
            contractProjectCheckPayment.setContractId(contract.getId());
            contractProjectCheckPayment.setPaymentType(4);
            contractProjectCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getProjectCheckRatio()).orElse(BigDecimal.ZERO));
            contractProjectCheckPayment.setPaymentDate(contract.getProjectCheckDate());
            contractPaymentList.add(contractProjectCheckPayment);

            // 质保
            ContractPayment contractWarrantyPayment = new ContractPayment();
            contractWarrantyPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(5));
            contractWarrantyPayment.setContractId(contract.getId());
            contractWarrantyPayment.setPaymentType(5);
            contractWarrantyPayment.setPaymentRatio(Opt.ofNullable(contract.getWarrantyRatio()).orElse(BigDecimal.ZERO));
            contractWarrantyPayment.setPaymentDate(contract.getWarrantyDate());
            contractPaymentList.add(contractWarrantyPayment);

            // 第一笔维保款
            ContractPayment contractMaintainPayment1 = new ContractPayment();
            contractMaintainPayment1.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(6));
            contractMaintainPayment1.setContractId(contract.getId());
            contractMaintainPayment1.setPaymentType(6);
            contractMaintainPayment1.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio1()).orElse(BigDecimal.ZERO));
            contractMaintainPayment1.setPaymentDate(contract.getMaintainDate1());
            contractPaymentList.add(contractMaintainPayment1);

            // 第二笔维保款
            ContractPayment contractMaintainPayment2 = new ContractPayment();
            contractMaintainPayment2.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(7));
            contractMaintainPayment2.setContractId(contract.getId());
            contractMaintainPayment2.setPaymentType(7);
            contractMaintainPayment2.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio2()).orElse(BigDecimal.ZERO));
            contractMaintainPayment2.setPaymentDate(contract.getMaintainDate2());
            contractPaymentList.add(contractMaintainPayment2);

            // 第三笔维保款
            ContractPayment contractMaintainPayment3 = new ContractPayment();
            contractMaintainPayment3.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(8));
            contractMaintainPayment3.setContractId(contract.getId());
            contractMaintainPayment3.setPaymentType(8);
            contractMaintainPayment3.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio3()).orElse(BigDecimal.ZERO));
            contractMaintainPayment3.setPaymentDate(contract.getMaintainDate3());
            contractPaymentList.add(contractMaintainPayment3);
        }
        contractPaymentService.saveOrUpdateBatch(contractPaymentList);

        List<Payment> paymentList = paymentService.list();
        Map<String, BigDecimal> no2PaymentMap = paymentList.stream().collect(Collectors.groupingBy(Payment::getContractNo, Collectors.reducing(BigDecimal.ZERO, Payment::getPaymentAmount, BigDecimal::add)));

        insOrUpdContractList.forEach(c -> {
            String contractNo = c.getContractNo();
            Contract exist = contractService.lambdaQuery().eq(Contract::getContractNo, contractNo).one();
            Contract updDto = new Contract();
            updDto.setId(exist.getId());
            updDto.setPaidAmount(no2PaymentMap.getOrDefault(contractNo, BigDecimal.ZERO));
            contractPaymentService.calMoney(exist, updDto);
            contractService.updateById(updDto);
        });

        redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_TIME.getVal()).set(DateUtil.formatDateTime(insOrUpdContractList.get(0).getOriginalModTime()));
        log.info("【结束】从crm系统同步合同信息");
    }

    @Scheduled(cron = "0 0 * * * *")
    @Transactional(rollbackFor = Exception.class)
    public void contractSync1() {
        Long modifyTime = Opt.ofNullable((Long) redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).get()).orElse(0L);

        // 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同
        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"}))
                        .put(JSONUtil.ofObj()
                                .set("attr", "updateTime")
                                .set("symbol", "greatethan")
                                .set("value", new String[]{String.valueOf(modifyTime / 1000)}))
                )
                .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;
        }
        Integer cnt = jobO.getJSONObject("result").getInt("totalCount");
        Integer page = jobO.getJSONObject("result").getInt("totalPage");
        if (NumberUtil.equals(cnt, 0)) {
            log.info("没有需要插入或更新的合同");
            return;
        }
        var jsonArray = jobO.getJSONObject("result").getJSONArray("list");
        // 合同记录唯一 dataId
        var dataIdSet = jsonArray.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).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"}))
                            .put(JSONUtil.ofObj()
                                    .set("attr", "updateTime")
                                    .set("fieldType", "10015")
                                    .set("symbol", "greatethan")
                                    .set("value", new String[]{String.valueOf(modifyTime)}))
                    )
                    .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).getInt("dataId")).collect(Collectors.toSet());
            dataIdSet.addAll(dataIdSetR);
        }

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

        List<Contract> insOrUpdContractList = new ArrayList<>();
        List<RContractProduct> productList = new ArrayList<>();
        var crmProList = getProductList();
        if (CollUtil.isEmpty(crmProList)) {
            log.error("获取CRM产品信息为空");
            return;
        }
        dataIdSet.forEach(dataId -> {
            var json1 = JSONUtil.ofObj()
                    .set("corpid", corpId)
                    .set("dataId", dataId);
            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;
            }
            var result = jobj1.getJSONObject("result");
            var jsonObj1 = result.getJSONObject("data");
            Contract contract = new Contract();
            contract.setName(jsonObj1.getStr("text_14"));
            contract.setContractNo(jsonObj1.getStr("serialNo"));
            contract.setType(contractTypeMap.getOrDefault(jsonObj1.getJSONObject("text_17").getStr("text"), 0));
            contract.setSignDate(DateUtil.date(jsonObj1.getLong("date_1") * 1000));
            contract.setMaintainSdate(Opt.ofNullable(jsonObj1.getLong("date_4")).map(sec -> DateUtil.date(sec * 1000)).orElse(null));
            contract.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));
                contract.setWarrantyPeriod(Integer.parseInt(substring));
            }
            contract.setStatus(1);
            contract.setTotalAmount(jsonObj1.getBigDecimal("num_1"));
            contract.setPaidAmount(BigDecimal.ZERO);
            contract.setReceivableAmount(BigDecimal.ZERO);
            contract.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, "预付款")) {
                        contract.setSignRatio(ratio);
                        contract.setSignDate1(date);
                    } else if (StrUtil.equals(stage, "到货款")) {
                        contract.setArriveRatio(ratio);
                        contract.setArriveDate(date);
                    } else if (StrUtil.equals(stage, "系统验收款")) {
                        contract.setSystemCheckRatio(ratio);
                        contract.setSystemCheckDate(date);
                    } else if (StrUtil.equals(stage, "项目终验款")) {
                        contract.setProjectCheckRatio(ratio);
                        contract.setProjectCheckDate(date);
                    } else if (StrUtil.equals(stage, "质保款")) {
                        contract.setWarrantyRatio(ratio);
                        contract.setWarrantyDate(date);
                    } else if (StrUtil.equals(stage, "维保第一笔款")) {
                        contract.setMaintainRatio1(ratio);
                        contract.setMaintainDate1(date);
                    } else if (StrUtil.equals(stage, "维保第二笔款")) {
                        contract.setMaintainRatio2(ratio);
                        contract.setMaintainDate2(date);
                    } else if (StrUtil.equals(stage, "维保第三笔款")) {
                        contract.setMaintainRatio3(ratio);
                        contract.setMaintainDate3(date);
                    } else if (StrUtil.equals(stage, "维保进度款")) {
                        contract.setMaintainProgressRatio(ratio);
                        contract.setMaintainProgressDate(date);
                    } else if (StrUtil.equals(stage, "维保验收款")) {
                        contract.setMaintainAcceptanceRatio(ratio);
                        contract.setMaintainAcceptanceDate(date);
                    }
                });
            }
            contract.setSubject("北京文安智能技术股份有限公司");
            contract.setCustomerName(jsonObj1.getJSONObject("text_2").getStr("name"));
            contract.setSaleName(jsonObj1.getJSONObject("text_8").getStr("name"));
            contract.setCreateUser(-1L);
            contract.setModifyUser(-1L);
            contract.setEntryTime(DateUtil.date(result.getLong("addTime") * 1000));
            contract.setOriginalModTime(DateUtil.date(result.getLong("updateTime") * 1000));
            insOrUpdContractList.add(contract);

            var productArr = jsonObj1.getJSONArray("array_4");
            if (!productArr.isEmpty()) {
                productArr.forEach(pro -> {
                    var product = JSONUtil.parseObj(pro);
                    var crmProJson = crmProList.stream().filter(p -> p.getInt("dataId").equals(product.getInt("text_1"))).toList().get(0);
                    var crmPro = crmProJson.getJSONObject("data");

                    var contractProduct = new RContractProduct();
                    contractProduct.setContractNo(contract.getContractNo());
                    contractProduct.setProductName(crmPro.getStr("text_1"));
                    contractProduct.setProductCode(crmPro.getStr("serialNo"));
                    contractProduct.setProductModel(crmPro.getStr("text_4"));
                    contractProduct.setNum(product.getInt("num_3"));
                    contractProduct.setTaxPrice(product.getBigDecimal("num_1"));
                    contractProduct.setTaxRate(BigDecimal.valueOf(Integer.parseInt(crmPro.getStr("text_12").replace("%", "")) / 100));
                    // contractProduct.setNoTaxPrice(product.getBigDecimal("num_6"));
                    contractProduct.setDiscountRate(NumberUtil.div(product.getBigDecimal("num_4"), 100));
                    contractProduct.setActualPrice(product.getBigDecimal("num_6"));
                    // contractProduct.setErase(product);
                    contractProduct.setTotalPrice(product.getBigDecimal("num_5"));
                    productList.add(contractProduct);
                });
            }
        });
        insOrUpdContractList.sort(Comparator.comparing(Contract::getOriginalModTime).reversed());
        var no2ProductMap = productList.stream().collect(Collectors.groupingBy(RContractProduct::getContractNo));

        // 已存在的合同列表
        Map<String, Contract> no2ContactMap = contractService.list().stream().collect(Collectors.toMap(Contract::getContractNo, Function.identity()));

        List<Long> updContractIdList = new ArrayList<>();
        insOrUpdContractList.forEach(v -> {
            if (no2ContactMap.containsKey(v.getContractNo())) {
                Long contractId = no2ContactMap.get(v.getContractNo()).getId();
                v.setId(contractId);
                // 已有合同不更新状态
                v.setStatus(null);
                updContractIdList.add(contractId);
                // 移除已存在合同的关联产品信息,防止重复插入
                no2ProductMap.remove(v.getContractNo());
            }
        });
        contractProductService.saveBatch(no2ProductMap.values().stream().flatMap(Collection::stream).toList());

        // 合同更新,同步调用一下更新项目的维保状态
        Opt.ofEmptyAble(updContractIdList)
                .map(contractIdList -> contractStoreService.lambdaQuery().in(RContractStore::getContractId, contractIdList).list())
                .map(csList -> csList.stream().map(RContractStore::getStoreId).collect(Collectors.toList()))
                .filter(CollUtil::isNotEmpty)
                .ifPresent(storeService::calMaintainStatus);

        contractService.saveOrUpdateBatch(insOrUpdContractList, 500);
        insOrUpdContractList.forEach(v -> {
            // 合同状态不为空,代表此条记录为新增,需要同步销售人信息到 r_contract_user 表中
            if (ObjUtil.isNotNull(v.getStatus())) {
                RContractUser contractUser = new RContractUser();
                String userId = Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + v.getSaleName()).get())
                        .map(u -> (User) u)
                        .map(User::getUserid)
                        .orElse(null);
                contractUser.setUserId(userId);
                contractUser.setUsername(v.getSaleName());
                contractUser.setEnterDate(v.getSignDate());
                contractUser.setContractId(v.getId());
                contractUser.setContractNo(v.getContractNo());
                contractUserService.save(contractUser);
            }
        });

        List<ContractPayment> existContractPaymentList = contractPaymentService.list();
        Map<Long, Map<Integer, Long>> contractId2PaymentMap = existContractPaymentList.stream().collect(Collectors.groupingBy(ContractPayment::getContractId, Collectors.toMap(ContractPayment::getPaymentType, ContractPayment::getId)));

        // 合同付款比例
        List<ContractPayment> contractPaymentList = new ArrayList<>();
        for (Contract contract : insOrUpdContractList) {
            // 签订
            ContractPayment contractSignPayment = new ContractPayment();
            contractSignPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(1));
            contractSignPayment.setContractId(contract.getId());
            contractSignPayment.setPaymentType(1);
            contractSignPayment.setPaymentRatio(Opt.ofNullable(contract.getSignRatio()).orElse(BigDecimal.ZERO));
            contractSignPayment.setPaymentDate(contract.getSignDate1());
            contractSignPayment.setNodeDate(contract.getSignDate());
            contractPaymentList.add(contractSignPayment);

            // 到货
            ContractPayment contractArrivePayment = new ContractPayment();
            contractArrivePayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(2));
            contractArrivePayment.setContractId(contract.getId());
            contractArrivePayment.setPaymentType(2);
            contractArrivePayment.setPaymentRatio(Opt.ofNullable(contract.getArriveRatio()).orElse(BigDecimal.ZERO));
            contractArrivePayment.setPaymentDate(contract.getArriveDate());
            contractPaymentList.add(contractArrivePayment);

            // 系统验收
            ContractPayment contractSystemCheckPayment = new ContractPayment();
            contractSystemCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(3));
            contractSystemCheckPayment.setContractId(contract.getId());
            contractSystemCheckPayment.setPaymentType(3);
            contractSystemCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getSystemCheckRatio()).orElse(BigDecimal.ZERO));
            contractSystemCheckPayment.setPaymentDate(contract.getSystemCheckDate());
            contractPaymentList.add(contractSystemCheckPayment);

            // 项目验收
            ContractPayment contractProjectCheckPayment = new ContractPayment();
            contractProjectCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(4));
            contractProjectCheckPayment.setContractId(contract.getId());
            contractProjectCheckPayment.setPaymentType(4);
            contractProjectCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getProjectCheckRatio()).orElse(BigDecimal.ZERO));
            contractProjectCheckPayment.setPaymentDate(contract.getProjectCheckDate());
            contractPaymentList.add(contractProjectCheckPayment);

            // 质保
            ContractPayment contractWarrantyPayment = new ContractPayment();
            contractWarrantyPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(5));
            contractWarrantyPayment.setContractId(contract.getId());
            contractWarrantyPayment.setPaymentType(5);
            contractWarrantyPayment.setPaymentRatio(Opt.ofNullable(contract.getWarrantyRatio()).orElse(BigDecimal.ZERO));
            contractWarrantyPayment.setPaymentDate(contract.getWarrantyDate());
            contractPaymentList.add(contractWarrantyPayment);

            // 第一笔维保款
            ContractPayment contractMaintainPayment1 = new ContractPayment();
            contractMaintainPayment1.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(6));
            contractMaintainPayment1.setContractId(contract.getId());
            contractMaintainPayment1.setPaymentType(6);
            contractMaintainPayment1.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio1()).orElse(BigDecimal.ZERO));
            contractMaintainPayment1.setPaymentDate(contract.getMaintainDate1());
            contractPaymentList.add(contractMaintainPayment1);

            // 第二笔维保款
            ContractPayment contractMaintainPayment2 = new ContractPayment();
            contractMaintainPayment2.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(7));
            contractMaintainPayment2.setContractId(contract.getId());
            contractMaintainPayment2.setPaymentType(7);
            contractMaintainPayment2.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio2()).orElse(BigDecimal.ZERO));
            contractMaintainPayment2.setPaymentDate(contract.getMaintainDate2());
            contractPaymentList.add(contractMaintainPayment2);

            // 第三笔维保款
            ContractPayment contractMaintainPayment3 = new ContractPayment();
            contractMaintainPayment3.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(8));
            contractMaintainPayment3.setContractId(contract.getId());
            contractMaintainPayment3.setPaymentType(8);
            contractMaintainPayment3.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio3()).orElse(BigDecimal.ZERO));
            contractMaintainPayment3.setPaymentDate(contract.getMaintainDate3());
            contractPaymentList.add(contractMaintainPayment3);
        }
        contractPaymentService.saveOrUpdateBatch(contractPaymentList);

        List<Payment> paymentList = paymentService.list();
        Map<String, BigDecimal> no2PaymentMap = paymentList.stream().collect(Collectors.groupingBy(Payment::getContractNo, Collectors.reducing(BigDecimal.ZERO, Payment::getPaymentAmount, BigDecimal::add)));

        insOrUpdContractList.forEach(c -> {
            String contractNo = c.getContractNo();
            Contract exist = contractService.lambdaQuery().eq(Contract::getContractNo, contractNo).one();
            Contract updDto = new Contract();
            updDto.setId(exist.getId());
            updDto.setPaidAmount(no2PaymentMap.getOrDefault(contractNo, BigDecimal.ZERO));
            contractPaymentService.calMoney(exist, updDto);
            contractService.updateById(updDto);
        });
        redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).set(insOrUpdContractList.get(0).getOriginalModTime().getTime());

        log.info("【结束】从crm系统同步合同信息");
    }

    /**
     * 获取CRM产品列表,若循环调用接口出现一次失败,则直接返回空列表
     *
     * @return java.util.List<org.dromara.hutool.json.JSONObject>
     */
    public List<JSONObject> getProductList() {
        List<JSONObject> resList = new ArrayList<>();
        var json = JSONUtil.ofObj()
                .set("corpid", corpId)
                .set("page", 1)
                .set("pageSize", 100);

        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产品列表失败:{}", jobj);
            return List.of();
        }
        var result = jobj.getJSONObject("result");
        var totalPage = result.getInt("totalPage");
        result.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add);

        for (int i = 2; i <= totalPage; i++) {
            var json1 = JSONUtil.ofObj()
                    .set("corpid", corpId)
                    .set("page", i)
                    .set("pageSize", 100);
            var res1 = Request.of("https://proapi.xbongbong.com/pro/v2/api/product/list")
                    .header("sign", SecureUtil.sha256(json1 + token))
                    .body(json1.toString())
                    .method(Method.POST)
                    .send();
            var body1 = res1.bodyStr();
            var jobj1 = JSONUtil.parseObj(body1);
            if (jobj1.getInt("code") != 1) {
                log.error("获取CRM产品列表失败:{}", jobj1);
                return List.of();
            }
            var result1 = jobj1.getJSONObject("result");
            result1.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add);
        }
        return resList;
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void calMaintainStatus() {
        log.info("【开始】计算门店维保状态");
        storeService.calMaintainStatus(ListUtil.empty());
        log.info("【结束】计算门店维保状态");
    }

    @Scheduled(cron = "0 10 * ? * *")
    public void syncContractFile() {
        contractService.syncContractFile(null);
    }
}