ScrmDataCubeJoinRestCloudService.java 73.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
package cn.com.glsx.entmicro.service;

import ch.ethz.ssh2.*;
import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.entity.BaseEntity;
import cn.com.glsx.entmicro.entity.DataCubeMerchantConfigDO;
import cn.com.glsx.entmicro.entity.DataCubeTemplateConfigDO;
import cn.com.glsx.entmicro.entity.DataCubeUploadLogDO;
import cn.com.glsx.entmicro.entity.datacube.DataCubeConfigFieldRelationDO;
import cn.com.glsx.entmicro.entity.datacube.DataCubeFieldPoolDO;
import cn.com.glsx.entmicro.entity.datacube.DataCubeTableConfigInfo;
import cn.com.glsx.entmicro.entity.magic.MagicTemplateConfigInfo;
import cn.com.glsx.entmicro.kafka.producer.ProducerComponent;
import cn.com.glsx.entmicro.listener.SelfResearchRestCloudListener;
import cn.com.glsx.entmicro.mapper.*;
import cn.com.glsx.entmicro.model.FailRecord;
import cn.com.glsx.entmicro.model.UserResponse;
import cn.com.glsx.entmicro.model.WechatMessageModel;
import cn.com.glsx.entmicro.model.request.DataCubeBaseRpcRequest;
import cn.com.glsx.entmicro.model.request.DataCubeFileInfo;
import cn.com.glsx.entmicro.model.request.MagicCubeImportApiRequest;
import cn.com.glsx.entmicro.model.request.RestCloudContentRpcRequest;
import cn.com.glsx.entmicro.model.request.restcloud.*;
import cn.com.glsx.entmicro.model.response.DataCubeMerchantConfigResponse;
import cn.com.glsx.entmicro.model.response.DataCubeUploadLogResponse;
import cn.com.glsx.entmicro.model.response.EntmicroStaffResponse;
import cn.com.glsx.entmicro.model.response.restcloud.DataCubeTemplateConfigResponse;
import cn.com.glsx.entmicro.model.response.restcloud.DataPoolResponse;
import cn.com.glsx.entmicro.model.response.restcloud.TableConfigInfoResponse;
import cn.com.glsx.entmicro.model.response.restcloud.TemplateConfigResponse;
import cn.com.glsx.entmicro.service.common.CommonService;
import cn.com.glsx.entmicro.util.FileUploadServerData;
import cn.com.glsx.entmicro.util.FileUploadUtil;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chizw
 * @Description 数据魔方对接RestCloud
 * @create 2022/4/22 14:55
 */
@Service
@Slf4j
public class ScrmDataCubeJoinRestCloudService {

    @Resource
    private DataCubeUploadLogMapper dataCubeUploadLogMapper;

    @Resource
    private DataCubeTemplateConfigMapper dataCubeTemplateConfigMapper;

    @Resource
    private EntmicroStaffMapper entmicroStaffMapper;

    @Resource
    private CommonService commonService;

    @Resource
    private MerchantService merchantService;

    @Resource
    private ProducerComponent producerComponent;

    @Resource
    private DataCubeTableFieldRelationMapper dataCubeTableFieldRelationMapper;

    @Resource
    private DataCubeFieldPoolMapper dataCubeFieldPoolMapper;

    @Autowired
    private Environment environment;

    // RestCloud最大回调文件
    private static final int REST_CLOUD_FILE_TOTAL_MAX = 6;
    // RestCloud回调成功
    private static final int REST_CLOUD_RESULT_SUCCESS = 1;
    // RestCloud回调失败
    private static final int REST_CLOUD_RESULT_FAIL = 0;
    // 文件处理成功
    private static final int REST_CLOUD_STATE_SUCCESS = 1;
    // 文件处理失败
    private static final int REST_CLOUD_STATE_FAIL = 2;
    // 文件待处理
    private static final int REST_CLOUD_STATE_WAIT = 3;
    //是否独立部署 0=否 1=是
    private static final String IS_INDEPENDENT_DEPLOYMENT = "1";
    //已迁移门店,","号分隔
    private static final String TRANSFER_MERCHANT = "scrm.datacube.restcloud.transfer.merchant";

    private static final String ADD_WAY_FIELD = "add_way";
    private static final String MERCHANT_ID_FIELD = "merchant_id";
    private static final int DATA_CUBE_ADD_WAY = 101;
    private static final String REST_CLOUD_BASE_URL = "http://rc.glsx.com.cn/restcloud/stage_44211266/etl_flow_221025006";

    @Value("${scrm.datacube.restcloud.default.path}")
    private String REST_CLOUD_DEFAULT_PATH;

    @Value("${scrm.datacube.restcloud.exception.path}")
    private String EXCEPTION_DATA_FILE_PATH;

    @Value("${scrm.datacube.restcloud.user}")
    private String USER;

    @Value("${scrm.datacube.restcloud.password}")
    private String PASSWORD;

    @Value("${scrm.datacube.restcloud.ip}")
    public void setRestCloudIp(String ip) {
        REST_CLOUD_IP = ip;
    }

    @Value("${scrm.datacube.restcloud.port}")
    public void setRestCloudPort(Integer port) {
        REST_CLOUD_PORT = port;
    }

    private static String REST_CLOUD_IP;

    private static int REST_CLOUD_PORT;

    @Autowired
    private TemplateConfigMapper templateConfigMapper;

    /**
     * 数据魔方文件上传
     */
    @Async("taskExecutor")
    public void uploadDataCubeFiles(List<MagicCubeImportApiRequest> fileList, Integer merchantId, String batchNumber) {
        log.info("商户:{},批次:{},RestCloud开始上传:{}", merchantId, batchNumber, fileList);
        try {
            if (merchantId == null) {
                throw new RpcServiceException("1", "商户不存在");
            }
            log.info("商户:{}数据魔方文件上传参数:{}", merchantId, fileList);
            if (StringUtils.isEmpty(batchNumber)) {
                batchNumber = buildBatchNumber();
            }
            //文件上传RestCloud
            fileList = fileList.stream().sorted(Comparator.comparing(MagicCubeImportApiRequest::getBusinessTypeId, Comparator.nullsLast(Integer::compareTo)))
                    .collect(Collectors.toList());
            boolean flag = false;
            List<DataCubeFileInfo> fileInfoList = new ArrayList<>();
            for (MagicCubeImportApiRequest file : fileList) {
                //url解析
                byte[] fileBytes = parseUrlToFileByte(file.getFileUrl());
                if (fileBytes == null) {
                    throw new RpcServiceException("1", "文件不存在,请重新选择文件!");
                }
                //上传文件目标服务器的文件名称和文件路径
                String fileName = buildFileName(merchantId, file.getBusinessTypeId() + "", batchNumber);
                String remoteTargetDirectory = buildRemoteTargetDirectory(merchantId + "", file.getBusinessTypeName());
                //上传文件
                String property = environment.getProperty("scrm.datacube.restcloud.independent.deployment", "1");
                String transferMerchant = environment.getProperty(TRANSFER_MERCHANT);
                List<String> transferList = null;
                if (!StringUtils.isEmpty(transferMerchant)) {
                    transferList = Arrays.asList(transferMerchant.split(","));
                }
                Boolean uploadSuccess;
                if (IS_INDEPENDENT_DEPLOYMENT.equals(property) && (transferList == null || transferList.contains(merchantId + ""))) {
                    flag = true;
                    uploadSuccess = true;
                    fileInfoList.add(new DataCubeFileInfo(fileBytes, file.getBusinessTypeId()));
                } else {
                    uploadSuccess = uploadRestCloud(fileBytes, remoteTargetDirectory, fileName);
                }
                if (!uploadSuccess) {
                    throw new RpcServiceException("2", "文件上传失败!");
                }
                //更新日志表
                DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
                logDO.setRcFileName(fileName);
                logDO.setFileSize(fileBytes.length);
                updateDataCubeUploadLog(merchantId, batchNumber, file.getBusinessTypeId(), logDO);
            }
            if (flag) {
                mockCallback(fileInfoList, merchantId, batchNumber);
            }
            //远程调用执行RestCloud清洗(待开发)
            log.info("商户:{},批次:{},RestCloud上传成功", merchantId, batchNumber);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("商户:{},批次:{},RestCloud上传失败:{}", merchantId, batchNumber, e);
            //更新日志表
            DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
            logDO.setState(REST_CLOUD_STATE_FAIL);
            updateDataCubeUploadLog(merchantId, batchNumber, null, logDO);
            //上传失败时执行下一批次
            executeNextBatch(merchantId);
        }
    }

