package com.zehong.web.controller.externaldocking.lpggas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.*;
import com.zehong.system.domain.vo.UserManageSafetyDeviceExportVo;
import com.zehong.system.domain.vo.YeHuaqiUserManageSafetyDeviceExportVo;
import com.zehong.system.mapper.TEnterpriseInfoMapper;
import com.zehong.system.service.*;
import com.zehong.web.controller.tool.DESEncoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 液化气-外部对接controller
 */
@RestController
@RequestMapping("/api/externaldocking")
public class lpgGasController {

    /**
     * 气瓶档案
     */
    @Resource
    private ITLpgGasBottleFilesService tLpgGasBottleFilesService;

    /**
     * 充装记录
     */
    @Resource
    private ITLpgAirChargeFilesService itLpgAirChargeFilesService;

    @Resource
    private ITLpgThirdPartyDockingInterfaceRecordService lpgThirdPartyDockingInterfaceRecordService;

    /**
     * 车辆信息
     */
    @Resource
    private ITLpgVehicleInfoService lpgVehicleInfoService;

    /**
     * 安检记录
     */
    @Resource
    private ITLpgSafeCheckRecordService lpgSafeCheckRecordService;

//    /**
//     * 燃气用户
//     */
//    @Resource
//    private ITYehuaqiUserService tYehuaqiUserService;

    /**
     * 燃气用户
     */
    @Resource
    private ITDetectorUserService itDetectorUserService;

    /**
     * 配送记录
     */
    @Resource
    private ITLpgDeliveryRecordService itLpgDeliveryRecordService;

    /**
     * 县级行政区
     */
    @Resource
    private ITCountyLevelRegionService countyLevelRegionService;

    /**
     * 居住区(村庄) service
     */
    @Resource
    private ITUserManageVillageService itUserManageVillageService;

    @Resource
    DecryptService decryptService;

    @Resource
    private TEnterpriseInfoMapper tEnterpriseInfoMapper;

    @Autowired
    private ITInspectionAccidentService tInspectionAccidentService;

    @Autowired
    private ITLinePatrolService tLinePatrolService;