    /**
     * 执行下一批次
     *
     * @param merchantId
     */
    public void executeNextBatch(Integer merchantId) {
        List<DataCubeUploadLogDO> logDOListByState = selectDataCubeUploadLog(merchantId, REST_CLOUD_STATE_WAIT, null, null);
        if (CollectionUtils.isEmpty(logDOListByState)) {
            return;
        }
        String batchNumber = logDOListByState.get(0).getBatchNumber();
        List<DataCubeUploadLogDO> uploadLogDOList = selectDataCubeUploadLog(merchantId, null, batchNumber, null);
        log.info("商户:{}开始执行下一批次:{}", merchantId, uploadLogDOList);
        if (!CollectionUtils.isEmpty(uploadLogDOList)) {
            Map<String, List<DataCubeUploadLogDO>> logByBatchNumber = uploadLogDOList.stream().filter(s -> s.getBatchNumber() != null && s.getCreatedTime() != null)
                    .collect(Collectors.groupingBy(DataCubeUploadLogDO::getBatchNumber));
            String minBatchNumber = uploadLogDOList.stream().min(Comparator.comparing(BaseEntity::getCreatedTime)).get().getBatchNumber();
            List<MagicCubeImportApiRequest> newFileList = logByBatchNumber.get(minBatchNumber).stream().map(s -> {
                MagicCubeImportApiRequest file = new MagicCubeImportApiRequest();
                file.setFileName(s.getFileName());
                file.setFileUrl(s.getFileUrl());
                file.setBusinessTypeId(s.getBusinessType());
                file.setBusinessTypeName(s.getBusinessName());
                return file;
            }).collect(Collectors.toList());
            uploadDataCubeFiles(newFileList, merchantId, minBatchNumber);
        }
    }

    /**
     * RestCloud 账号密码认证
     *
     * @param user     账号
     * @param password 密码
     * @return 认证结果
     */
    public boolean isAuthedWithPassword(String user, String password, Connection connection) {
        try {
            log.info("Connection连接信息ip:{},port:{},user:{},password:{}", connection.getHostname(), connection.getPort(), user, password);
            return connection.authenticateWithPassword(user, password);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 文件服务器url解析
     *
     * @param fileUrl 文件服务器url
     * @return 文件字节
     */
    public byte[] parseUrlToFileByte(String fileUrl) {
        log.info("文件服务器数据魔方url:{}", fileUrl);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Accept", MediaType.ALL_VALUE);
        ResponseEntity<byte[]> response = new RestTemplate().exchange(fileUrl, HttpMethod.GET, new HttpEntity<Byte>(requestHeaders), byte[].class);
        log.info("文件服务器数据statusCode:{},{}", response.getStatusCode(), response.getStatusCodeValue());
        byte[] responseBody = response.getBody();
        if (response.getStatusCodeValue() != 200 || responseBody == null) {
//            throw new RpcServiceException("3","文件服务器数据为空!");
            return null;
        }
        return responseBody;
    }

    /**
     * 文件上传RestCloud
     *
     * @param fileByte              文件字节
     * @param remoteTargetDirectory RestCloud文件路径
     * @param fileName              RestCloud文件名称
     * @return
     */
    public Boolean uploadRestCloud(byte[] fileByte, String remoteTargetDirectory, String fileName) {
        if (fileByte == null || fileByte.length == 0) {
            log.error("文件数据为空:{}", fileByte);
            return false;
        }
        Connection connection = new Connection(REST_CLOUD_IP, REST_CLOUD_PORT);
        try (InputStream bais = new ByteArrayInputStream(fileByte)) {
            connection.connect();
            //服务器用户名和密码认证
            boolean isAuthed = isAuthedWithPassword(USER, PASSWORD, connection);
            if (!isAuthed) {
                log.error("RestCloud建立连接失败!");
                return false;
            }
            SCPClient scpClient = new SCPClient(connection);
            SFTPv3Client sftpv3Client = new SFTPv3Client(connection);
            //创建文件目录
            boolean isdir = cmdMkDir(remoteTargetDirectory, connection);
            if (!isdir) {
                log.error("RestCloud文件目录创建失败!");
                return false;
            }
            log.info("{}:文件正在上传", fileName);
            try (SCPOutputStream os = scpClient.put(fileName, fileByte.length, remoteTargetDirectory, null)) {
                byte[] b = new byte[1024];
                int i;
                while ((i = bais.read(b, 0, b.length)) != -1) {
                    os.write(b, 0, i);
                }
                os.flush();
                boolean chmonFlag = cmdChmod(777, remoteTargetDirectory, fileName, connection);
                if (!chmonFlag) {
                    return false;
                }
                log.info("{}:upload ok", fileName);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("{}:文件上传失败!:{}", fileName, e);
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            connection.close();
        }
        return true;
    }

    /**
     * RestCloud创建文件目录
     *
     * @param remoteTargetDirectory 文件路径
     * @return
     */
    public boolean cmdMkDir(String remoteTargetDirectory, Connection connection) {
        String cmd = "mkdir -p " + remoteTargetDirectory;
        log.info("linux命令创建文件目录:{}", cmd);
        try {
            Session session = connection.openSession();
            try {
                session.execCommand(cmd);
            } finally {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件目录创建失败");
            return false;
        }
        return true;
    }

    /**
     * RestCloud 修改文件权限
     *
     * @param code                  权限码
     * @param remoteTargetDirectory 文件路径
     * @param fileName              文件名称
     */
    public boolean cmdChmod(Integer code, String remoteTargetDirectory, String fileName, Connection connection) {
        //远程执行linux命令 因为上传的文件没有读的文件 需要加上才能下载 (如果你上传的文件有)
        String cmd = "chmod " + code + " " + remoteTargetDirectory + "/" + fileName;
        log.info("linux命令修改文件权限:{}", cmd);
        try {
            Session session = connection.openSession();
            try {
                session.execCommand(cmd);//执行命令
            } finally {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件权限修改失败");
            return false;
        }
        return true;
    }

    /**
     * 生成批次号
     *
     * @return
     */
    public String buildBatchNumber() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        return date + getSeconds();
    }

    /**
     * 生成上传文件的名称
     *
     * @param merchantId       商户号
     * @param businessTypeName 业务名称
     * @return
     */
    public String buildFileName(Integer merchantId, String businessTypeName, String batchNumber) {
        //文件名不能包含斜杠
        String fileName = merchantId + "";
        if (!StringUtils.isEmpty(businessTypeName)) {
            fileName += "_" + businessTypeName;
        }
        if (!StringUtils.isEmpty(batchNumber)) {
            fileName += "_" + batchNumber;
        }
        fileName += ".xlsx";
        log.info("构建文件名称:{}", fileName);
        return fileName;
    }

    /**
     * 生成上传服务器的文件路径
     *
     * @return
     */
    public String buildRemoteTargetDirectory(String merchantId, String businessTypeName) {
        String remoteTargetDirectory = REST_CLOUD_DEFAULT_PATH;
        if (!StringUtils.isEmpty(merchantId)) {
            remoteTargetDirectory += "/" + merchantId;
        }
        if (!StringUtils.isEmpty(businessTypeName)) {
            remoteTargetDirectory += "/" + businessTypeName;
        }
        log.info("构建上传路径:{}", remoteTargetDirectory);
        return remoteTargetDirectory;
    }

    /**
     * 数据魔方日志表新增
     *
     * @param UploadLogList
     */
    public void insertList(List<DataCubeUploadLogDO> UploadLogList) {
        log.info("新增数据魔方日志表:{}", UploadLogList);
        dataCubeUploadLogMapper.insertList(UploadLogList);
    }

    /**
     * 获取当天结束还剩余多少秒
     *
     * @return
     */
    public static synchronized int getSeconds() {
        //获取今天当前时间
        Calendar curDate = Calendar.getInstance();
        //获取明天凌晨0点的日期
        Calendar tommorowDate = new GregorianCalendar(
                curDate.get(Calendar.YEAR),
                curDate.get(Calendar.MONTH),
                curDate.get(Calendar.DATE) + 1,
                3, 0, 0);
        //返回 明天凌晨0点 和 今天当前时间 的差值(秒数)
        try {
            Thread.sleep((int) (Math.random() * 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (int) (tommorowDate.getTimeInMillis() - curDate.getTimeInMillis()) / 100;
    }


    /**
     * 数据魔方模板查询
     *
     * @param merchantId
     */
    public List<DataCubeMerchantConfigResponse> queryDateCubeTemplate(Integer merchantId) {
        if (merchantId == null) {
            throw new RpcServiceException("1", "商户不存在!");
        }
        List<DataCubeMerchantConfigResponse> templateList = dataCubeTemplateConfigMapper.selectDateCubeTemplateByMerchantId(merchantId);
        log.info("数据魔方商户配置模板:{}", templateList);
        if (CollectionUtils.isEmpty(templateList)) {
            throw new RpcServiceException("2", "商户未配置模板!");
        }
        return templateList;
    }

    /**
     * 查询数据魔方上传日志
     *
     * @param merchantId
     * @return
     */
    public List<DataCubeUploadLogDO> selectDataCubeUploadLog(Integer merchantId, Integer state, String batchNumber, Integer businessType) {
        Example example = new Example(DataCubeUploadLogDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delFlag", 0);
        if (merchantId != null) {
            criteria.andEqualTo("merchantId", merchantId);
        }
        if (state != null) {
            criteria.andEqualTo("state", state);
        }
        if (batchNumber != null) {
            criteria.andEqualTo("batchNumber", batchNumber);
        }
        if (businessType != null) {
            criteria.andEqualTo("businessType", businessType);
        }
        List<DataCubeUploadLogDO> uploadLogDOList = dataCubeUploadLogMapper.selectByExample(example);
        log.info("数据魔方查询日志结果:{}", uploadLogDOList);
        return uploadLogDOList;
    }

    /**
     * 分页查询数据魔方日志列表
     */
    public RpcPagination<DataCubeUploadLogResponse> queryDataCubeUploadLogByPage(DataCubeBaseRpcRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Integer merchantId = request.getMerchantId();
        if (merchantId == null) {
            throw new RpcServiceException("1", "商户号不存在!");
        }
        Integer state = request.getState();
        Date startTime = request.getStartTime();
        Date endTime = request.getEndTime();
        if (endTime != null) {
            endTime = DateUtils.addDays(endTime, 1);
        }
        Page<DataCubeUploadLogResponse> logPage = dataCubeUploadLogMapper.selectDataCubeUploadLogByPage(merchantId, state, startTime, endTime);
        if (!CollectionUtils.isEmpty(logPage)) {
//            logPage.stream().filter(s -> s.getFailDataUrl() == null && s.getState() == 1).forEach(s -> {
//                String failedDataurl = findRestCloudFailedData(merchantId, s.getBatchNumber(), s.getBusinessType());
//                s.setFailDataUrl(failedDataurl);
//            });
            Integer createdBy = logPage.get(0).getCreatedBy();
            List<UserResponse> allUser = merchantService.findAllUser(Collections.singletonList(createdBy));
            log.info("createdBy:{}导入人员信息:{}", createdBy, allUser);
            if (!CollectionUtils.isEmpty(allUser)) {
                String userName = allUser.get(0).getUserName();
                logPage.forEach(s -> {
                    s.setCreatedStaff(userName);
                });
            }
        }
        log.info("数据魔方日志列表:{}", logPage);
        return RpcPagination.copyPage(logPage);
    }

    /**
     * 更新日志表
     */
    public void updateDataCubeUploadLog(Integer merchantId, String batchNumber, Integer businessType, DataCubeUploadLogDO logDO) {
        Example example = new Example(DataCubeUploadLogDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andEqualTo("batchNumber", batchNumber);
        if (businessType != null) {
            criteria.andEqualTo("businessType", businessType);
        }
        int i = dataCubeUploadLogMapper.updateByExampleSelective(logDO, example);
        log.info("数据魔方更新日志行数:{}", i);
    }

    /**
     * 更新日志表
     */
    public void updateDataCubeUploadLogByBatchBusinessType(Integer merchantId, String batchNumber, List<Integer> businessType, DataCubeUploadLogDO logDO) {
        Example example = new Example(DataCubeUploadLogDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andEqualTo("batchNumber", batchNumber);
        if (!CollectionUtils.isEmpty(businessType)) {
            criteria.andIn("businessType", businessType);
        }
        int i = dataCubeUploadLogMapper.updateByExampleSelective(logDO, example);
        log.info("数据魔方更新日志行数:{}", i);
    }

    /**
     * PC端数据魔方处理完成提醒
     *
     * @param merchantId
     * @return
     */
    public List<String> noticeReminderToPC(Integer merchantId) {
        if (merchantId == null) {
            throw new RpcServiceException("1", "商户不存在!");
        }
        //未通知消息
        Example example = new Example(DataCubeUploadLogDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andEqualTo("notice", 0);
        criteria.andIn("state", Arrays.asList(REST_CLOUD_STATE_SUCCESS, REST_CLOUD_STATE_FAIL));
        List<DataCubeUploadLogDO> noticeLogList = dataCubeUploadLogMapper.selectByExample(example);
        log.info("数据魔方处理完成PC端通知:{}", noticeLogList);
        List<String> batchNumberList = noticeLogList.stream().map(DataCubeUploadLogDO::getBatchNumber).collect(Collectors.toList());
        //更新日志表
        DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
        logDO.setNotice(1);
        for (String batchNumber : batchNumberList) {
            updateDataCubeUploadLog(merchantId, batchNumber, null, logDO);
        }
        return batchNumberList;
    }

    /**
     * RestCloud上传结果回调
     *
     * @param content
     */
    public void restCloudUploadResultCallback(RestCloudContentRpcRequest content) {
        log.info("RestCloud上传回调content:{}", content);
        Integer merchantId = null;
        int result = content.getResoult() == null ? REST_CLOUD_RESULT_FAIL : content.getResoult();
        try {
            if (ObjectUtils.isEmpty(content)) {
                log.error("RestCloud回调数据为空!");
                return;
            }
            String successFIle = getSuccessFIle(content);
            if (successFIle == null) {
                log.error("RestCloud无执行成功的文件!");
                return;
            }
            DataCubeUploadLogDO successUpload = fileNameResolution(successFIle, null);
            if (successUpload == null) {
                log.error("RestCloud文件名称错误!");
                return;
            }
            int state = REST_CLOUD_STATE_SUCCESS;
            if (result == REST_CLOUD_RESULT_FAIL) {
                state = REST_CLOUD_STATE_FAIL;
            }
            merchantId = successUpload.getMerchantId();
            String batchNumber = successUpload.getBatchNumber();
            Date updateTime = new Date();
            List<DataCubeMerchantConfigResponse> configList = queryDateCubeTemplate(merchantId);
            Map<Integer, List<DataCubeMerchantConfigResponse>> configMapByBusinessType = configList.stream()
                    .collect(Collectors.groupingBy(DataCubeMerchantConfigResponse::getBusinessType));
            for (DataCubeMerchantConfigResponse config : configList) {
                Integer businessTypeId = config.getBusinessType();
                //更新日志表
                DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
                setRestCloudFileResult(businessTypeId, content, logDO);
                String logDOBatchNumber = logDO.getBatchNumber();
                Integer inPutBusinessType = logDO.getBusinessType();
                if (inPutBusinessType == null) {
                    continue;
                }
                logDO.setState(state);
                logDO.setUpdatedTime(updateTime);
                //异常数据文件
                String businessName = configMapByBusinessType.get(inPutBusinessType).get(0).getBusinessName();
                String saveName = businessName + logDOBatchNumber;
                String failedUrl = restCloudFileDownload(logDO.getInPutFile(), saveName, merchantId);
                logDO.setFailDataUrl(httpsConversion(failedUrl));
                updateDataCubeUploadLog(merchantId, logDOBatchNumber, inPutBusinessType, logDO);
            }
            //推送企微消息
            staffSendWechatMessage(merchantId, batchNumber);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据魔方处理错误!");
        }
        if (result != REST_CLOUD_RESULT_FAIL && merchantId != null) {
            //执行下一批次
            executeNextBatch(merchantId);
        }
    }

    /**
     * 员工推送企微消息
     */
    private void staffSendWechatMessage(Integer merchantId, String batchNumber) {
        List<DataCubeUploadLogDO> uploadLogDOList = selectDataCubeUploadLog(merchantId, null, batchNumber, null);
        if (CollectionUtils.isEmpty(uploadLogDOList)) {
            return;
        }
        DataCubeUploadLogDO logDO = uploadLogDOList.get(0);
        if (ObjectUtils.isEmpty(logDO)) {
            return;
        }
        String followStaffId = logDO.getFollowStaffId();
        if (StringUtils.isEmpty(followStaffId)) {
            return;
        }
        String[] staffArray = followStaffId.split(",");
        WechatMessageModel wechatMessageModel = new WechatMessageModel();
        wechatMessageModel.setMerchantId(merchantId);
        wechatMessageModel.setContent("【数据魔方分析完毕通知】\n本次处理的数据批次为:" + batchNumber + ",请登陆【SCRM门店后台系统-企微魔方】查看详情。");
        for (String staffId : staffArray) {
            List<EntmicroStaffResponse> staffById = entmicroStaffMapper.getStaffById(Collections.singletonList(Integer.parseInt(staffId)));
            String userId = staffById.get(0).getUserId();
            wechatMessageModel.setUserId(userId);
            commonService.sendSingleWechatMessage(wechatMessageModel);
        }
    }

    /**
     * https转换
     */
    public String httpsConversion(String url) {
        if (!StringUtils.isEmpty(url) && url.startsWith("http:")) {
            StringBuilder stringBuilder = new StringBuilder(url);
            url = stringBuilder.insert(4, "s").toString();
        }
        return url;
    }

    /**
     * RestCloud文件名称解析
     *
     * @param fileName
     * @param logDO
     * @return
     */
    public DataCubeUploadLogDO fileNameResolution(String fileName, DataCubeUploadLogDO logDO) {
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            fileName = fileName.substring(0, index);
        }
        String[] split = fileName.trim().split("_");
        if (split.length < 3) {
            return null;
        }
        if (logDO == null) {
            logDO = new DataCubeUploadLogDO();
        }
        Integer merchantId = Integer.parseInt(split[0]);
        Integer businessType = Integer.parseInt(split[1]);
        String batchNumber = split[2];
        logDO.setMerchantId(merchantId);
        logDO.setBusinessType(businessType);
        logDO.setBatchNumber(batchNumber);
        return logDO;
    }

    /**
     * 查询文件RestCloud处理异常数据(废弃)
     */
    public String findRestCloudFailedData(Integer merchantId, String batchNumber, Integer businessTypeId) {
        Example example = new Example(DataCubeUploadLogDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andEqualTo("batchNumber", batchNumber);
        if (businessTypeId != null) {
            criteria.andEqualTo("businessType", businessTypeId);
        }
        List<DataCubeUploadLogDO> logDOList = dataCubeUploadLogMapper.selectByExample(example);
        String failedDataUrl = null;
        log.info("商户:{},批次号:{},业务类型:{},RestCloud异常数据:{}", merchantId, batchNumber, businessTypeId, logDOList);
        if (!CollectionUtils.isEmpty(logDOList)) {
            DataCubeUploadLogDO logDO = logDOList.get(0);
            failedDataUrl = restCloudFileDownload(logDO.getInPutFile(), logDO.getFileName(), merchantId);
            DataCubeUploadLogDO updateLogDO = new DataCubeUploadLogDO();
            updateLogDO.setFailDataUrl(failedDataUrl);
            updateDataCubeUploadLog(merchantId, batchNumber, businessTypeId, updateLogDO);
        }
        return failedDataUrl;
    }

    /**
     * RestCloud文件下载
     *
     * @param searchName
     * @param saveName
     * @return
     */
    public String restCloudFileDownload(String searchName, String saveName, Integer merchantId) {
        if (StringUtils.isEmpty(searchName) || StringUtils.isEmpty(saveName)) {
            return null;
        }
        int index = saveName.lastIndexOf(".");
        if (index != -1) {
            saveName = saveName.substring(0, index);
        }
        searchName = searchName + ".xlsx";
        Connection connection = new Connection(REST_CLOUD_IP, REST_CLOUD_PORT);
        try (ByteArrayOutputStream ops = new ByteArrayOutputStream();) {
            connection.connect();
            boolean isAuthed = isAuthedWithPassword(USER, PASSWORD, connection);
            if (!isAuthed) {
                log.error("RestCloud建立连接失败!");
                return null;
            }
            SCPClient scpClient = connection.createSCPClient();
            //从目标文件服务器下载文件
            String filePath = String.format(EXCEPTION_DATA_FILE_PATH, merchantId, searchName);
            SCPInputStream sis = scpClient.get(filePath);
            byte[] b = new byte[4096];
            int i;
            while ((i = sis.read(b)) != -1) {
                ops.write(b, 0, i);
            }
            sis.close();
            log.info("RestCloud download ok");
            byte[] bytes = ops.toByteArray();
            FileUploadServerData uploadResult = FileUploadUtil.uploadToFileSystem(saveName, bytes, "xlsx");
            log.info("文件服务器上传结果:{}", uploadResult);
            if (uploadResult != null) {
                return uploadResult.getUrl();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("RestCloud下载文件异常" + e);
            return null;
        } finally {
            connection.close();
        }
    }

    /**
     * 获取RestCloud对应文件参数
     *
     * @param businessTypeId
     * @param content
     * @return
     */
    public DataCubeUploadLogDO setRestCloudFileResult(Integer businessTypeId, RestCloudContentRpcRequest content, DataCubeUploadLogDO logDO) {
        log.info("执行业务类型:{}", businessTypeId);
        if (logDO == null) {
            logDO = new DataCubeUploadLogDO();
        }
        if (businessTypeId == null || ObjectUtils.isEmpty(content)) {
            return logDO;
        }
        logDO.setResult(content.getResoult());
        switch (businessTypeId) {
            case 1:
                String inPutFile1 = content.getInPutFile1();
                logDO.setInPutFile(inPutFile1);
                fileNameResolution(inPutFile1, logDO);
                logDO.setFileExist(content.getFileExist1());
                logDO.setKeyValueCheck(content.getKeyValueCheck1());
                break;
            case 2:
                String inPutFile2 = content.getInPutFile2();
                logDO.setInPutFile(inPutFile2);
                fileNameResolution(inPutFile2, logDO);
                logDO.setFileExist(content.getFileExist2());
                logDO.setKeyValueCheck(content.getKeyValueCheck2());
                break;
            case 3:
                String inPutFile3 = content.getInPutFile3();
                logDO.setInPutFile(inPutFile3);
                fileNameResolution(inPutFile3, logDO);
                logDO.setFileExist(content.getFileExist3());
                logDO.setKeyValueCheck(content.getKeyValueCheck3());
                break;
            case 4:
                String inPutFile4 = content.getInPutFile4();
                logDO.setInPutFile(inPutFile4);
                fileNameResolution(inPutFile4, logDO);
                logDO.setFileExist(content.getFileExist4());
                logDO.setKeyValueCheck(content.getKeyValueCheck4());
                break;
            case 5:
                String inPutFile5 = content.getInPutFile5();
                logDO.setInPutFile(inPutFile5);
                fileNameResolution(inPutFile5, logDO);
                logDO.setFileExist(content.getFileExist4());
                logDO.setKeyValueCheck(content.getKeyValueCheck4());
                break;
            case 6:
                String inPutFile6 = content.getInPutFile6();
                logDO.setInPutFile(inPutFile6);
                fileNameResolution(inPutFile6, logDO);
                logDO.setFileExist(content.getFileExist4());
                logDO.setKeyValueCheck(content.getKeyValueCheck4());
                break;
            default:
                break;
        }
        return logDO;
    }

    /**
     * 查找RestCloud执行成功的文件
     *
     * @return
     */
    public String getSuccessFIle(RestCloudContentRpcRequest content) {
        DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
        for (int i = 1; i <= REST_CLOUD_FILE_TOTAL_MAX; i++) {
            logDO = setRestCloudFileResult(i, content, logDO);
            String inPutFile = logDO.getInPutFile();
            if (!StringUtils.isEmpty(inPutFile)) {
                return inPutFile;
            }
        }
        return null;
    }

    /**
     * 启动restcloud执行流程
     *
     * @param merchantId 商户号
     * @return 启动结果
     */
    public Boolean startProcess(Integer merchantId) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        String response = restTemplate.postForObject(REST_CLOUD_BASE_URL, form, String.class);
        log.info("response=============" + response);
        return true;
    }


    /***********************************************  self restcloud  *******************************************************/

    public void reportDataProcess(String json) {
        Integer merchantId;
        Integer templateId;
        byte[] fileByte;
        if (json.startsWith("[")) {
            List<JSONObject> list = JSON.parseArray(json, JSONObject.class);
            JSONObject jsonObject = list.get(0);
            templateId = (Integer) jsonObject.get("template_id");
            String defaultTemplateId = environment.getProperty("scrm.datacube.restcloud.templateId.default", "49");
            templateId = templateId == null ? Integer.parseInt(defaultTemplateId) : templateId;
            merchantId = (Integer) jsonObject.get("merchant_id");
            fileByte = json2ExcelByte(list);
        } else {
            JSONObject jsonObject = JSON.parseObject(json);
            templateId = (Integer) jsonObject.get("template_id");
            String defaultTemplateId = environment.getProperty("scrm.datacube.restcloud.templateId.default", "49");
            templateId = templateId == null ? Integer.parseInt(defaultTemplateId) : templateId;
            merchantId = (Integer) jsonObject.get("merchant_id");
            fileByte = json2ExcelByte(jsonObject);
        }

        if (fileByte == null) {
            return;
        }
        String batchNumber = "R" + getSeconds();
        List<JSONObject> dataList = reportRestCloud(fileByte, merchantId, templateId, batchNumber);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (JSONObject data : dataList) {
                sendDataToCDPKafka(data.toJSONString());
            }
        }
    }

    public static byte[] json2ExcelByte(JSONObject jsonObject) {
        byte[] excelBytes = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\chizw\\Desktop\\1111.xlsx")) {
            List<List<String>> head = new ArrayList<>();
            List<Object> dataInner = new ArrayList<>();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                head.add(Collections.singletonList(entry.getKey()));
                dataInner.add(entry.getValue());
            }
            List<List<Object>> data = Collections.singletonList(dataInner);
            EasyExcelFactory.write(outputStream).head(head).sheet("Sheet1").doWrite(data);
            EasyExcelFactory.write(fileOutputStream).head(head).sheet("Sheet1").doWrite(data);
            excelBytes = outputStream.toByteArray();
        } catch (Exception e) {
            log.error("restcloud report json2ExcelByte error:{}", e.getMessage(), e);
        }
        return excelBytes;
    }

    public static byte[] json2ExcelByte(List<JSONObject> list) {
        byte[] excelBytes = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\chizw\\Desktop\\1111.xlsx")) {
            Set<String> set = new HashSet<>();
            for (JSONObject jsonObject : list) {
                set.addAll(jsonObject.keySet());
            }
            List<List<String>> head = new ArrayList<>();
            for (String key : set) {
                head.add(Collections.singletonList(key));
            }
            List<List<Object>> dataList = new ArrayList<>();
            for (JSONObject jsonObject : list) {
                List<Object> dataInner = new ArrayList<>(list.size());
                for (String key : set) {
                    dataInner.add(jsonObject.get(key));
                }
                dataList.add(dataInner);
            }
            EasyExcelFactory.write(outputStream).head(head).sheet("Sheet1").doWrite(dataList);
            EasyExcelFactory.write(fileOutputStream).head(head).sheet("Sheet1").doWrite(dataList);
            excelBytes = outputStream.toByteArray();
        } catch (Exception e) {
            log.error("restcloud report json2ExcelByte error:{}", e.getMessage(), e);
        }
        return excelBytes;
    }

    private void mockCallback(List<DataCubeFileInfo> fileInfoList, Integer merchantId, String batchNumber) {
        log.info("restcloud模拟回调 merchantId:{},batchNumber:{},fileInfoList{}", merchantId, batchNumber, fileInfoList);
        for (DataCubeFileInfo fileInfo : fileInfoList) {
            selfResearchRestCloud(fileInfo.getFileByte(), merchantId, fileInfo.getBusinessType(), batchNumber);
        }
        staffSendWechatMessage(merchantId, batchNumber);
        executeNextBatch(merchantId);
    }

    /**
     * 自研restcloud
     *
     * @param fileByte     导入文件流
     * @param merchantId   商户号
     * @param businessType 业务类型
     */
    public void selfResearchRestCloud(byte[] fileByte, Integer merchantId, Integer businessType, String batchNumber) {

        DataCubeTemplateConfigDO templateConfigDO = dataCubeTemplateConfigMapper.selectTemplateConfigIdByMerchant(merchantId, businessType);
        if (templateConfigDO == null) throw new RpcServiceException("商户未配置模板,请联系管理员处理");

        Integer templateId = templateConfigDO.getTemplateId();
        List<DataCubeTableConfigInfo> tableConfigInfoList = selectTableInfoByConfigId(templateId);
        if (CollectionUtils.isEmpty(tableConfigInfoList))
            throw new RpcServiceException("未对商户模板字段进行配置,请联系管理员处理");

        DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
        logDO.setUpdatedTime(new Date());
        int state = REST_CLOUD_STATE_SUCCESS;
        try (
                InputStream inputStream = new ByteArrayInputStream(fileByte);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            SelfResearchRestCloudListener selfResearchRestCloudListener = new SelfResearchRestCloudListener(tableConfigInfoList);
            int headRowNumber = 1;
            Integer headerRow = templateConfigDO.getHeaderRow();
            if (headerRow != null && headerRow > 1) {
                headRowNumber = headerRow;
            }
            EasyExcelFactory.read(inputStream, selfResearchRestCloudListener).sheet().headRowNumber(headRowNumber).doRead();
            List<JSONObject> dataList = selfResearchRestCloudListener.getDataList();
            log.info("数据魔方导入成功数据 dataList:{}", dataList);
            List<List<Object>> failList = selfResearchRestCloudListener.getFailList();
            log.info("数据魔方导入异常数据 failList:{}", failList);
            if (!CollectionUtils.isEmpty(dataList)) {
                for (JSONObject jsonObject : dataList) {
                    jsonObject.put(ADD_WAY_FIELD, DATA_CUBE_ADD_WAY);
                    jsonObject.put(MERCHANT_ID_FIELD, merchantId);
                    sendDataToCDPKafka(jsonObject.toJSONString());
                }
            }
            if (!CollectionUtils.isEmpty(failList)) {
                List<List<String>> head = selfResearchRestCloudListener.buildWriteHead();
                EasyExcelFactory.write(outputStream).head(head).registerWriteHandler(new headStyle()).sheet().doWrite(failList);
                FileUploadServerData fileUploadServerData = FileUploadUtil.uploadToFileSystem("异常数据文件" + System.currentTimeMillis(),
                        outputStream.toByteArray(), "xlsx");
                String url = httpsConversion(fileUploadServerData.getUrl());
                log.info("数据魔方导入异常文件 url:{}", url);
                logDO.setFailDataUrl(url);
            }
            logDO.setTotalReadCount(selfResearchRestCloudListener.getRowNum());
            logDO.setTotalSuccessCount(dataList.size());
            logDO.setTotalFailedCount(failList.size());
        } catch (Exception e) {
            log.error("数据魔方导入错误 err_msg:{}", e.getMessage(), e);
            String exception = e + e.getMessage() + Arrays.toString(e.getStackTrace());
            logDO.setExceptionInfo(exception);
            state = REST_CLOUD_STATE_FAIL;
        }
        logDO.setState(state);
        updateDataCubeUploadLog(merchantId, batchNumber, businessType, logDO);
    }

    public List<JSONObject> reportRestCloud(byte[] fileByte, Integer merchantId, Integer templateId, String batchNumber) {
        List<JSONObject> dataList = new ArrayList<>();
        List<DataCubeTableConfigInfo> tableConfigInfoList = selectTableInfoByConfigId(templateId);
        if (CollectionUtils.isEmpty(tableConfigInfoList))
            throw new RpcServiceException("未对商户模板字段进行配置,请联系管理员处理");
        DataCubeUploadLogDO logDO = new DataCubeUploadLogDO();
        logDO.setUpdatedTime(new Date());
        int state = REST_CLOUD_STATE_SUCCESS;
        try (
                InputStream inputStream = new ByteArrayInputStream(fileByte);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            SelfResearchRestCloudListener selfResearchRestCloudListener = new SelfResearchRestCloudListener(tableConfigInfoList);
            EasyExcelFactory.read(inputStream, selfResearchRestCloudListener).sheet().doRead();
            dataList = selfResearchRestCloudListener.getDataList();
            log.info("数据魔方导入成功数据 dataList:{}", dataList);
            List<List<Object>> failList = selfResearchRestCloudListener.getFailList();
            log.info("数据魔方导入异常数据 failList:{}", failList);
            if (!CollectionUtils.isEmpty(failList)) {
                List<List<String>> head = selfResearchRestCloudListener.buildWriteHead();
                EasyExcelFactory.write(outputStream).head(head).registerWriteHandler(new headStyle()).sheet().doWrite(failList);
                FileUploadServerData fileUploadServerData = FileUploadUtil.uploadToFileSystem("异常数据文件" + System.currentTimeMillis(),
                        outputStream.toByteArray(), "xlsx");
                String url = httpsConversion(fileUploadServerData.getUrl());
                log.info("数据魔方导入异常文件 url:{}", url);
                logDO.setFailDataUrl(url);
            }
            logDO.setTotalReadCount(selfResearchRestCloudListener.getRowNum());
            logDO.setTotalSuccessCount(dataList.size());
            logDO.setTotalFailedCount(failList.size());
        } catch (Exception e) {
            log.error("数据魔方导入错误 err_msg:{}", e.getMessage(), e);
            String exception = e + e.getMessage() + Arrays.toString(e.getStackTrace());
            logDO.setExceptionInfo(exception);
            state = REST_CLOUD_STATE_FAIL;
        }
        logDO.setState(state);
//        updateDataCubeUploadLog(merchantId, batchNumber, businessType, logDO);
        return dataList;
    }

    public static class headStyle extends AbstractColumnWidthStyleStrategy {

        private static final int MAX_COLUMN_WIDTH = 255;
        private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);
        // 保底宽度
        private static final int COLUMN_WIDTH = 15;

        @Override
        protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
                                      Head head, Integer relativeRowIndex, Boolean isHead) {
            boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
            if (needSetWidth) {
                Map<Integer, Integer> maxColumnWidthMap = CACHE.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>());

                Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
                if (columnWidth > MAX_COLUMN_WIDTH) {
                    columnWidth = MAX_COLUMN_WIDTH;
                }
                if (columnWidth < COLUMN_WIDTH) {
                    columnWidth = COLUMN_WIDTH;
                }
                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    Sheet sheet = writeSheetHolder.getSheet();
                    sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }
            }
        }

        private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
            if (isHead) {
                return cell.getStringCellValue().getBytes().length;
            } else {
                CellData<?> cellData = cellDataList.get(0);
                CellDataTypeEnum type = cellData.getType();
                if (type == null) {
                    return -1;
                } else {
                    switch (type) {
                        case STRING:
                            // 换行符(数据需要提前解析好)
                            int index = cellData.getStringValue().indexOf("\n");
                            return index != -1 ?
                                    cellData.getStringValue().substring(0, index).getBytes().length + 1 : cellData.getStringValue().getBytes().length + 1;
                        case BOOLEAN:
                            return cellData.getBooleanValue().toString().getBytes().length;
                        case NUMBER:
                            return cellData.getNumberValue().toString().getBytes().length;
                        default:
                            return -1;
                    }
                }
            }
        }
    }

    public List<DataCubeTableConfigInfo> selectTableInfoByConfigId(Integer configId) {
        List<DataCubeTableConfigInfo> tableConfigInfoList = dataCubeTableFieldRelationMapper.selectTableInfoByConfigId(configId);
        log.info("数据魔方模板字段配置 tableConfigInfoList:{}", tableConfigInfoList);
        return tableConfigInfoList;
    }

    /**
     * 推送数据到CDP模块
     *
     * @param json json数据
     */
    public void sendDataToCDPKafka(String json) {
        //推送CDP模块
        producerComponent.sendCustomerToKafka(json);
    }

    public List<DataCubeTableConfigInfo> getHeaderConfigList() {
        List<DataCubeTableConfigInfo> configInfoList = new ArrayList<>();
        configInfoList.add(new DataCubeTableConfigInfo("客户名称", "customer_name"));
        configInfoList.add(new DataCubeTableConfigInfo("企微名称", "customer_qw_nickname"));
        configInfoList.add(new DataCubeTableConfigInfo("手机号", "customer_phone"));
        configInfoList.add(new DataCubeTableConfigInfo("车辆品牌", "car_brand"));
        configInfoList.add(new DataCubeTableConfigInfo("车系", "car_series"));
        configInfoList.add(new DataCubeTableConfigInfo("车型", "car_model"));
        configInfoList.add(new DataCubeTableConfigInfo("车牌号", "car_number"));
        configInfoList.add(new DataCubeTableConfigInfo("车架号", "car_vin"));
        configInfoList.add(new DataCubeTableConfigInfo("车辆价格", "car_buy_price"));
        configInfoList.add(new DataCubeTableConfigInfo("购车时间", "car_buy_date"));
        configInfoList.add(new DataCubeTableConfigInfo("车险开始时间", "ins_start_date"));
        return configInfoList;
    }

    /**
     * 替代表结构测试流程
     *
     * @return
     */
    public Map<String, MagicTemplateConfigInfo> getAllHeadTitleMap() {
        Map<String, MagicTemplateConfigInfo> allHeadTitleMap = new HashMap<>();
//            allHeadTitleMap.put("客户id", new MagicTemplateConfigInfo("customer_id",null,null,null));
//        allHeadTitleMap.put("性别", new MagicTemplateConfigInfo("customer_sex",null,null,null));
//            allHeadTitleMap.put("跟进员工", new MagicTemplateConfigInfo("customer_phone",null,null,null));
//            allHeadTitleMap.put("是否已加企微", new MagicTemplateConfigInfo("customer_phone",null,null,null));
//            allHeadTitleMap.put("年款", new MagicTemplateConfigInfo("customer_phone",null,null,null));
//        allHeadTitleMap.put("当前状态", new MagicTemplateConfigInfo("customer_phone",null,null,null));
//        allHeadTitleMap.put("所属渠道", new MagicTemplateConfigInfo("add_way",null,null,null));
//        allHeadTitleMap.put("添加来源", new MagicTemplateConfigInfo("add_way",null,null,null));
        allHeadTitleMap.put("客户名称", new MagicTemplateConfigInfo("customer_name", null, null, null));
        allHeadTitleMap.put("企微名称", new MagicTemplateConfigInfo("customer_qw_nickname", null, null, null));
        allHeadTitleMap.put("手机号", new MagicTemplateConfigInfo("customer_phone", null, null, null));
        allHeadTitleMap.put("车辆品牌", new MagicTemplateConfigInfo("car_brand", null, null, null));
        allHeadTitleMap.put("车系", new MagicTemplateConfigInfo("car_series", null, null, null));
        allHeadTitleMap.put("车型", new MagicTemplateConfigInfo("car_model", null, null, null));
        allHeadTitleMap.put("车牌号", new MagicTemplateConfigInfo("car_number", null, null, null));
        allHeadTitleMap.put("车架号", new MagicTemplateConfigInfo("car_vin", null, null, null));
        allHeadTitleMap.put("车辆价格", new MagicTemplateConfigInfo("car_buy_price", null, null, null));
        allHeadTitleMap.put("购车时间", new MagicTemplateConfigInfo("car_buy_date", null, null, null));
        allHeadTitleMap.put("车险开始时间", new MagicTemplateConfigInfo("ins_start_date", null, null, null));
        allHeadTitleMap.put("车险到期时间", new MagicTemplateConfigInfo("ins_end_date", null, null, null));
        allHeadTitleMap.put("最近保养时间", new MagicTemplateConfigInfo("ma_last_time", null, null, null));
        allHeadTitleMap.put("最近到店时间", new MagicTemplateConfigInfo("enter_last_time", null, null, null));
        allHeadTitleMap.put("首次添加时间", new MagicTemplateConfigInfo("create_time", null, null, null));
        return allHeadTitleMap;
    }

    /**
     * 返回excel
     *
     * @param inputStream 文件流
     * @param failListMap 错误的数据
     * @param response    响应体
     * @author tzh
     */
    private void downloadExcel(InputStream inputStream, Map<Integer, Map<Integer, FailRecord>> failListMap,
                               HttpServletResponse response) throws IOException {
        OutputStream osOut = null;
        try {
            Workbook workbook = WorkbookFactory.create(inputStream);
            compileExcel(workbook, failListMap);

            String fileName = "客户列表";
//            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 形成输出流
            osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            workbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (osOut != null) {
                osOut.close();
            }
        }
    }

    /**
     * 编辑excel
     *
     * @param workbook    workbook
     * @param failListMap 错误数据
     * @author tzh
     */
    private void compileExcel(Workbook workbook, Map<Integer, Map<Integer, FailRecord>> failListMap) {
        Sheet sheet = workbook.getSheetAt(0);
        Set<Integer> rows = failListMap.keySet();
        //初始化所有字体颜色
        initFontColor(workbook, sheet);

        for (Integer row : rows) {
            Row row1 = sheet.getRow(row);
            Map<Integer, FailRecord> map = failListMap.get(row);
            Set<Integer> cloumns = map.keySet();
            for (Integer cloumn : cloumns) {
                Cell cell = row1.getCell(cloumn);
                if (cell == null) {
                    Cell cell1 = row1.createCell(cloumn);
                    fillStyle(cell1, workbook, sheet, row, cloumn, map);
                } else {
                    fillStyle(cell, workbook, sheet, row, cloumn, map);
                }
            }
        }
    }

    /**
     * 初始化所有字体颜色
     */
    private void initFontColor(Workbook workbook, Sheet sheet) {
        Cell cell2 = sheet.getRow(2).getCell(0);
        CellStyle cellStyle = sheet.getRow(2).getCell(0).getCellStyle();
        //设置垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        //设置字体为正常
        font.setColor(Font.COLOR_NORMAL);
        cellStyle.setFont(font);
        cell2.setCellStyle(cellStyle);
    }

    /**
     * 填充错误的颜色和批注样式
     */
    private void fillStyle(Cell cell, Workbook workbook, Sheet sheet, Integer row, Integer cloumn, Map<Integer,
            FailRecord> map) {
        if (cell.toString().length() == 0) {
            cell.setCellValue(map.get(cloumn).getMsg());
        }
        CellStyle cellStyle = workbook.createCellStyle();
        //设置垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();

        //设置字体为红色
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();

        Comment comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0,
                (short) (row + 0), cloumn, (short) (row + 1), cloumn + 1));

        comment.setString(new XSSFRichTextString(map.get(cloumn).getMsg()));
        cell.setCellComment(comment);
        cell.setCellStyle(cellStyle);
    }