    /**
     * 创建 气瓶档案接口
     * @return r
     */
    @PostMapping("/createLpgGasBottleFiles")
    public AjaxResult createLpgGasBottleFiles(@RequestBody Encryption encryption){

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if(selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder=new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if(tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js= JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js,JSONObject.class);

            if(list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLpgGasBottleFiles> lpgGasBottleFiles = new ArrayList<>();

            // 需要修改的
            List<TLpgGasBottleFiles> updateLpgGasBottleFiles = new ArrayList<>();

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (int i=0;i<list.size();i++){
                TLpgGasBottleFiles lpgGasBottleFiles1 = new TLpgGasBottleFiles();

                String dateFormat = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

                JSONObject jsonObject = list.get(i);

                // 气瓶条码
                String qrcode = jsonObject.getString("qrcode");
                if(StringUtils.isBlank(qrcode)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "气瓶条码不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(qrcode.length() > 64){
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "气瓶条码不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 生产日期
                String makeDate = jsonObject.getString("makeDate") == null ? "" : jsonObject.getString("makeDate");
                if(makeDate.length()>0 && !isValidDate(sdf,makeDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "生产日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 上检日期
                String pchkDate = jsonObject.getString("pchkDate") == null ? "" : jsonObject.getString("pchkDate");
                if(pchkDate.length() > 0 && !isValidDate(sdf,pchkDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "上检日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 下检日期
                String nchkDate = jsonObject.getString("nchkDate") == null ? "" : jsonObject.getString("nchkDate");
                if(nchkDate.length() > 0 && !isValidDate(sdf,nchkDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "下检日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 生产日期
                String productDate = jsonObject.getString("productDate") == null ? "" : jsonObject.getString("productDate");
                if(productDate.length() > 0 && !isValidDate(sdf,productDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "生产日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 报废日期
                String discardDate = jsonObject.getString("discardDate") == null ? "" : jsonObject.getString("discardDate");
                if(discardDate.length()>0 && !isValidDate(sdf,discardDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "报废日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 安全评价日期
                String safeJudgeDate = jsonObject.getString("safeJudgeDate") == null ? "" : jsonObject.getString("safeJudgeDate");
                if(safeJudgeDate.length() > 0 && !isValidDate(sdf,safeJudgeDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "安全评价日期不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 生产(制造单位)
                String makeInfo = jsonObject.getString("makeInfo") == null ? "" : jsonObject.getString("makeInfo");
                if(makeInfo.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "生产(制造单位)不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;

                }
                // 登记证号
                String regCode = jsonObject.getString("regCode") == null ? "" : jsonObject.getString("regCode");
                if (regCode.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "登记证号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;

                }
                // 产品编号
                String equNo = jsonObject.getString("equNo") == null ? "" : jsonObject.getString("equNo");
                if (equNo.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "产品编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 设备类型
                String equType = jsonObject.getString("equType") == null ? "" : jsonObject.getString("equType");
                if (equType.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "设备类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 充装介质
                String medium = jsonObject.getString("medium") == null ? "" : jsonObject.getString("medium");
                if (medium.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "充装介质不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 单位内编号
                String selfId = jsonObject.getString("selfId") == null ? "" : jsonObject.getString("selfId");
                if (selfId.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "单位内编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 压力
                String pressure = jsonObject.getString("pressure") == null ? "" : jsonObject.getString("pressure");
                BigDecimal pressureBigDecimal = BigDecimal.ZERO;
                if (pressure.length() > 0) {
                    try {
                        pressureBigDecimal = new BigDecimal(pressure);
                    } catch (NumberFormatException  e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "压力不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 体积
                String volume = jsonObject.getString("volume") == null ? "" : jsonObject.getString("volume");
                BigDecimal volumeBigDecimal = BigDecimal.ZERO;
                if (volume.length() > 0) {
                    try {
                        volumeBigDecimal = new BigDecimal(volume);
                    } catch (NumberFormatException  e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "体积不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 电子标签
                String appId = jsonObject.getString("appId") == null ? "" : jsonObject.getString("appId");
                if (appId.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "电子标签不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 使用单位
                String buildUser = jsonObject.getString("buildUser") == null ? "" : jsonObject.getString("buildUser");
                if (buildUser.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "使用单位不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 公称压力Mpa
                String gpressure = jsonObject.getString("gpressure") == null ? "" : jsonObject.getString("gpressure");
                BigDecimal gpressureBigDecimal = BigDecimal.ZERO;
                if (gpressure.length() > 0) {
                    try {
                        gpressureBigDecimal = new BigDecimal(gpressure);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "公称压力不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 水试验压力Mpa
                String wpressure = jsonObject.getString("wpressure") == null ? "" : jsonObject.getString("wpressure");
                BigDecimal wpressureBigDecimal = BigDecimal.ZERO;
                if (wpressure.length() > 0) {
                    try {
                        wpressureBigDecimal = new BigDecimal(wpressure);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "水试验压力不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 标准重量KG
                String selfWeight = jsonObject.getString("selfWeight") == null ? "" : jsonObject.getString("selfWeight");
                BigDecimal selfWeightBigDecimal = BigDecimal.ZERO;
                if (selfWeight.length() > 0) {
                    try {
                        selfWeightBigDecimal = new BigDecimal(selfWeight);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "标准重量不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }
                // 壁厚mm
                String thickness = jsonObject.getString("thickness") == null ? "" : jsonObject.getString("thickness");
                BigDecimal thicknessBigDecimal = BigDecimal.ZERO;
                if (thickness.length() > 0) {
                    try {
                        thicknessBigDecimal = new BigDecimal(thickness);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "壁厚不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 气瓶许可证号
                String permitNo = jsonObject.getString("permitNo") == null ? "" : jsonObject.getString("permitNo");
                if (permitNo.length() > 100) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "气瓶许可证号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 阀类型名称
                String valveName = jsonObject.getString("valveName") == null ? "" : jsonObject.getString("valveName");
                if (valveName.length() > 100) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "阀类型名称不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 钢瓶规格名称
                String botSpecName = jsonObject.getString("botSpecName") == null ? "" : jsonObject.getString("botSpecName");
                if (botSpecName.length() > 64) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "钢瓶规格名称不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  钢瓶型号
                String bottleType = jsonObject.getString("bottleType") == null ? "" : jsonObject.getString("bottleType");

                if(bottleType.length() > 64) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "钢瓶型号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  已检验次数
                String inspectedTimes = jsonObject.getString("inspectedTimes") == null ? "" : jsonObject.getString("inspectedTimes");
                long inspectedTimesl = 0L;
                if (inspectedTimes.length() > 0) {
                    try {
                        inspectedTimesl = Long.parseLong(inspectedTimes);
                    } catch (NumberFormatException e) {

                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                                "已检验次数不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                //  阀厂家
                String valveManuFacturer = jsonObject.getString("valveManuFacturer") == null ? "" : jsonObject.getString("valveManuFacturer");
                if (valveManuFacturer.length() > 100) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "阀厂家不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 检验标牌(有/无)
                String inspectionLabel = jsonObject.getString("inspectionLabel") == null ? "" : jsonObject.getString("inspectionLabel");

                if (inspectionLabel.length() > 100) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "检验标牌不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 第三方标签
                String thirdPartyLabel = jsonObject.getString("thirdPartyLabel") == null ? "" : jsonObject.getString("thirdPartyLabel");
                if (thirdPartyLabel.length() > 100) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "第三方标签不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                //  孔洞码
                String holeCode = jsonObject.getString("holeCode") == null ? "" : jsonObject.getString("holeCode");

                if (holeCode.length() > 100) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "孔洞码不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  存储类型(气相/液相)
                String bottleStorageType = jsonObject.getString("bottleStorageType") == null ? "" : jsonObject.getString("bottleStorageType");

                if(bottleStorageType.length() > 100) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgGasBottleFiles", jsonObject.toJSONString(),
                            "存储类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                //  钢瓶交付文件照片
                String payImage = jsonObject.getString("payImage") == null ? "" : jsonObject.getString("payImage");
                if(payImage.length() > 0 && isBase64Image(payImage)) {
                    lpgGasBottleFiles1.setPayImage(payImage);
                }

                //  检验质量证明书照片
                String batchImage = jsonObject.getString("batchImage") == null ? "" : jsonObject.getString("batchImage");

                if (batchImage.length() > 0 && isBase64Image(batchImage)) {
                    lpgGasBottleFiles1.setBatchImage(batchImage);
                }

                //  制造监督检验证书照片
                String deviceImage = jsonObject.getString("deviceImage") == null ? "" : jsonObject.getString("deviceImage");

                if (deviceImage.length() > 0 && isBase64Image(deviceImage)) {
                    lpgGasBottleFiles1.setDeviceImage(deviceImage);
                }

                //  检验报告照片
                String checkImage = jsonObject.getString("checkImage") == null ? "" : jsonObject.getString("checkImage");

                if (checkImage.length() > 0 && isBase64Image(checkImage)) {
                    lpgGasBottleFiles1.setCheckImage(checkImage);
                }

                //  钢瓶信息照片
                String botImage = jsonObject.getString("botImage") == null ? "" : jsonObject.getString("botImage");
                if (botImage.length() > 0 && isBase64Image(botImage)) {
                    lpgGasBottleFiles1.setBotImage(botImage);
                }

                lpgGasBottleFiles1.setQrcode(qrcode);
                try {
                    lpgGasBottleFiles1.setMakeDate(sdf.parse(makeDate));
                    lpgGasBottleFiles1.setPchkDate(sdf.parse(pchkDate));
                    lpgGasBottleFiles1.setNchkDate(sdf.parse(nchkDate));
                    lpgGasBottleFiles1.setProductDate(sdf.parse(productDate));
                    lpgGasBottleFiles1.setDiscardDate(sdf.parse(discardDate));
                    lpgGasBottleFiles1.setSafeJudgeDate(sdf.parse(safeJudgeDate));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                lpgGasBottleFiles1.setMakeInfo(makeInfo);
                lpgGasBottleFiles1.setRegCode(regCode);
                lpgGasBottleFiles1.setEquNo(equNo);
                lpgGasBottleFiles1.setEquType(equType);
                lpgGasBottleFiles1.setMedium(medium);
                lpgGasBottleFiles1.setSelfId(selfId);

                lpgGasBottleFiles1.setPressure(pressureBigDecimal);
                lpgGasBottleFiles1.setVolume(volumeBigDecimal);

                lpgGasBottleFiles1.setGpressure(gpressureBigDecimal);
                lpgGasBottleFiles1.setWpressure(wpressureBigDecimal);
                lpgGasBottleFiles1.setSelfWeight(selfWeightBigDecimal);
                lpgGasBottleFiles1.setThickness(thicknessBigDecimal);

                lpgGasBottleFiles1.setInspectedTimes(inspectedTimesl);

                lpgGasBottleFiles1.setAppId(appId);
                lpgGasBottleFiles1.setBuildUser(buildUser);
                lpgGasBottleFiles1.setPermitNo(permitNo);
                lpgGasBottleFiles1.setValveName(valveName);
                lpgGasBottleFiles1.setBotSpecName(botSpecName);
                lpgGasBottleFiles1.setBottleType(bottleType);
                lpgGasBottleFiles1.setValveManuFacturer(valveManuFacturer);
                lpgGasBottleFiles1.setInspectionLabel(inspectionLabel);
                lpgGasBottleFiles1.setThirdPartyLabel(thirdPartyLabel);
                lpgGasBottleFiles1.setHoleCode(holeCode);
                lpgGasBottleFiles1.setBottleStorageType(bottleStorageType);

                // 设置 企业id
                lpgGasBottleFiles1.setEnterpriseId(tEnterpriseInfo.getEnterpriseId());

                successNum++;
                lpgGasBottleFiles.add(lpgGasBottleFiles1);

                TLpgGasBottleFiles lpgGasBottleFilesDb = new TLpgGasBottleFiles();
                BeanUtils.copyProperties(lpgGasBottleFiles1,lpgGasBottleFilesDb);
                lpgGasBottleFilesDb.setPayImage("");
                lpgGasBottleFilesDb.setBatchImage("");
                lpgGasBottleFilesDb.setDeviceImage("");
                lpgGasBottleFilesDb.setCheckImage("");
                lpgGasBottleFilesDb.setBotImage("");
                lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgGasBottleFiles", lpgGasBottleFilesDb.toString(), encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
            }

            if (lpgGasBottleFiles.size() > 0) {

                // 第一步 先把正确数据里面的 重复 气瓶条码的数据 去去重

                Set<TLpgGasBottleFiles> set = new HashSet<>(lpgGasBottleFiles);

                int i1 = lpgGasBottleFiles.size() - set.size();
                if (i1 > 0) {
                    repeatNum = i1;
                    successNum = successNum - repeatNum;
                }

                List<TLpgGasBottleFiles> notRepeatList = new ArrayList<>(set);

                // 第二步 判断数据库里面的 气瓶条码 是否存在，存在的话就更新数据库数据
                List<String> collect = notRepeatList.stream().map(TLpgGasBottleFiles::getQrcode).collect(Collectors.toList());
                List<TLpgGasBottleFiles> lpgGasBottleFiles1 = tLpgGasBottleFilesService.queryAllByQrcodeAndEnterpriseList(collect, tEnterpriseInfo.getEnterpriseId());
                Map<String, List<TLpgGasBottleFiles>> collect1 = lpgGasBottleFiles1.stream().collect(Collectors.groupingBy(TLpgGasBottleFiles::getQrcode));

                Iterator<TLpgGasBottleFiles> iterator = notRepeatList.iterator();
                while (iterator.hasNext()) {
                    TLpgGasBottleFiles next = iterator.next();
                    List<TLpgGasBottleFiles> lpgGasBottleFiles2 = collect1.get(next.getQrcode());
                    if (lpgGasBottleFiles2 != null && lpgGasBottleFiles2.size() > 0) {
                        updateLpgGasBottleFiles.add(next);
                        iterator.remove();
                    }
                }

                // 不重复的该新增的新增
                if (notRepeatList.size() > 0){
                    tLpgGasBottleFilesService.externalDockingCreateLpgGasBottleFiles(notRepeatList);
                }

                // 不重复的该修改的修改
                if(updateLpgGasBottleFiles.size() > 0) {
                    tLpgGasBottleFilesService.externalDockingUpdateLpgGasBottleFiles(updateLpgGasBottleFiles);
                }

            }

            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }

        } else {
            return AjaxResult.error("数据异常");
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0 || repeatNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条;重复").append(repeatNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }

    /**
     * 判断是否是正确日期
     * @param dateString  d
     * @return r
     */
    public static boolean isValidDate(SimpleDateFormat sdf,String dateString) {
        sdf.setLenient(false); // 设置为不宽松模式，严格按照指定的格式解析
        try {
            sdf.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     * 判断给定的字符串是否是Base64编码的图片
     *
     * @param base64String 要检查的字符串
     * @return 如果是Base64编码的，则返回true；否则返回false。
     */
    public static boolean isBase64Image(String base64String) {
        try {
            // 解码Base64字符串为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64String);

            // 尝试从字节数组读取图片
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));

            // 如果成功读取到图片，则返回true
            return image != null;
        } catch (IllegalArgumentException | IOException e) {
            // 如果在解码或读取图片时发生异常，则认为不是有效的图片文件
            return false;
        }
    }


    /**
     * 创建 充装记录接口
     * @return r
     */
    @PostMapping("/createLpgAirChargeFiles")
    public AjaxResult createLpgAirChargeFiles(@RequestBody Encryption encryption){

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if(selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder=new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if(tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;


        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if(list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLpgAirChargeFiles> lpgAirChargeFiles = new ArrayList<>();
            TLpgAirChargeFiles tLpgAirChargeFiles;

            // 需要更新的集合
            List<TLpgAirChargeFiles> updateLpgAirChargeFiles = new ArrayList<>();

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (int i = 0; i < list.size(); i++) {
                tLpgAirChargeFiles = new TLpgAirChargeFiles();

                String dateFormat = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

                JSONObject jsonObject = list.get(i);

                // 气瓶条码
                String barCode = jsonObject.getString("barCode");
                if(StringUtils.isBlank(barCode)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "气瓶条码不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(barCode.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "气瓶条码数据不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  充装记录编号
                String gzId = jsonObject.getString("gzId");
                if (StringUtils.isBlank(gzId)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装记录编号不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  充装记录编号
                try {
                    long l = Long.parseLong(gzId);
                    tLpgAirChargeFiles.setGzId(l);
                }catch (NumberFormatException e) {
                    tLpgAirChargeFiles.setGzId(0L);
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装记录编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 充装开始时间
                String fillStatrTime = jsonObject.getString("fillStatrTime") == null ? "" : jsonObject.getString("fillStatrTime");
                if(fillStatrTime.length() > 0 && !isValidDate(sdf,fillStatrTime)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装开始时间不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 充装结束时间
                String fillEndTime = jsonObject.getString("fillEndTime") == null ? "" : jsonObject.getString("fillEndTime");
                if(fillEndTime.length() > 0 && !isValidDate(sdf,fillEndTime)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装结束时间不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                //   充装单位
                String stationName = jsonObject.getString("stationName") == null ? "" : jsonObject.getString("stationName");
                if (stationName.length() > 300) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装单位不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   钢印号
                String vaseCode = jsonObject.getString("vaseCode") == null ? "" : jsonObject.getString("vaseCode");
                if (vaseCode.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "钢印号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   秤号
                String scaleNum = jsonObject.getString("scaleNum") == null ? "" : jsonObject.getString("scaleNum");
                if (scaleNum.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "秤号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   充装工
                String oprateName = jsonObject.getString("oprateName") == null ? "" : jsonObject.getString("oprateName");
                if (oprateName.length() > 64) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                            "充装工不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 设定净重
                String setWeight = jsonObject.getString("setWeight") == null ? "" : jsonObject.getString("setWeight");
                if (setWeight.length() > 0) {
                    try {
                        new BigDecimal(setWeight);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                                "设定净重不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 实际净重
                String wtNet = jsonObject.getString("wtNet") == null ? "" : jsonObject.getString("wtNet");
                if (wtNet.length() > 0) {
                    try {
                        new BigDecimal(wtNet);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                                "实际净重不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 设定瓶重
                String setBottleWeight = jsonObject.getString("setBottleWeight") == null ? "" : jsonObject.getString("setBottleWeight");
                if (setBottleWeight.length() > 0) {
                    try {
                        new BigDecimal(setBottleWeight);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                                "设定瓶重不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 实际瓶重
                String bottleWeight = jsonObject.getString("bottleWeight") == null ? "" : jsonObject.getString("bottleWeight");
                if (bottleWeight.length() > 0) {
                    try {
                        new BigDecimal(bottleWeight);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                                "实际瓶重不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 实际总重
                String wtGross = jsonObject.getString("wtGross") == null ? "" : jsonObject.getString("wtGross");
                if (wtGross.length() > 0) {
                    try {
                        new BigDecimal(wtGross);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", jsonObject.toJSONString(),
                                "实际总重不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }


                tLpgAirChargeFiles.setBarCode(barCode);
                tLpgAirChargeFiles.setFillStatrTime(fillStatrTime);
                tLpgAirChargeFiles.setFillEndTime(fillEndTime);
                tLpgAirChargeFiles.setStationName(stationName);
                tLpgAirChargeFiles.setVaseCode(vaseCode);
                tLpgAirChargeFiles.setScaleNum(scaleNum);
                tLpgAirChargeFiles.setOprateName(oprateName);

                tLpgAirChargeFiles.setSetWeight(setWeight);
                tLpgAirChargeFiles.setWtNet(wtNet);
                tLpgAirChargeFiles.setSetBottleWeight(setBottleWeight);
                tLpgAirChargeFiles.setBottleWeight(bottleWeight);
                tLpgAirChargeFiles.setWtGross(wtGross);

                tLpgAirChargeFiles.setEnterpriseId(tEnterpriseInfo.getEnterpriseId());

                lpgAirChargeFiles.add(tLpgAirChargeFiles);
            }


            // 看看 气瓶条码是否 都符合规则
            List<TLpgAirChargeFiles> successLpgAirChargeFiles = new ArrayList<>();
            if (lpgAirChargeFiles.size() > 0) {
                List<String> collect = lpgAirChargeFiles.stream().map(TLpgAirChargeFiles::getBarCode).collect(Collectors.toList());
                List<TLpgGasBottleFiles> lpgGasBottleFiles = tLpgGasBottleFilesService.queryALlByQrcodeList(collect);
                Map<String, List<TLpgGasBottleFiles>> collect1 = lpgGasBottleFiles.stream().collect(Collectors.groupingBy(TLpgGasBottleFiles::getQrcode));
                for (TLpgAirChargeFiles lpgAirChargeFile : lpgAirChargeFiles) {
                    List<TLpgGasBottleFiles> lpgGasBottleFiles1 = collect1.get(lpgAirChargeFile.getBarCode());
                    if (lpgGasBottleFiles1 != null && lpgGasBottleFiles1.size() > 0) {
                        successNum++;
                        successLpgAirChargeFiles.add(lpgAirChargeFile);
                        lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgAirChargeFiles", lpgAirChargeFile.toString(), encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    } else {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgAirChargeFiles", lpgAirChargeFile.toString(),
                                "监管平台气瓶档案下无此气瓶条码信息！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum ++;
                    }
                }
            }

            if (successLpgAirChargeFiles.size() > 0) {
                // 把正确数据里面的 如果 气瓶条码 和 充装记录编号重复的去去重
                Set<TLpgAirChargeFiles> uniqueList = new HashSet<>(successLpgAirChargeFiles);

                int i1 = successLpgAirChargeFiles.size() - uniqueList.size();

                if(i1> 0) {
                    repeatNum = i1;
                    successNum = successNum - repeatNum;
                }

                List<TLpgAirChargeFiles> successNoRepeatLpgAirChargeFilesList = new ArrayList<>(uniqueList);
                // 气瓶条码都符合规则后 并且去重 后 ，再根据  企业id 气瓶条码 充装记录编码判断唯一，如果已存在，则修改。不存在 则新增
                List<TLpgAirChargeFiles> lpgAirChargeFiles1 = itLpgAirChargeFilesService.queryALlByBarcodeAndGizId(successNoRepeatLpgAirChargeFilesList);
                Map<String, List<TLpgAirChargeFiles>> collect = lpgAirChargeFiles1.stream().collect(Collectors.groupingBy(item -> item.getBarCode() + ":" + item.getGzId()));

                Iterator<TLpgAirChargeFiles> iterator = successNoRepeatLpgAirChargeFilesList.iterator();
                while (iterator.hasNext()) {
                    TLpgAirChargeFiles next = iterator.next();
                    String key = next.getBarCode() + ":" + next.getGzId();
                    List<TLpgAirChargeFiles> lpgAirChargeFiles2 = collect.get(key);
                    // 说明是要修改的
                    if (lpgAirChargeFiles2 != null && lpgAirChargeFiles2.size() > 0) {
                        updateLpgAirChargeFiles.add(next);
                        iterator.remove();
                    }
                }

                // 插入新增的
                if (successNoRepeatLpgAirChargeFilesList.size() > 0) {
                    itLpgAirChargeFilesService.externalDockingCreateLpgAirChargeFileInfo(successNoRepeatLpgAirChargeFilesList);
                }

                // 修改要修改的
                if (updateLpgAirChargeFiles.size() > 0) {
                    itLpgAirChargeFilesService.externalDockingUpdateLpgAirChargeFileInfo(updateLpgAirChargeFiles);
                }
            }

            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }

        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0 || repeatNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条;重复:").append(repeatNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 创建 车辆信息接口
     * @return r
     */
    @PostMapping("/createLpgVehicleInfo")
    public AjaxResult createLpgVehicleInfo(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if(selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if(list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLpgVehicleInfo> lpgVehicleInfos = new ArrayList<>();
            // 需要更新的数据
            List<TLpgVehicleInfo> updateLpgVehicleInfos = new ArrayList<>();
            TLpgVehicleInfo lpgVehicleInfo;

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (int i = 0; i < list.size(); i++) {
                lpgVehicleInfo = new TLpgVehicleInfo();

                JSONObject jsonObject = list.get(i);

                // 车牌号
                String carNum = jsonObject.getString("carNum");
                if(StringUtils.isBlank(carNum)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "车牌号不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                if (carNum.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "车牌号过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   储备站
                String stationName = jsonObject.getString("stationName") == null ? "" : jsonObject.getString("stationName");
                if (stationName.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "储备站过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   车辆编号
                String carNumber = jsonObject.getString("carNumber") == null ? "" : jsonObject.getString("carNumber");
                if (carNumber.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "车辆编号过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   代码
                String vehicleCode = jsonObject.getString("vehicleCode") == null ? "" : jsonObject.getString("vehicleCode");
                if (vehicleCode.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "代码过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                //   品牌型号
                String brandModel = jsonObject.getString("brandModel") == null ? "" : jsonObject.getString("brandModel");
                if (brandModel.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "品牌型号过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                //   车辆类型
                String vehicleType = jsonObject.getString("vehicleType") == null ? "" : jsonObject.getString("vehicleType");
                if (vehicleType.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            "车辆类型过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   车辆载重
                String vehicleLoad = jsonObject.getString("vehicleLoad") == null ? "" : jsonObject.getString("vehicleLoad");
                if (vehicleLoad.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 车辆载重过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   车辆大小
                String vehicleSize = jsonObject.getString("vehicleSize") == null ? "" : jsonObject.getString("vehicleSize");
                if (vehicleSize.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 车辆大小过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   车辆限乘
                String vehicleLimt = jsonObject.getString("vehicleLimt") == null ? "" : jsonObject.getString("vehicleLimt");
                if (vehicleLimt.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 车辆限乘过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   车辆检查信息
                String vehicleInspect = jsonObject.getString("vehicleInspect") == null ? "" : jsonObject.getString("vehicleInspect");
                if (vehicleInspect.length() > 200) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 车辆检查信息过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   责任人
                String personLiable = jsonObject.getString("personLiable") == null ? "" : jsonObject.getString("personLiable");
                if (personLiable.length() > 200) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 责任人过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   使用状态
                String onState = jsonObject.getString("onState") == null ? "" : jsonObject.getString("onState");
                if (onState.length() > 1) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 使用状态过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                //   使用状态
                if (!"0".equals(onState) && !"1".equals(onState)) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 使用状态不符合要求值！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   使用人
                String vehicleUser = jsonObject.getString("vehicleUser") == null ? "" : jsonObject.getString("vehicleUser");
                if (vehicleUser.length() > 200) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 使用人过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   联系电话
                String phone = jsonObject.getString("phone") == null ? "" : jsonObject.getString("phone");
                if (phone.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 联系电话过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //   备注
                String remarks = jsonObject.getString("remarks") == null ? "" : jsonObject.getString("remarks");
                if (remarks.length() > 255) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgVehicleInfo", jsonObject.toJSONString(),
                            " 备注过长！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                lpgVehicleInfo.setCarNum(carNum);
                lpgVehicleInfo.setStationName(stationName);
                lpgVehicleInfo.setCarNumber(carNumber);
                lpgVehicleInfo.setVehicleCode(vehicleCode);
                lpgVehicleInfo.setBrandModel(brandModel);
                lpgVehicleInfo.setVehicleType(vehicleType);
                lpgVehicleInfo.setVehicleLoad(vehicleLoad);
                lpgVehicleInfo.setVehicleSize(vehicleSize);
                lpgVehicleInfo.setVehicleLimt(vehicleLimt);
                lpgVehicleInfo.setVehicleInspect(vehicleInspect);
                lpgVehicleInfo.setPersonLiable(personLiable);
                lpgVehicleInfo.setOnState(onState);
                lpgVehicleInfo.setVehicleUser(vehicleUser);
                lpgVehicleInfo.setPhone(phone);
                lpgVehicleInfo.setRemarks(remarks);
                lpgVehicleInfo.setEnterpriseId(tEnterpriseInfo.getEnterpriseId());

                lpgVehicleInfos.add(lpgVehicleInfo);
                lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgVehicleInfo", jsonObject.toJSONString(), encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                successNum++;
            }

            if (lpgVehicleInfos.size() > 0) {

                // 先把数据自身重复的去去重
                Set<TLpgVehicleInfo> set = new HashSet<>(lpgVehicleInfos);
                int i = lpgVehicleInfos.size() - set.size();
                if (i > 0) {
                    repeatNum = i;
                    successNum = successNum - repeatNum;
                }

                // 去重后的数据
                List<TLpgVehicleInfo> neRepeatVehicleInfoList = new ArrayList<>(set);

                //目前拿到的数据还都再判断下 车牌号 是否重复 重复直接更新
                List<String> collect = neRepeatVehicleInfoList.stream().map(TLpgVehicleInfo::getCarNum).collect(Collectors.toList());
                List<TLpgVehicleInfo> tLpgVehicleInfos = lpgVehicleInfoService.queryByCarNumsAndEnterpriseId(collect, tEnterpriseInfo.getEnterpriseId());
                Map<String, List<TLpgVehicleInfo>> collect1 = tLpgVehicleInfos.stream().collect(Collectors.groupingBy(TLpgVehicleInfo::getCarNum));
                Iterator<TLpgVehicleInfo> iterator = neRepeatVehicleInfoList.iterator();
                while (iterator.hasNext()) {
                    TLpgVehicleInfo next = iterator.next();
                    List<TLpgVehicleInfo> tLpgVehicleInfos1 = collect1.get(next.getCarNum());
                    if (tLpgVehicleInfos1 != null && tLpgVehicleInfos1.size() > 0) {
                        updateLpgVehicleInfos.add(next);
                        iterator.remove();
                    }
                }

                // 新增的新增
                if (neRepeatVehicleInfoList.size() > 0) {
                    lpgVehicleInfoService.insertBatch(neRepeatVehicleInfoList);
                }
                // 修改的修改
                if (updateLpgVehicleInfos.size() > 0) {
                    lpgVehicleInfoService.updateBatch(updateLpgVehicleInfos);
                }
            }

            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0 || repeatNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条;重复").append(repeatNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 创建 安检记录接口
     * @return r
     */
    @PostMapping("/createLpgSafeCheckRecord")
    public AjaxResult createLpgSafeCheckRecord(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLpgSafeCheckRecord> lpgSafeCheckRecords = new ArrayList<>();
            // 液化气表里面有的userOwnId
            List<TLpgSafeCheckRecord> yehuaqiLpgSafeCheckRecords = new ArrayList<>();
            TLpgSafeCheckRecord lpgSafeCheckRecord;

            String dateFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (int i = 0; i < list.size(); i++) {
                lpgSafeCheckRecord = new TLpgSafeCheckRecord();

                JSONObject jsonObject = list.get(i);

                // 用户自有编号 可以为空
                String userOwnId = jsonObject.getString("userOwnId") == null ? "" : jsonObject.getString("userOwnId");

                if(userOwnId.length() > 50) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用户自有编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 储备站 可以为空
                String stationName = jsonObject.getString("stationName") == null ? "" : jsonObject.getString("stationName");

                if (stationName.length() > 64) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "储备站不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户名可以为空
                String gasUser = jsonObject.getString("gasUser") == null ? "" : jsonObject.getString("gasUser");

                if (gasUser.length() > 64) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用户名不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 联系电话 可以为空
                String telNum = jsonObject.getString("telNum") == null ? "" : jsonObject.getString("telNum");

                if (telNum.length() > 50) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "联系电话不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户地址 可以为空
                String gasUserAddress = jsonObject.getString("gasUserAddress") == null ? "" : jsonObject.getString("gasUserAddress");

                if (gasUserAddress.length() > 50) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用户地址 不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户类型 可以为空
                String gasUserType = jsonObject.getString("gasUserType") == null ? "" : jsonObject.getString("gasUserType");

                if (gasUserType.length() > 2) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用户类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户类型 可以为空
                if(gasUserType.length()> 0 && !"0".equals(gasUserType) && !"1".equals(gasUserType)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用户类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                // 安检时间 可以为空
                String safeCheckDate = jsonObject.getString("safeCheckDate") == null ? "" : jsonObject.getString("safeCheckDate");
                if (safeCheckDate.length() > 0 && !isValidDate(sdf,safeCheckDate)) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "安检时间不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 安检人 可以为空
                String safeCheckPerson = jsonObject.getString("safeCheckPerson") == null ? "" : jsonObject.getString("safeCheckPerson");
                if(safeCheckPerson.length() > 20) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "安检人不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 气瓶数量 可以为空
                String bottleNum = jsonObject.getString("bottleNum") == null ? "" : jsonObject.getString("bottleNum");
                int bottleNumInt = 0;
                if(bottleNum.length() > 0) {
                    try {
                        bottleNumInt = Integer.parseInt(bottleNum);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                                "气瓶数量不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }
                // 入户状态 可以为空
                String checkInStatus = jsonObject.getString("checkInStatus") == null ? "" : jsonObject.getString("checkInStatus");
                if(checkInStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "入户状态不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                if (checkInStatus.length() > 0 && !"0".equals(checkInStatus) && !"1".equals(checkInStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "入户状态不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 燃气灶具检查情况 可以为空
                String stoveCheckStatus = jsonObject.getString("stoveCheckStatus") == null ? "" : jsonObject.getString("stoveCheckStatus");
                if(stoveCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "燃气灶具检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (stoveCheckStatus.length() > 0 && !"0".equals(stoveCheckStatus) && !"1".equals(stoveCheckStatus) && !"2".equals(stoveCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "燃气灶具检查情况 不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 连接软管检查情况 可以为空
                String hoseCheckStatus = jsonObject.getString("hoseCheckStatus") == null ? "" : jsonObject.getString("hoseCheckStatus");
                if(hoseCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "连接软管检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (hoseCheckStatus.length() > 0 && !"0".equals(hoseCheckStatus) && !"1".equals(hoseCheckStatus)
                        && !"2".equals(hoseCheckStatus)&& !"3".equals(hoseCheckStatus)&& !"4".equals(hoseCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "连接软管检查情况 不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                // 减压阀检查情况: 可以为空
                String valveCheckStatus = jsonObject.getString("valveCheckStatus") == null ? "" : jsonObject.getString("valveCheckStatus");
                if(valveCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "减压阀检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (valveCheckStatus.length() > 0 && !"0".equals(valveCheckStatus) && !"1".equals(valveCheckStatus) && !"2".equals(valveCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "减压阀检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  液化气钢瓶检查情况 可以为空
                String bottleCheckStatus = jsonObject.getString("bottleCheckStatus") == null ? "" : jsonObject.getString("bottleCheckStatus");
                if(bottleCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "液化气钢瓶检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                if (bottleCheckStatus.length() > 0 && !"0".equals(bottleCheckStatus) && !"1".equals(bottleCheckStatus)
                        && !"2".equals(bottleCheckStatus)&& !"3".equals(bottleCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "液化气钢瓶检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  报警器加电磁切断阀检查情况 可以为空
                String alarmCheckStatus = jsonObject.getString("alarmCheckStatus") == null ? "" : jsonObject.getString("alarmCheckStatus");
                if(alarmCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "报警器加电磁切断阀检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (alarmCheckStatus.length() > 0 && !"0".equals(alarmCheckStatus) && !"1".equals(alarmCheckStatus)
                        && !"2".equals(alarmCheckStatus)&& !"3".equals(alarmCheckStatus)&& !"4".equals(alarmCheckStatus)
                        && !"5".equals(alarmCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "报警器加电磁切断阀检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //  用气场所检查情况 可以为空
                String placeCheckStatus = jsonObject.getString("placeCheckStatus") == null ? "" : jsonObject.getString("placeCheckStatus");
                if(placeCheckStatus.length() > 2) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用气场所检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                if (placeCheckStatus.length() > 0 && !"0".equals(placeCheckStatus) && !"1".equals(placeCheckStatus)
                        && !"2".equals(placeCheckStatus)&& !"3".equals(placeCheckStatus)&& !"4".equals(placeCheckStatus)
                        && !"5".equals(placeCheckStatus)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", jsonObject.toJSONString(),
                            "用气场所检查情况不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                lpgSafeCheckRecord.setUserOwnId(userOwnId);
                lpgSafeCheckRecord.setStationName(stationName);
                lpgSafeCheckRecord.setGasUser(gasUser);
                lpgSafeCheckRecord.setTelNum(telNum);
                lpgSafeCheckRecord.setGasUserAddress(gasUserAddress);
                lpgSafeCheckRecord.setGasUserType(gasUserType);
                lpgSafeCheckRecord.setSafeCheckDate(DateUtils.parseDate(safeCheckDate));
                lpgSafeCheckRecord.setSafeCheckPerson(safeCheckPerson);
                lpgSafeCheckRecord.setBottleNum(bottleNumInt);
                lpgSafeCheckRecord.setCheckInStatus(checkInStatus);
                lpgSafeCheckRecord.setStoveCheckStatus(stoveCheckStatus);
                lpgSafeCheckRecord.setHoseCheckStatus(hoseCheckStatus);
                lpgSafeCheckRecord.setValveCheckStatus(valveCheckStatus);
                lpgSafeCheckRecord.setBottleCheckStatus(bottleCheckStatus);
                lpgSafeCheckRecord.setAlarmCheckStatus(alarmCheckStatus);
                lpgSafeCheckRecord.setPlaceCheckStatus(placeCheckStatus);

                // 六张照片
                // 燃气灶具检查情况照片 可以为空
                String stoveCheckPic = jsonObject.getString("stoveCheckPic") == null ? "" : jsonObject.getString("stoveCheckPic");
                if(stoveCheckPic.length() > 0 && !isBase64Image(stoveCheckPic)) {
                    lpgSafeCheckRecord.setStoveCheckPic(stoveCheckPic);
                }
                // 连接软管检查情况照片 可以为空
                String hoseCheckPic = jsonObject.getString("hoseCheckPic") == null ? "" : jsonObject.getString("hoseCheckPic");
                if(hoseCheckPic.length() > 0 && !isBase64Image(hoseCheckPic)) {
                    lpgSafeCheckRecord.setHoseCheckPic(hoseCheckPic);
                }
                // 减压阀检查情况 可以为空
                String valveCheckPic = jsonObject.getString("valveCheckPic") == null ? "" : jsonObject.getString("valveCheckPic");
                if(valveCheckPic.length() > 0 && !isBase64Image(valveCheckPic)) {
                    lpgSafeCheckRecord.setValveCheckPic(valveCheckPic);
                }
                // 液化气钢瓶检查情况 可以为空
                String bottleCheckPic = jsonObject.getString("bottleCheckPic") == null ? "" : jsonObject.getString("bottleCheckPic");
                if(bottleCheckPic.length() > 0 && !isBase64Image(bottleCheckPic)) {
                    lpgSafeCheckRecord.setBottleCheckPic(bottleCheckPic);
                }
                // 报警器加电磁切断阀检查情况照片 可以为空
                String alarmCheckPic = jsonObject.getString("alarmCheckPic") == null ? "" : jsonObject.getString("alarmCheckPic");
                if(alarmCheckPic.length() > 0 && !isBase64Image(alarmCheckPic)) {
                    lpgSafeCheckRecord.setAlarmCheckPic(alarmCheckPic);
                }
                // 用气场所检查情况照片 可以为空
                String placeCheckPic = jsonObject.getString("placeCheckPic") == null ? "" : jsonObject.getString("placeCheckPic");
                if(placeCheckPic.length() > 0 && !isBase64Image(placeCheckPic)) {
                    lpgSafeCheckRecord.setPlaceCheckPic(placeCheckPic);
                }

                lpgSafeCheckRecords.add(lpgSafeCheckRecord);
            }

            if (lpgSafeCheckRecords.size() > 0) {
                // 集合里面如果有 userOwnId 则 去燃气用户表里面查下 看看有没有该用户

                List<TLpgSafeCheckRecord> collect = lpgSafeCheckRecords.stream().filter(item -> StringUtils.isNotBlank(item.getUserOwnId())).collect(Collectors.toList());

                // userOwnId 不为空的数据
                if (collect.size() > 0) {

                    // 处理没有 userownid的数据，直接插入
                    List<TLpgSafeCheckRecord> collect2 = lpgSafeCheckRecords.stream().filter(item -> StringUtils.isBlank(item.getUserOwnId())).collect(Collectors.toList());
                    if (collect2.size() > 0) {
                        successNum += collect2.size();
                        lpgSafeCheckRecordService.insertBatchContainPic(collect2);
                        for (TLpgSafeCheckRecord safeCheckRecord : collect2) {
                            safeCheckRecord.setPlaceCheckPic("");
                            safeCheckRecord.setValveCheckPic("");
                            safeCheckRecord.setBottleCheckPic("");
                            safeCheckRecord.setAlarmCheckPic("");
                            safeCheckRecord.setHoseCheckPic("");
                            safeCheckRecord.setStoveCheckPic("");
                            lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgSafeCheckRecord", safeCheckRecord.toString(), encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        }
                    }

                    // 处理有 userOwnId的 看看 燃气用户表下有没有数据
                    List<String> collect1 = collect.stream().map(TLpgSafeCheckRecord::getUserOwnId).collect(Collectors.toList());
                    List<TDetectorUser> yehuaqiUsers = itDetectorUserService.queryByUserOwnIdsAndEnterpriseId(collect1, tEnterpriseInfo.getEnterpriseId());
                    if (yehuaqiUsers.size() > 0) {

                        Map<String, List<TDetectorUser>> collect3 = yehuaqiUsers.stream().collect(Collectors.groupingBy(TDetectorUser::getUserOwnId));
                        for (TLpgSafeCheckRecord tLpgSafeCheckRecord : collect) {
                            List<TDetectorUser> yehuaqiUsers1 = collect3.get(tLpgSafeCheckRecord.getUserOwnId());
                            if (yehuaqiUsers1.size() > 0) {
                                successNum ++;
                                tLpgSafeCheckRecord.setPlaceCheckPic("");
                                tLpgSafeCheckRecord.setValveCheckPic("");
                                tLpgSafeCheckRecord.setBottleCheckPic("");
                                tLpgSafeCheckRecord.setAlarmCheckPic("");
                                tLpgSafeCheckRecord.setHoseCheckPic("");
                                tLpgSafeCheckRecord.setStoveCheckPic("");
                                tLpgSafeCheckRecord.setUserId(yehuaqiUsers1.get(0).getUserId());
                                lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgSafeCheckRecord", tLpgSafeCheckRecord.toString(), encryption.getQybm());
                                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                                yehuaqiLpgSafeCheckRecords.add(tLpgSafeCheckRecord);
                            } else {
                                errorNum++;
                                tLpgSafeCheckRecord.setPlaceCheckPic("");
                                tLpgSafeCheckRecord.setValveCheckPic("");
                                tLpgSafeCheckRecord.setBottleCheckPic("");
                                tLpgSafeCheckRecord.setAlarmCheckPic("");
                                tLpgSafeCheckRecord.setHoseCheckPic("");
                                tLpgSafeCheckRecord.setStoveCheckPic("");
                                String sb = "燃气用户userOwnId为:" + tLpgSafeCheckRecord.getUserOwnId() + "的用户在监管平台不存在";
                                lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", tLpgSafeCheckRecord.toString(),
                                        sb, encryption.getQybm());
                                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            }
                        }

                    } else {
                        errorNum += collect.size();

                        for (TLpgSafeCheckRecord safeCheckRecord : collect) {
                            safeCheckRecord.setPlaceCheckPic("");
                            safeCheckRecord.setValveCheckPic("");
                            safeCheckRecord.setBottleCheckPic("");
                            safeCheckRecord.setAlarmCheckPic("");
                            safeCheckRecord.setHoseCheckPic("");
                            safeCheckRecord.setStoveCheckPic("");

                            String sb = "燃气用户userOwnId为:" + safeCheckRecord.getUserOwnId() + "的用户在监管平台不存在";

                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgSafeCheckRecord", safeCheckRecord.toString(),
                                    sb, encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        }
                    }
                // userOwnId 都为空的数据
                } else {
                    lpgSafeCheckRecordService.insertBatchContainPic(lpgSafeCheckRecords);
                    for (TLpgSafeCheckRecord safeCheckRecord : lpgSafeCheckRecords) {
                        safeCheckRecord.setPlaceCheckPic("");
                        safeCheckRecord.setValveCheckPic("");
                        safeCheckRecord.setBottleCheckPic("");
                        safeCheckRecord.setAlarmCheckPic("");
                        safeCheckRecord.setHoseCheckPic("");
                        safeCheckRecord.setStoveCheckPic("");
                        lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgSafeCheckRecord", safeCheckRecord.toString(), encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    }

                    successNum += lpgSafeCheckRecords.size();
                }
            }

            if(yehuaqiLpgSafeCheckRecords.size() > 0) {
                lpgSafeCheckRecordService.insertBatchContainPic(yehuaqiLpgSafeCheckRecords);
            }

            // 接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }


        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 创建 配送记录接口
     * @return r
     */
    @PostMapping("/createLpgDeliveryRecord")
    public AjaxResult createLpgDeliveryRecord(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLpgDeliveryRecord> lpgDeliveryRecords = new ArrayList<>();
            // 液化气表里面有的userOwnId
            List<TLpgDeliveryRecord> yehuaqiLpgDeliveryRecords = new ArrayList<>();

            // 液化气表里面有的userOwnId
            List<TLpgDeliveryRecord> userOwnIdNotBlackLpgDeliveryRecords = new ArrayList<>();
            TLpgDeliveryRecord lpgDeliveryRecord;

            String dateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (JSONObject object : list) {
                lpgDeliveryRecord = new TLpgDeliveryRecord();

                // 气瓶条码不许为空
                String bottleCode = object.getString("bottleCode");
                if (StringUtils.isBlank(bottleCode)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "气瓶条码不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (bottleCode.length() > 255) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "气瓶条码不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户自有编号 可以为空 为空时 就不关联 燃气用户了
                String userOwnId = object.getString("userOwnId") == null ? "" : object.getString("userOwnId");

                if (userOwnId.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "用户自有编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 储备站 可以为空
                String stationName = object.getString("stationName") == null ? "" : object.getString("stationName");

                if (stationName.length() > 64) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "储备站不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 配送人员 可以为空
                String deliveryPerson = object.getString("deliveryPerson") == null ? "" : object.getString("deliveryPerson");

                if (deliveryPerson.length() > 20) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "储备站不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 车辆代码 可以为空
                String vehicleCode = object.getString("vehicleCode") == null ? "" : object.getString("vehicleCode");

                if (vehicleCode.length() > 50) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "车辆代码不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户类型 可以为空
                String gasUserType = object.getString("gasUserType") == null ? "" : object.getString("gasUserType");

                if (gasUserType.length() > 2) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "用户类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if (gasUserType.length() > 0 && !"0".equals(gasUserType) && !"1".equals(gasUserType)) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "用户类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 配送地址 可以为空
                String deliveryAddress = object.getString("deliveryAddress") == null ? "" : object.getString("deliveryAddress");

                if (deliveryAddress.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "配送地址不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 配送时间 可以为空
                String deliveryDate = object.getString("deliveryDate") == null ? "" : object.getString("deliveryDate");

                if (deliveryDate.length() > 0 && !isValidDate(sdf, deliveryDate)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "配送时间不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                lpgDeliveryRecord.setBottleCode(bottleCode);
                lpgDeliveryRecord.setUserOwnId(userOwnId);
                lpgDeliveryRecord.setStationName(stationName);
                lpgDeliveryRecord.setDeliveryPerson(deliveryPerson);
                lpgDeliveryRecord.setVehicleCode(vehicleCode);
                lpgDeliveryRecord.setGasUserType(gasUserType);
                lpgDeliveryRecord.setDeliveryAddress(deliveryAddress);
                lpgDeliveryRecord.setDeliveryDate(DateUtils.parseDate(deliveryDate));

                lpgDeliveryRecords.add(lpgDeliveryRecord);
            }

            if (lpgDeliveryRecords.size() > 0) {
                // 1 先过滤下 气瓶条码 符不符合 监管平台
                List<String> collect = lpgDeliveryRecords.stream().map(TLpgDeliveryRecord::getBottleCode).collect(Collectors.toList());
                List<TLpgGasBottleFiles> lpgGasBottleFiles = tLpgGasBottleFilesService.queryAllByQrcodeAndEnterpriseList(collect, tEnterpriseInfo.getEnterpriseId());
                Map<String, List<TLpgGasBottleFiles>> collect1 = lpgGasBottleFiles.stream().collect(Collectors.groupingBy(TLpgGasBottleFiles::getQrcode));
                for (TLpgDeliveryRecord deliveryRecord : lpgDeliveryRecords) {
                    List<TLpgGasBottleFiles> lpgGasBottleFiles1 = collect1.get(deliveryRecord.getBottleCode());
                    if (lpgGasBottleFiles1 != null && lpgGasBottleFiles1.size() > 0) {
                        yehuaqiLpgDeliveryRecords.add(deliveryRecord);
                    } else {
                        String sb = "气瓶条码为:" + deliveryRecord.getBottleCode() + "的信息在监管平台不存在";
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", deliveryRecord.toString(),
                                sb, encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                    }
                }

                // 2 过滤完 气瓶条码后 判断 userOwnId 如果不为空，看看 监管平台有没有。
                if(yehuaqiLpgDeliveryRecords.size() > 0) {
                    List<TLpgDeliveryRecord> userOwnIdNotBlankList = yehuaqiLpgDeliveryRecords.stream().filter(item -> StringUtils.isNotBlank(item.getUserOwnId())).collect(Collectors.toList());
                    List<TLpgDeliveryRecord> userOwnIdBlankList = yehuaqiLpgDeliveryRecords.stream().filter(item -> StringUtils.isBlank(item.getUserOwnId())).collect(Collectors.toList());

                    // userOwnId 不为空的
                    if (userOwnIdNotBlankList.size() > 0) {

                        List<String> collect3 = userOwnIdNotBlankList.stream().map(TLpgDeliveryRecord::getUserOwnId).collect(Collectors.toList());
                        // 2024-10-26 调整 基础信息下的天然气用户 和 液化石油气监管下的 石油气用户都用 t_detector_user 这张表
                        List<TDetectorUser> yehuaqiUsers = itDetectorUserService.queryByUserOwnIdsAndEnterpriseId(collect3, tEnterpriseInfo.getEnterpriseId());
                        if (yehuaqiUsers.size() > 0) {
                            Map<String, List<TDetectorUser>> collect2 = yehuaqiUsers.stream().collect(Collectors.groupingBy(TDetectorUser::getUserOwnId));
                            for (TLpgDeliveryRecord tLpgDeliveryRecord : userOwnIdNotBlankList) {
                                List<TDetectorUser> yehuaqiUsers1 = collect2.get(tLpgDeliveryRecord.getUserOwnId());
                                if (yehuaqiUsers1 != null && yehuaqiUsers1.size() > 0) {
                                    userOwnIdNotBlackLpgDeliveryRecords.add(tLpgDeliveryRecord);
                                    lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgDeliveryRecord", tLpgDeliveryRecord.toString(), encryption.getQybm());
                                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                                    successNum++;
                                }else {
                                    String sb = "userOwnId为:" + tLpgDeliveryRecord.getUserOwnId() + "的信息在监管平台不存在";
                                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", tLpgDeliveryRecord.toString(),
                                            sb, encryption.getQybm());
                                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                                    errorNum++;
                                }
                            }

                            // 说明 监管平台没有这些 userOwnIds 则 都是错误数据
                        } else {
                            for (TLpgDeliveryRecord tLpgDeliveryRecord : userOwnIdNotBlankList) {

                                String sb = "userOwnId为:" + tLpgDeliveryRecord.getUserOwnId() + "的信息在监管平台不存在";
                                lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", tLpgDeliveryRecord.toString(),
                                        sb, encryption.getQybm());
                                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                                errorNum++;
                            }
                        }
                    }

                    // userOwnId 都为空，都为空的话，直接插入，就不关联 燃气用户数据了。
                    if (userOwnIdBlankList.size() > 0){
                        itLpgDeliveryRecordService.insertBatch(userOwnIdBlankList);
                        for (TLpgDeliveryRecord yehuaqiLpgDeliveryRecord : userOwnIdBlankList) {
                            lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgDeliveryRecord", yehuaqiLpgDeliveryRecord.toString(), encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            successNum++;
                        }
                    }
                }
            }

            // 这些是 判断了 气瓶 并且  也 判断了 userownid的正确数据
            if (userOwnIdNotBlackLpgDeliveryRecords.size() > 0) {
                itLpgDeliveryRecordService.insertBatch(userOwnIdNotBlackLpgDeliveryRecords);
            }

            // 接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 创建 液化气用户接口
     * @return r
     */
    @PostMapping("/createLpgLiquefiedGasUser")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createLpgLiquefiedGasUser(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 200) {
                return AjaxResult.error("每次最多处理200条数据");
            }

            // 2024-10-26 基础信息里面的 天然气用户 和 液压石油气监管下的 液化气用户 都使用 t_detector_user 这张表的数据

            List<TDetectorUser> yehuaqiUsers = new ArrayList<>();

            // 筛出去 userOwnId 重复的
            List<TDetectorUser> noRepeatUserOwnIdList;

            // 需要更新的数据
            List<TDetectorUser> updateYehuaqiUsers = new ArrayList<>();

            // 安全装置 集合数据
            List<TGasuserSafetyDeviceInfo> yehuaqiuserSafetyDeviceInfos = new ArrayList<>();

            // 需要修改的燃气用户的 安全装置 集合数据
            List<TGasuserSafetyDeviceInfo> updateYehuaqiuserSafetyDeviceInfos = new ArrayList<>();

            TDetectorUser yehuaqiUser;

            String dateFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (JSONObject object : list) {
                yehuaqiUser = new TDetectorUser();

                String userOwnId = object.getString("userOwnId");

                if (StringUtils.isBlank(userOwnId)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户自有编号不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(userOwnId.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户自有编号不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                // 用户名称
                String nickName = object.getString("nickName");
                if(StringUtils.isBlank(nickName)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户名称不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(nickName.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户名称不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 用户类型
                String userType = object.getString("userType");
                if(StringUtils.isBlank(userType)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户类型不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(!"1".equals(userType) && !"2".equals(userType) && !"4".equals(userType)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户类型不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 居住区村庄id
                String villageId = object.getString("villageId");
                long villageIdl = 0L;
                if ("1".equals(userType)) {
                    if (StringUtils.isBlank(villageId)) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                "用户类型为居民用户时，居住区村庄不许为空！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                if (StringUtils.isNotBlank(villageId)) {

                    try {
                        villageIdl = Long.parseLong(villageId);
                    }catch (NumberFormatException e) {

                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                "居住区村庄id 不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 用户地址
                String address = object.getString("address");
                if(StringUtils.isBlank(address)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户地址不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(address.length() > 255) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "用户地址不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 经度
                String longitude = object.getString("longitude");
                BigDecimal bigDecimalLongitude = BigDecimal.ZERO;
                if(StringUtils.isNotBlank(longitude)) {
                    try {
                        bigDecimalLongitude = new BigDecimal(longitude);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                "经度 不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 纬度
                String latitude = object.getString("latitude");
                BigDecimal bigDecimalLatitude = BigDecimal.ZERO;
                if(StringUtils.isNotBlank(longitude)) {
                    try {
                        bigDecimalLatitude = new BigDecimal(latitude);
                    }catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                "纬度 不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }
                // 联系人
                String linkman = object.getString("linkman") == null ? "" : object.getString("linkman");
                if(linkman.length() > 100) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "联系人不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 电话
                String phone = object.getString("phone") == null ? "" : object.getString("phone");
                if(phone.length() > 20) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "电话不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 备注
                String remarks = object.getString("remarks") == null ? "" : object.getString("remarks");
                if(remarks.length() > 4000) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                            "备注不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                yehuaqiUser.setUserOwnId(userOwnId);
                yehuaqiUser.setNickName(nickName);
                yehuaqiUser.setUserType(userType);
                if (villageIdl > 0) {
                    yehuaqiUser.setVillageId(villageIdl);
                }
                yehuaqiUser.setAddress(address);
                if(!BigDecimal.ZERO.equals(bigDecimalLongitude)) {
                    yehuaqiUser.setLongitude(bigDecimalLongitude);
                }
                if (!BigDecimal.ZERO.equals(bigDecimalLatitude)) {
                    yehuaqiUser.setLatitude(bigDecimalLatitude);
                }

                yehuaqiUser.setLinkman(linkman);
                yehuaqiUser.setPhone(phone);
                yehuaqiUser.setRemarks(remarks);
                yehuaqiUser.setBeyondEnterpriseId(tEnterpriseInfo.getEnterpriseId());
                // 2024-10-26 液化气和天然气都是用 t_detector_user 这张表，所以接口来的默认传1
                yehuaqiUser.setGasType("1");

                List<UserManageSafetyDeviceExportVo> tYehuaqiuserSafetyDeviceInfoList = new ArrayList<>();
                JSONArray safetyDeviceList = object.getJSONArray("safetyDeviceList");
                UserManageSafetyDeviceExportVo yehuaqiuserSafetyDeviceInfo;

                // 安装装置有错误时只做记录，不做任何错误提示返回。也不入库。
                if (safetyDeviceList != null) {

                    String safetyDeviceListSr = JSONObject.toJSONString(safetyDeviceList, SerializerFeature.WriteClassName);

                    List<JSONObject> safetyDeviceJsonList = JSONObject.parseArray(safetyDeviceListSr, JSONObject.class);

                    for (JSONObject jsonObject : safetyDeviceJsonList) {

                        // 设备名称
                        String fDeviceName = jsonObject.getString("fDeviceName") == null ?
                                "" : jsonObject.getString("fDeviceName");
                        if(fDeviceName.length() > 50) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "设备名称不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 设备型号
                        String fDeviceModel = jsonObject.getString("fDeviceModel") == null ?
                                "" : jsonObject.getString("fDeviceModel");
                        if(fDeviceModel.length() > 100) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "设备型号不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }


                        // 物联网编号
                        String fIotNo = jsonObject.getString("fIotNo") == null ?
                                "" : jsonObject.getString("fIotNo");
                        if(fIotNo.length() > 100) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "物联网编号不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 设备类型
                        String fRelationDeviceType = jsonObject.getString("fRelationDeviceType") == null ?
                                "" : jsonObject.getString("fRelationDeviceType");
                        if(fRelationDeviceType.length() > 50) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "设备类型不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 探测介质
                        String fDetectionMedium = jsonObject.getString("fDetectionMedium") == null ?
                                "" : jsonObject.getString("fDetectionMedium");
                        if(fDetectionMedium.length() > 255) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "探测介质不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }


                        // 设备安装时间
                        String fDeviceInstallTime = jsonObject.getString("fDeviceInstallTime") == null ?
                                "" : jsonObject.getString("fDeviceInstallTime");
                        if(fDeviceInstallTime.length() > 0 && !isValidDate(sdf,fDeviceInstallTime)) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "设备安装时间不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 设备安装位置
                        String fDeviceInstallPosition = jsonObject.getString("fDeviceInstallPosition") == null ?
                                "" : jsonObject.getString("fDeviceInstallPosition");
                        if(fDeviceInstallPosition.length() > 100) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "设备安装位置不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 负责人
                        String fHead = jsonObject.getString("fHead") == null ?
                                "" : jsonObject.getString("fHead");
                        if(fHead.length() > 20) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "负责人不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        // 联系电话
                        String fPhone = jsonObject.getString("fPhone") == null ?
                                "" : jsonObject.getString("fPhone");
                        if(fPhone.length() > 20) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", object.toJSONString(),
                                    "电话不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            break;
                        }

                        if (fDeviceName.length() > 0 || fDeviceModel.length() > 0 || fIotNo.length() > 0
                        || fRelationDeviceType.length() > 0 || fDetectionMedium.length() > 0
                        || fDeviceInstallTime.length() > 0 || fDeviceInstallPosition.length() > 0
                        || fHead.length() > 0 || fPhone.length() > 0) {

                            yehuaqiuserSafetyDeviceInfo = new UserManageSafetyDeviceExportVo();
                            yehuaqiuserSafetyDeviceInfo.setDeviceName(fDeviceName);
                            yehuaqiuserSafetyDeviceInfo.setDeviceModel(fDeviceModel);
                            yehuaqiuserSafetyDeviceInfo.setfIotNo(fIotNo);
                            yehuaqiuserSafetyDeviceInfo.setRelationDeviceType(fRelationDeviceType);
                            yehuaqiuserSafetyDeviceInfo.setDetectionMedium(fDetectionMedium);
                            yehuaqiuserSafetyDeviceInfo.setDeviceInstallTime(DateUtils.parseDate(fDeviceInstallTime));
                            yehuaqiuserSafetyDeviceInfo.setDeviceInstallPosition(fDeviceInstallPosition);
                            yehuaqiuserSafetyDeviceInfo.setHead(fHead);
                            yehuaqiuserSafetyDeviceInfo.setPhone(fPhone);
                            tYehuaqiuserSafetyDeviceInfoList.add(yehuaqiuserSafetyDeviceInfo);
                        }
                    }
                }

                if(tYehuaqiuserSafetyDeviceInfoList.size() > 0) {
                    yehuaqiUser.setUserManageSafetyDeviceExportVos(tYehuaqiuserSafetyDeviceInfoList);
                }

                yehuaqiUsers.add(yehuaqiUser);
            }

            //1 封装完数据后 先去重，userOwnId 相同的筛一筛
            if (yehuaqiUsers.size() > 0) {
                Set<TDetectorUser> yehuaqiUsers1 = new HashSet<>(yehuaqiUsers);

                int i = yehuaqiUsers.size() - yehuaqiUsers1.size();
                if (i > 0) {
                    repeatNum = i;
                }

                // 筛除重复后
                noRepeatUserOwnIdList = new ArrayList<>(yehuaqiUsers1);

                //2 筛除重复后，再筛下 有村的是否在监管平台存在
                if(noRepeatUserOwnIdList.size() > 0) {
                    List<Long> collect = noRepeatUserOwnIdList.stream().filter(item -> item.getVillageId() != null).map(TDetectorUser::getVillageId).collect(Collectors.toList());
                    List<TUserManageVillage> userManageVillages = itUserManageVillageService.queryByVillageIds(collect);
                    Map<Long, List<TUserManageVillage>> collect1 = userManageVillages.stream().collect(Collectors.groupingBy(TUserManageVillage::getfVillageId));

                    Iterator<TDetectorUser> iterator = noRepeatUserOwnIdList.iterator();
                    while (iterator.hasNext()) {
                        TDetectorUser next = iterator.next();
                        Long villageId = next.getVillageId();
                        if (villageId != null) {
                            List<TUserManageVillage> userManageVillages1 = collect1.get(villageId);
                            if (userManageVillages1 == null || userManageVillages1.size() == 0) {

                                lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgLiquefiedGasUser", next.toString(),
                                        "居住区村庄id在监管平台无信息！！！", encryption.getQybm());
                                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                                errorNum ++;
                                iterator.remove();
                            }
                        }
                    }
                }

                //3 根据 userOwnId 和 enterpriseId 查询 数据库是否存在数据 存在则更新
                if (noRepeatUserOwnIdList.size() > 0) {
                    List<String> collect = noRepeatUserOwnIdList.stream().map(TDetectorUser::getUserOwnId).collect(Collectors.toList());

                    List<TDetectorUser> yehuaqiUsers2 = itDetectorUserService.queryByUserOwnIdAndEnterpriseIdForThirdParty(collect, tEnterpriseInfo.getEnterpriseId());

                    Map<String, List<TDetectorUser>> collect1 = yehuaqiUsers2.stream().collect(Collectors.groupingBy(TDetectorUser::getUserOwnId));

                    Iterator<TDetectorUser> iterator = noRepeatUserOwnIdList.iterator();
                    while (iterator.hasNext()) {
                        TDetectorUser next = iterator.next();

                        List<TDetectorUser> yehuaqiUsers3 = collect1.get(next.getUserOwnId());
                        if (yehuaqiUsers3 != null && yehuaqiUsers3.size() > 0) {
                            next.setUserId(yehuaqiUsers3.get(0).getUserId());
                            updateYehuaqiUsers.add(next);
                            iterator.remove();
                        }
                    }
                }

                //4 判断那些是 新增的，那些是 修改的后，进行 批量插入 和 批量更新操作。
                // 需要新增的
                if (noRepeatUserOwnIdList.size() > 0) {
                    successNum+=noRepeatUserOwnIdList.size();
                    itDetectorUserService.insertBatchForThirdParty(noRepeatUserOwnIdList);

                    for (TDetectorUser tYehuaqiUser : noRepeatUserOwnIdList) {

                        lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgLiquefiedGasUser", tYehuaqiUser.toString(), encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);

                        List<UserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = tYehuaqiUser.getUserManageSafetyDeviceExportVos();
                        if (userManageSafetyDeviceExportVos != null && userManageSafetyDeviceExportVos.size() > 0) {
                            for (UserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVos) {
                                TGasuserSafetyDeviceInfo tYehuaqiuserSafetyDeviceInfo = new TGasuserSafetyDeviceInfo();
                                BeanUtils.copyProperties(userManageSafetyDeviceExportVo,tYehuaqiuserSafetyDeviceInfo);
                                tYehuaqiuserSafetyDeviceInfo.setRelationGasuserId(tYehuaqiUser.getUserId());
                                yehuaqiuserSafetyDeviceInfos.add(tYehuaqiuserSafetyDeviceInfo);
                            }
                        }
                    }
                }

                // 批量插入安全装置
                if (yehuaqiuserSafetyDeviceInfos.size() > 0) {
                    itDetectorUserService.insertBatchSafetyDevice(yehuaqiuserSafetyDeviceInfos);
                }

                //5 需要批量修改的
                if (updateYehuaqiUsers.size() > 0) {
                    successNum+=updateYehuaqiUsers.size();
                    for (TDetectorUser updateYehuaqiUser : updateYehuaqiUsers) {

                        lpgThirdPartyDockingInterfaceRecord = successRecord("createLpgLiquefiedGasUser", updateYehuaqiUser.toString(), encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);

                        List<UserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = updateYehuaqiUser.getUserManageSafetyDeviceExportVos();

                        if (userManageSafetyDeviceExportVos != null && userManageSafetyDeviceExportVos.size() > 0) {
                            for (UserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVos) {
                                TGasuserSafetyDeviceInfo yehuaqiuserSafetyDeviceInfo = new TGasuserSafetyDeviceInfo();
                                BeanUtils.copyProperties(userManageSafetyDeviceExportVo,yehuaqiuserSafetyDeviceInfo);
                                yehuaqiuserSafetyDeviceInfo.setRelationGasuserId(updateYehuaqiUser.getUserId());
                                updateYehuaqiuserSafetyDeviceInfos.add(yehuaqiuserSafetyDeviceInfo);
                            }
                        }
                    }

                    // 批量修改 燃气用户
                    itDetectorUserService.updateBatch(updateYehuaqiUsers);
                    // 批量修改完 燃气用户后 再处理 燃气用户下的 安全装置。先删除，再新增
                    List<Long> collect = updateYehuaqiUsers.stream().map(TDetectorUser::getUserId).collect(Collectors.toList());
                    itDetectorUserService.deleteBatchSafetyDeviceByUserIds(collect);
                    itDetectorUserService.insertBatchSafetyDevice(updateYehuaqiuserSafetyDeviceInfos);
                }
            }
            // 6 接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }
        StringBuilder sb = new StringBuilder();
        if (errorNum > 0 || repeatNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条;重复").append(repeatNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 查询基本信息维护-用户管理-居住区(村庄)列表
     */
    @GetMapping("/queryUserManageVillage")
    public AjaxResult queryUserManageVillage(Integer pageNum,Integer pageSize,String qybm)
    {
        if (pageNum == null || pageSize == null || StringUtils.isBlank(qybm)) {
            return AjaxResult.error("分页参数会企业编码不许不为空！！！");
        }

        if (pageSize > 1000) {
            return AjaxResult.error("分页参数不能超过1000");
        }

        keyInformation selectkey = decryptService.selectkey(qybm);

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }


        return AjaxResult.success(itUserManageVillageService.queryUserManageVillageForThirdParty(pageNum,pageSize));
    }



    /**
     * 创建 居住区(村庄)接口
     * @return r
     */
    @PostMapping("/createUserManageVillage")
    public AjaxResult createUserManageVillage(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TUserManageVillage> userManageVillages = new ArrayList<>();

            List<TUserManageVillage> noRepeatList = new ArrayList<>();

            TUserManageVillage userManageVillage;

            String dateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (JSONObject object : list) {
                userManageVillage = new TUserManageVillage();

                //居住区(村庄)名称
                String fVillageName = object.getString("fVillageName");
                if (StringUtils.isBlank(fVillageName)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                            "居住区(村庄)名称不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                if(fVillageName.length() > 50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                            "居住区(村庄)名称不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }


                //居民总户数
                String fTotalNumHouse = object.getString("fTotalNumHouse");
                if (StringUtils.isBlank(fTotalNumHouse)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                            "居民总户数不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                long fTotalNumHousel = 0L;
                try {
                    fTotalNumHousel = Long.parseLong(fTotalNumHouse);
                } catch (NumberFormatException e) {

                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                            "居民总户数不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 县（市、区）行政区划编码
                String countyCode = object.getString("countyCode") == null ? "" : object.getString("countyCode");
                if(countyCode.length()>50) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createLpgDeliveryRecord", object.toJSONString(),
                            "县（市、区）行政区划编码不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 瓶装燃气用户数
                String fBottledGasUsers = object.getString("fBottledGasUsers") == null ? "" : object.getString("fBottledGasUsers");

                long fBottledGasUsersl = 0L;
                if (fBottledGasUsers.length() > 0) {
                    try {
                        fBottledGasUsersl = Long.parseLong(fBottledGasUsers);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                                "瓶装燃气用户数不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 管道燃气用户数
                String fPipeGasUsers = object.getString("fPipeGasUsers") == null ? "" : object.getString("fPipeGasUsers");

                long fPipeGasUsersl = 0L;
                if (fPipeGasUsers.length() > 0) {
                    try {
                        fPipeGasUsersl = Long.parseLong(fPipeGasUsers);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                                "管道燃气用户数不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 经度
                String longitude = object.getString("longitude") == null ? "" : object.getString("longitude");

                BigDecimal bigDecimalLongitude = BigDecimal.ZERO;
                if (longitude.length() > 0) {
                    try {
                        bigDecimalLongitude = new BigDecimal(longitude);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                                "经度不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 纬度
                String latitude = object.getString("latitude") == null ? "" : object.getString("latitude");

                BigDecimal bigDecimalLatitude = BigDecimal.ZERO;
                if (latitude.length() > 0) {
                    try {
                        bigDecimalLatitude = new BigDecimal(latitude);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                                "纬度不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 备注
                String remarks = object.getString("remarks") == null ? "" : object.getString("remarks");

                if (remarks.length() > 255) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", object.toJSONString(),
                            "备注不符合要求！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                userManageVillage.setfVillageName(fVillageName);
                userManageVillage.setCountyCode(countyCode);
                userManageVillage.setfTotalNumHouse(fTotalNumHousel);
                userManageVillage.setfPipeGasUsers(fPipeGasUsersl);
                userManageVillage.setfBottledGasUsers(fBottledGasUsersl);
                if (!BigDecimal.ZERO.equals(bigDecimalLongitude)) {
                    userManageVillage.setLongitude(bigDecimalLongitude);
                }
                if (!BigDecimal.ZERO.equals(bigDecimalLatitude)) {
                    userManageVillage.setLatitude(bigDecimalLatitude);
                }
                userManageVillage.setRemarks(remarks);
                userManageVillages.add(userManageVillage);
            }

            if (userManageVillages.size() > 0) {
                //1 查看 录入的行政区是否符合要求
                List<String> collect = userManageVillages.stream().filter(item -> StringUtils.isNotBlank(item.getCountyCode()))
                        .map(TUserManageVillage::getCountyCode).collect(Collectors.toList());

                List<TCountyLevelRegion> tCountyLevelRegions = countyLevelRegionService.queryByCountyCodes(collect);
                Map<String, List<TCountyLevelRegion>> collect1 = tCountyLevelRegions.stream().collect(Collectors.groupingBy(TCountyLevelRegion::getfCountyCode));
                Iterator<TUserManageVillage> iterator = userManageVillages.iterator();
                while (iterator.hasNext()) {
                    TUserManageVillage next = iterator.next();
                    if (StringUtils.isNotBlank(next.getCountyCode())) {
                        List<TCountyLevelRegion> tCountyLevelRegions1 = collect1.get(next.getCountyCode());
                        if (tCountyLevelRegions1 == null || tCountyLevelRegions1.size() == 0) {
                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", next.toString(),
                                    "县（市、区）行政区划编码 不符合要求！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            errorNum++;
                            iterator.remove();
                        }else {
                            next.setfRegion(tCountyLevelRegions1.get(0).getfId());
                        }
                    }
                }

                //2 过滤完 行政区后 再过滤 村 是否在系统里面已存在。
                if (userManageVillages.size() > 0) {
                    List<String> collect2 = userManageVillages.stream().map(TUserManageVillage::getfVillageName).collect(Collectors.toList());
                    List<TUserManageVillage> userManageVillages1 = itUserManageVillageService.queryByVillageNames(collect2);
                    Map<String, List<TUserManageVillage>> collect3 = userManageVillages1.stream().collect(Collectors.groupingBy(TUserManageVillage::getfVillageName));

                    Iterator<TUserManageVillage> iterator1 = userManageVillages.iterator();
                    while (iterator.hasNext()) {
                        TUserManageVillage next = iterator1.next();
                        List<TUserManageVillage> userManageVillages2 = collect3.get(next.getfVillageName());
                        if (userManageVillages2 != null && userManageVillages2.size() > 0) {

                            lpgThirdPartyDockingInterfaceRecord = errorRecord("createUserManageVillage", next.toString(),
                                    "居住区(村庄) 名称已存在！！！", encryption.getQybm());
                            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                            errorNum++;
                            iterator.remove();
                        }
                    }
                }

                //3 都过滤完后 看看 集合里面名称有没有重复的。
                if (userManageVillages.size() > 0) {
                    Set<TUserManageVillage> set = new HashSet<>(userManageVillages);
                    int i = userManageVillages.size() - set.size();
                    if (i > 0) {
                        repeatNum = i;
                    }
                    noRepeatList = new ArrayList<>(set);
                }

                //4 都验证后 入库
                if(noRepeatList.size() > 0) {
                    successNum = noRepeatList.size();
                    for (TUserManageVillage tUserManageVillage : noRepeatList) {
                        lpgThirdPartyDockingInterfaceRecord = successRecord("createUserManageVillage", tUserManageVillage.toString(), encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    }
                    itUserManageVillageService.insertBatch(noRepeatList);
                }
            }

            // 5接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0 || repeatNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条;重复：").append(repeatNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }

    /**
     * 创建 巡检事故接口
     * @return r
     */
    @PostMapping("/inspectionAccident")
    public AjaxResult inspectionAccident(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TInspectionAccident> userTInspectionAccidents = new ArrayList<>();

            //List<TUserManageVillage> userManageVillages = new ArrayList<>();

            List<TInspectionAccident> noRepeatList = new ArrayList<>();

            TInspectionAccident userTInspectionAccident;

            String dateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (JSONObject object : list) {
                userTInspectionAccident = new TInspectionAccident();

                //事故名称
                String accidentName = object.getString("accidentName");
                if (StringUtils.isBlank(accidentName)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionAccident", object.toJSONString(),
                            "事故名称不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                // 经度
                String longitude = object.getString("longitude") == null ? "" : object.getString("longitude");

                BigDecimal bigDecimalLongitude = BigDecimal.ZERO;
                if (longitude.length() > 0) {
                    try {
                        bigDecimalLongitude = new BigDecimal(longitude);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionAccident", object.toJSONString(),
                                "经度不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }

                // 纬度
                String latitude = object.getString("latitude") == null ? "" : object.getString("latitude");

                BigDecimal bigDecimalLatitude = BigDecimal.ZERO;
                if (latitude.length() > 0) {
                    try {
                        bigDecimalLatitude = new BigDecimal(latitude);
                    } catch (NumberFormatException e) {
                        lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionAccident", object.toJSONString(),
                                "纬度不符合要求！！！", encryption.getQybm());
                        lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                        errorNum++;
                        continue;
                    }
                }
                userTInspectionAccident.setAccidentName(accidentName);
                userTInspectionAccident.setHappenDate(object.getString("happenDate") == null ? "" : object.getString("happenDate"));
                userTInspectionAccident.setAccidentLocation(object.getString("accidentLocation") == null ? "" : object.getString("accidentLocation"));
                if (!BigDecimal.ZERO.equals(bigDecimalLongitude)) {
                    userTInspectionAccident.setLongitude(bigDecimalLongitude);
                }
                if (!BigDecimal.ZERO.equals(bigDecimalLatitude)) {
                    userTInspectionAccident.setLatitude(bigDecimalLatitude);
                }
                userTInspectionAccident.setAccidentDescription(object.getString("accidentDescription") == null ? "" : object.getString("accidentDescription"));
                userTInspectionAccident.setAccidentReason(object.getString("accidentReason") == null ? "" : object.getString("accidentReason"));
                userTInspectionAccident.setObligationPerson(object.getString("obligationPerson") == null ? "" : object.getString("obligationPerson"));
                userTInspectionAccident.setBeyondEnterpriseId(tEnterpriseInfo.getEnterpriseId());
                userTInspectionAccident.setBeyondEnterpriseName(tEnterpriseInfo.getEnterpriseName());
                userTInspectionAccident.setCreateTime(new Date());
                userTInspectionAccident.setRemark(object.getString("remark") == null ? "" : object.getString("remark"));
                userTInspectionAccidents.add(userTInspectionAccident);
            }

            if (userTInspectionAccidents.size() > 0) {
                successNum = userTInspectionAccidents.size();
                for (TInspectionAccident tInspectionAccident : userTInspectionAccidents) {
                    lpgThirdPartyDockingInterfaceRecord = successRecord("inspectionAccident", tInspectionAccident.toString(), encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                }
                tInspectionAccidentService.insertBatch(userTInspectionAccidents);
            }

            // 5接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条。");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }

    /**
     * 创建 巡检轨迹接口
     * @return r
     */
    @PostMapping("/inspectionRoute")
    public AjaxResult inspectionRoute(@RequestBody Encryption encryption) {

        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());

        if (selectkey == null) {
            return AjaxResult.error("企业编码不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, selectkey.getSecretKey());

        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        int successNum = 0;
        int errorNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

            if (list.size() > 500) {
                return AjaxResult.error("每次最多处理500条数据");
            }

            List<TLinePatrol> userTLinePatrols = new ArrayList<>();

            List<TLinePatrol> noRepeatList = new ArrayList<>();

            TLinePatrol userTLinePatrol;

            String dateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

            // 接口保存记录
            List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
            TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
            for (JSONObject object : list) {
                userTLinePatrol = new TLinePatrol();

                //任务名称
                String taskName = object.getString("taskName");
                if (StringUtils.isBlank(taskName)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionRoute", object.toJSONString(),
                            "任务名称不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }
                //任务名称
                String linePatrolPerson = object.getString("linePatrolPerson");
                if (StringUtils.isBlank(linePatrolPerson)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionRoute", object.toJSONString(),
                            "巡检人员不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //任务名称
                String linePatrolTime = object.getString("linePatrolTime");
                if (StringUtils.isBlank(linePatrolTime)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionRoute", object.toJSONString(),
                            "巡检时间不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                //任务名称
                String coordinates = object.getString("coordinates");
                if (StringUtils.isBlank(coordinates)) {
                    lpgThirdPartyDockingInterfaceRecord = errorRecord("inspectionRoute", object.toJSONString(),
                            "坐标不许为空！！！", encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                    errorNum++;
                    continue;
                }

                userTLinePatrol.setTaskName(taskName);
                userTLinePatrol.setLinePatrolPerson(linePatrolPerson);
                userTLinePatrol.setLinePatrolTime(linePatrolTime);
                userTLinePatrol.setCoordinates(coordinates);
                userTLinePatrol.setBeyondEnterpriseId(tEnterpriseInfo.getEnterpriseId());
                userTLinePatrol.setBeyondEnterpriseName(tEnterpriseInfo.getEnterpriseName());
                userTLinePatrol.setCreateTime(new Date());
                userTLinePatrol.setRemark(object.getString("remark") == null ? "" : object.getString("remark"));
                userTLinePatrols.add(userTLinePatrol);
            }

            if (userTLinePatrols.size() > 0) {
                successNum = userTLinePatrols.size();
                for (TLinePatrol tLinePatrol : userTLinePatrols) {
                    lpgThirdPartyDockingInterfaceRecord = successRecord("inspectionRoute", tLinePatrol.toString(), encryption.getQybm());
                    lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                }
                tLinePatrolService.insertBatch(userTLinePatrols);
            }

            // 5接口记录直接插入
            if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
                lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条。");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }


    /**
     * 封装一个 失败的接口对象
     * @return r
     */
    public TLpgThirdPartyDockingInterfaceRecord errorRecord(String interfaceName,String receiveData,
                                                             String failureReason,String qybm){

        TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord = new TLpgThirdPartyDockingInterfaceRecord();
        lpgThirdPartyDockingInterfaceRecord.setInterfaceName(interfaceName);
        lpgThirdPartyDockingInterfaceRecord.setReceiveData(receiveData);
        lpgThirdPartyDockingInterfaceRecord.setFailureReason(failureReason);
        // 1 失败
        lpgThirdPartyDockingInterfaceRecord.setState("1");
        lpgThirdPartyDockingInterfaceRecord.setReceiveDate(new Date());
        lpgThirdPartyDockingInterfaceRecord.setQybm(qybm);

        return lpgThirdPartyDockingInterfaceRecord;
    }

    /**
     * 返回一个 成功的接口对象
     * @return r
     */
    public TLpgThirdPartyDockingInterfaceRecord successRecord(String interfaceName,String receiveData,String qybm) {

        TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord = new TLpgThirdPartyDockingInterfaceRecord();
        lpgThirdPartyDockingInterfaceRecord.setInterfaceName(interfaceName);
        lpgThirdPartyDockingInterfaceRecord.setReceiveData(receiveData);
        // 0 成功
        lpgThirdPartyDockingInterfaceRecord.setState("0");
        lpgThirdPartyDockingInterfaceRecord.setReceiveDate(new Date());
        lpgThirdPartyDockingInterfaceRecord.setQybm(qybm);

        return lpgThirdPartyDockingInterfaceRecord;
    }
}