    /***********************************************  DB Manage  *****************************************************/

    /**
     * 查询模板list
     */
    public RpcPagination<TemplateConfigResponse> findMerchantConfigList(RpcPagination<DataCubeMerchantRequest> request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<TemplateConfigResponse> templateList = dataCubeTemplateConfigMapper.findTemplateList(request.getCondition());
        return RpcPagination.copyPage(templateList);
    }

    /**
     * 查询详情
     *
     * @return 模板详情
     */
    public TemplateConfigResponse findByTemplateId(Integer id) {
        TemplateConfigResponse templateConfigResponse = dataCubeTemplateConfigMapper.findByTemplateId(id);
        if (templateConfigResponse != null) {
            List<DataCubeTableConfigInfo> dataCubeTableConfigInfos = dataCubeTableFieldRelationMapper.selectTableInfoByConfigId(templateConfigResponse.getTemplateId());
            if (!CollectionUtils.isEmpty(dataCubeTableConfigInfos)) {
                templateConfigResponse.setTableConfigInfoResponses(dataCubeTableConfigInfos.stream().map(index -> {
                    TableConfigInfoResponse tableConfigInfoResponse = new TableConfigInfoResponse();
                    BeanUtils.copyProperties(index, tableConfigInfoResponse);
                    return tableConfigInfoResponse;
                }).collect(Collectors.toList()));
            }
        }
        return templateConfigResponse;
    }

    /**
     * 查询模板list
     *
     * @param request 入参
     */
    public RpcPagination<DataPoolResponse> findPoolPagelList(RpcPagination<DataPoolSearchRequest> request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<DataPoolResponse> dataPoolResponses = dataCubeFieldPoolMapper.findPoolList(request.getCondition());
        return RpcPagination.copyPage(dataPoolResponses);
    }

    /**
     * 查询模板list
     *
     * @param id 主键id
     */
    public DataPoolResponse findPoolDetail(Integer id) {
        DataPoolResponse dataPoolResponses = new DataPoolResponse();
        DataCubeFieldPoolDO dataCubeFieldPoolDO = dataCubeFieldPoolMapper.selectByPrimaryKey(id);
        if (dataCubeFieldPoolDO != null) {
            BeanUtils.copyProperties(dataCubeFieldPoolDO, dataPoolResponses);
        }
        return dataPoolResponses;
    }

    /**
     * 新增字段池
     *
     * @param dataCubeFieldPoolDORequest 主键id
     */
    public void savePool(DataCubeFieldPoolDORequest dataCubeFieldPoolDORequest) {
        checkUnionPoolName(dataCubeFieldPoolDORequest);
        DataCubeFieldPoolDO dataCubeFieldPoolDO = new DataCubeFieldPoolDO();
        BeanUtils.copyProperties(dataCubeFieldPoolDORequest, dataCubeFieldPoolDO);
        dataCubeFieldPoolDO.setCreatedTime(new Date());
        dataCubeFieldPoolDO.setDelFlag(Constants.NORMAL_FLAG);
        Integer id = dataCubeFieldPoolMapper.findMaxId();
        dataCubeFieldPoolDO.setCdpFieldIndex(id + 1);
        dataCubeFieldPoolMapper.insertSelective(dataCubeFieldPoolDO);
    }

    /**
     * 新增字段池
     *
     * @param dataCubeFieldPoolDORequest 主键id
     */
    public void updatePool(DataCubeFieldPoolDORequest dataCubeFieldPoolDORequest) {
        checkUnionPoolName(dataCubeFieldPoolDORequest);
        DataCubeFieldPoolDO dataCubeFieldPoolDO = new DataCubeFieldPoolDO();
        BeanUtils.copyProperties(dataCubeFieldPoolDORequest, dataCubeFieldPoolDO);
        dataCubeFieldPoolDO.setUpdatedTime(new Date());
        dataCubeFieldPoolMapper.updateByPrimaryKeySelective(dataCubeFieldPoolDO);
    }

    /**
     * 校验规则
     *
     * @param dataCubeFieldPoolDORequest
     */
    private void checkUnionPoolName(DataCubeFieldPoolDORequest dataCubeFieldPoolDORequest) {
        String fieldName = dataCubeFieldPoolDORequest.getFieldName();
        List<DataCubeFieldPoolDO> dataCubeFieldPoolDOS = dataCubeFieldPoolMapper.selectAll();
        if (!CollectionUtils.isEmpty(dataCubeFieldPoolDOS)) {
            List<DataCubeFieldPoolDO> collect = dataCubeFieldPoolDOS.stream().filter(index -> index.getFieldName() != null && index.getFieldName().equals(fieldName)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                throw new RpcServiceException(DefaultErrorEnum.DATA_EXIST);
            }
        }
    }

    /**
     * 查询所有字段池
     */
    public List<DataPoolResponse> findPoolList() {
        Page<DataPoolResponse> dataPoolResponses = dataCubeFieldPoolMapper.findPoolList(new DataPoolSearchRequest());
        return dataPoolResponses.getResult();
    }

    /**
     * 新增商户配置
     *
     * @param templateConfigRequest
     */
    public void saveMerchantConfig(TemplateConfigRequest templateConfigRequest) {
        DataCubeMerchantConfigDO dataCubeMerchantConfigDO = new DataCubeMerchantConfigDO();
        BeanUtils.copyProperties(templateConfigRequest, dataCubeMerchantConfigDO);
        checkMerchantConfig(dataCubeMerchantConfigDO);
        dataCubeMerchantConfigDO.setCreatedTime(new Date());
        dataCubeMerchantConfigDO.setDelFlag(Constants.NORMAL_FLAG);
        dataCubeMerchantConfigDO.setUpdatedTime(new Date());
        dataCubeTemplateConfigMapper.insertUseGeneratedKeys(dataCubeMerchantConfigDO);
        List<TableConfigInfoResponse> tableConfigInfoResponses = templateConfigRequest.getTableConfigInfoResponses();
        if (!CollectionUtils.isEmpty(tableConfigInfoResponses)) {
            List<DataCubeConfigFieldRelationDO> collect = tableConfigInfoResponses.stream().map(index -> {
                DataCubeConfigFieldRelationDO dataCubeConfigFieldRelationDO = new DataCubeConfigFieldRelationDO();
                BeanUtils.copyProperties(index, dataCubeConfigFieldRelationDO);
                dataCubeConfigFieldRelationDO.setDelFlag(Constants.NORMAL_FLAG);
                return dataCubeConfigFieldRelationDO;
            }).collect(Collectors.toList());
            dataCubeTableFieldRelationMapper.insertList(collect);
        }
    }

    /**
     * 更新商户配置
     *
     * @param templateConfigRequest
     */
    public void updateMerchantConfig(TemplateConfigRequest templateConfigRequest) {
        DataCubeMerchantConfigDO dataCubeMerchantConfigDO = new DataCubeMerchantConfigDO();
        BeanUtils.copyProperties(templateConfigRequest, dataCubeMerchantConfigDO);
        checkMerchantConfig(dataCubeMerchantConfigDO);
        dataCubeMerchantConfigDO.setUpdatedTime(new Date());
        dataCubeTemplateConfigMapper.updateByPrimaryKeySelective(dataCubeMerchantConfigDO);
      /*  List<TableConfigInfoResponse> tableConfigInfoResponses = templateConfigRequest.getTableConfigInfoResponses();
        if (!CollectionUtils.isEmpty(tableConfigInfoResponses)) {
            List<DataCubeConfigFieldRelationDO> dataCubeTableConfigInfoList = tableConfigInfoResponses.stream().map(index -> {
                DataCubeConfigFieldRelationDO dataCubeTableConfigInfo = new DataCubeConfigFieldRelationDO();
                BeanUtils.copyProperties(index, dataCubeMerchantConfigDO);
                dataCubeTableConfigInfo.setDelFlag(Constants.NORMAL_FLAG);
                return dataCubeTableConfigInfo;
            }).collect(Collectors.toList());
            List<DataCubeConfigFieldRelationDO> addList = new ArrayList<>();
            List<DataCubeConfigFieldRelationDO> updateList = new ArrayList<>();
            List<Integer> deleteList = new ArrayList<>();
            List<DataCubeTableConfigInfo> dataCubeTableConfigInfos = dataCubeTableFieldRelationMapper.selectTableInfoByConfigId(templateConfigRequest.getTemplateId());
            if (!CollectionUtils.isEmpty(dataCubeTableConfigInfos)) {
                addList = dataCubeTableConfigInfoList;
            } else {
                List<Integer> collect = dataCubeTableConfigInfoList.stream().map(DataCubeConfigFieldRelationDO::getId).collect(Collectors.toList());
                updateList = dataCubeTableConfigInfoList.stream().filter(index -> collect.contains(index.getId())).collect(Collectors.toList());
                deleteList = dataCubeTableConfigInfos.stream().filter(index -> !collect.contains(index.getId())).map(DataCubeTableConfigInfo::getId).collect(Collectors.toList());
                addList = dataCubeTableConfigInfoList.stream().filter(index -> index.getId() == null).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(addList)) {
                dataCubeTableFieldRelationMapper.insertList(addList);
            }
            if (!CollectionUtils.isEmpty(updateList)) {
                dataCubeTableFieldRelationMapper.updateList(updateList);
            }
            if (!CollectionUtils.isEmpty(deleteList)) {
                dataCubeTableFieldRelationMapper.deleteList(deleteList);
            }
        }*/
    }

    private void checkMerchantConfig(DataCubeMerchantConfigDO dataCubeMerchantConfigDO) {
        List<DataCubeMerchantConfigDO> dataCubeMerchantConfigDOS = dataCubeTemplateConfigMapper.selectAll();
    }

    /**
     * 查询模板list
     */
    public List<DataCubeTemplateConfigResponse> findTemplateList() {
        List<DataCubeTemplateConfigResponse> list = new ArrayList<>();
        List<DataCubeTemplateConfigDO> dataCubeTemplateConfigDOS = templateConfigMapper.selectAll();
        if (!CollectionUtils.isEmpty(dataCubeTemplateConfigDOS)) {
            list = dataCubeTemplateConfigDOS.stream().map(index -> {
                DataCubeTemplateConfigResponse dataCubeTemplateConfigResponse = new DataCubeTemplateConfigResponse();
                BeanUtils.copyProperties(index, dataCubeTemplateConfigResponse);
                return dataCubeTemplateConfigResponse;
            }).collect(Collectors.toList());
        }
        return list;
    }


    /**
     * 查询模板list
     */
    public RpcPagination<DataCubeTemplateConfigResponse> findTemplatePageList(RpcPagination<DataCubeTemplateConfigSearchRequest> request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<DataCubeTemplateConfigResponse> templateList = templateConfigMapper.findTemplateList(request.getCondition());
        return RpcPagination.copyPage(templateList);
    }

    /**
     * 查询模板list
     */
    public DataCubeTemplateConfigResponse findTemplateDetail(Integer templateId) {
        Example example = new Example(DataCubeTemplateConfigDO.class);
        example.createCriteria().andEqualTo("id", templateId + "");
        List<DataCubeTemplateConfigDO> dataCubeTemplateConfigDOS = templateConfigMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(dataCubeTemplateConfigDOS)) {
            DataCubeTemplateConfigResponse dataCubeTemplateConfigResponse = new DataCubeTemplateConfigResponse();
            BeanUtils.copyProperties(dataCubeTemplateConfigDOS.get(0), dataCubeTemplateConfigResponse);
            return dataCubeTemplateConfigResponse;
        }
        return null;
    }

    /**
     * 新增模板
     */
    public void saveTemplate(DataCubeTemplateConfigRequest request) {
        DataCubeTemplateConfigDO dataCubeTemplateConfigDO = new DataCubeTemplateConfigDO();
        BeanUtils.copyProperties(request, dataCubeTemplateConfigDO);
        dataCubeTemplateConfigDO.setDelFlag(Constants.NORMAL_FLAG);
        dataCubeTemplateConfigDO.setCreatedTime(new Date());
        dataCubeTemplateConfigDO.setUpdatedTime(new Date());
        Integer id = templateConfigMapper.findMaxId();
        dataCubeTemplateConfigDO.setTemplateId(id + 1);
        templateConfigMapper.insertUseGeneratedKeys(dataCubeTemplateConfigDO);
    }

    /**
     * 更新模板
     */
    public void updateTemplate(DataCubeTemplateConfigRequest request) {
        DataCubeTemplateConfigDO dataCubeTemplateConfigDO = new DataCubeTemplateConfigDO();
        BeanUtils.copyProperties(request, dataCubeTemplateConfigDO);
        dataCubeTemplateConfigDO.setUpdatedTime(new Date());
        templateConfigMapper.updateByPrimaryKeySelective(dataCubeTemplateConfigDO);
    }

    /**
     * 查询模板list
     */
    public RpcPagination<TableConfigInfoResponse> findRelationPageList(RpcPagination<DataCubeTemplateConfigSearchRequest> request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<TableConfigInfoResponse> templateList = dataCubeTableFieldRelationMapper.findRelationPageList(request.getCondition());
        return RpcPagination.copyPage(templateList);
    }

    /**
     * 更新模板
     */
    public void updateRelation(TableConfigInfoResquest request) {
        DataCubeConfigFieldRelationDO dataCubeTemplateConfigDO = new DataCubeConfigFieldRelationDO();
        BeanUtils.copyProperties(request, dataCubeTemplateConfigDO);
        dataCubeTemplateConfigDO.setUpdatedTime(new Date());
        dataCubeTableFieldRelationMapper.updateByPrimaryKeySelective(dataCubeTemplateConfigDO);
    }

    /**
     * 更新模板
     */
    public void saveRelation(TableConfigInfoResquest request) {
        DataCubeConfigFieldRelationDO dataCubeTemplateConfigDO = new DataCubeConfigFieldRelationDO();
        BeanUtils.copyProperties(request, dataCubeTemplateConfigDO);
        dataCubeTemplateConfigDO.setCreatedTime(new Date());
        dataCubeTemplateConfigDO.setUpdatedTime(new Date());
        dataCubeTemplateConfigDO.setDelFlag(Constants.NORMAL_FLAG);
        dataCubeTableFieldRelationMapper.insertUseGeneratedKeys(dataCubeTemplateConfigDO);
    }

    /**
     * 查询模板list
     */
    public TableConfigInfoResponse findRelationDetail(Integer id) {
        Example example = new Example(DataCubeConfigFieldRelationDO.class);
        example.createCriteria().andEqualTo("id", id + "");
        List<DataCubeConfigFieldRelationDO> dataCubeTemplateConfigDOS = dataCubeTableFieldRelationMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(dataCubeTemplateConfigDOS)) {
            TableConfigInfoResponse dataCubeTemplateConfigResponse = new TableConfigInfoResponse();
            BeanUtils.copyProperties(dataCubeTemplateConfigDOS.get(0), dataCubeTemplateConfigResponse);
            return dataCubeTemplateConfigResponse;
        }
        return null;
    }
}