Selaa lähdekoodia

水量同步定时任务

wangli 4 vuotta sitten
vanhempi
commit
6fe6f1f1fb

+ 7 - 7
smart-city-platform/src/main/java/com/bz/smart_city/controller/common/CommonController.java

@@ -45,13 +45,13 @@ public class CommonController {
         return new AjaxMessage<>(ResultStatus.OK, list);
     }
 
-    @GetMapping("/getAllArea")
-    @ApiOperation(value = "获取所有的省市区")
-    public AjaxMessage<List<AreaDto>> getAllArea(
-    ) {
-        List<AreaDto> list = areaMapper.getAllArea();
-        return new AjaxMessage<>(ResultStatus.OK, TreeUtil.getArea(list, 100000, 1));
-    }
+//    @GetMapping("/getAllArea")
+//    @ApiOperation(value = "获取所有的省市区")
+//    public AjaxMessage<List<AreaDto>> getAllArea(
+//    ) {
+//        List<AreaDto> list = areaMapper.getAllArea();
+//        return new AjaxMessage<>(ResultStatus.OK, TreeUtil.getArea(list, 100000, 1));
+//    }
 
 
 }

+ 3 - 6
smart-city-platform/src/main/java/com/bz/smart_city/dao/pay/AmountWaterUsedAmountMapper.java

@@ -52,9 +52,6 @@ public interface AmountWaterUsedAmountMapper {
 
     Integer createdAmountByDay(@Param("siteId") Integer siteId, @Param("customerId")Integer customerId);
 
-    @MapKey("deviceId")
-    HashMap<BigInteger, MeterReadRecordDto> getMeterReadRecord(@Param("list")List<BigInteger> list);
-
     @MapKey("watermeterId")
     HashMap<BigInteger, AmountWaterUsedAmountByDay> getAmountWaterUsedAmountByDay(@Param("siteId") Integer siteId, @Param("customerId")Integer customerId);
 
@@ -90,8 +87,8 @@ public interface AmountWaterUsedAmountMapper {
     //获取同步计划
     List<String> GetAmountSynInfo(@Param("year") Integer year, @Param("month") Integer month, @Param("siteId") Integer siteId, @Param("customerId") Integer customerId);
 
-    //换表统计 list:设备ID
-    @MapKey("deviceId")
-    HashMap<BigInteger, ReplaceMeterCountDto> getRepalceRecordCount(@Param("stTime")LocalDateTime stTime, @Param("etTime")LocalDateTime etTime, @Param("list")List<BigInteger> list,@Param("siteId")Integer siteId,@Param("customerId")Integer customerId);
+
+    @MapKey("metercode")
+    HashMap<String, DeviceReplaceRecord > getRepalceRecordCount(@Param("year")Integer year, @Param("month")Integer month,@Param("siteId")Integer siteId,@Param("customerId")Integer customerId);
 
 }

+ 29 - 0
smart-city-platform/src/main/java/com/bz/smart_city/dto/pay/AmountDaySynParamDto.java

@@ -0,0 +1,29 @@
+package com.bz.smart_city.dto.pay;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * @description
+ * @auto wangli
+ * @data 2020-10-09 8:28
+ */
+@Data
+@Api("结算水量同步接口请求参数")
+public class AmountDaySynParamDto implements Serializable {
+
+    private static final long serialVersionUID = 3519394900406918279L;
+
+    @ApiModelProperty("账期,格式yyyymmdd")
+    private String readTime;
+
+    @ApiModelProperty("客户编号")
+    private String customerNo;
+
+    @ApiModelProperty("水表编码")
+    private List<String> fileNo;
+}

+ 42 - 0
smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/AmountSyncByDayJob.java

@@ -0,0 +1,42 @@
+package com.bz.smart_city.quartz.job;
+
+import com.bz.smart_city.quartz.service.AmountSynByDayService;
+import lombok.extern.slf4j.Slf4j;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.io.Serializable;
+
+/**
+ * @author Administrator
+ * @create 2020-05-18 14:07
+ */
+@Slf4j
+@Component
+public  class AmountSyncByDayJob implements Job, Serializable {
+
+    private static final long serialVersionUID = 3336891083300321324L;
+
+    @Autowired
+    public AmountSynByDayService amountSynByDayService;
+
+
+
+    @Override
+    public void execute(JobExecutionContext context) throws JobExecutionException {
+        // 1,获取推送配置信息
+        /*JobDetail jobDetail = context.getJobDetail();
+        JobDataMap jobDataMap = jobDetail.getJobDataMap();
+        Integer siteId = jobDataMap.getInt("siteId");
+        Integer customerId = jobDataMap.getInt("customerId");
+        */
+        // 2,调用推送方法
+        log.info("invoke AmountSyncByDayJob");
+        amountSynByDayService.start();
+        log.info("invoked AmountSyncByDayJob");
+    }
+
+}

+ 39 - 0
smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/AmountSyncJob.java

@@ -0,0 +1,39 @@
+package com.bz.smart_city.quartz.job;
+
+import com.bz.smart_city.quartz.service.AmountSynService;
+import lombok.extern.slf4j.Slf4j;
+import org.quartz.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.io.Serializable;
+
+/**
+ * @author Administrator
+ * @create 2020-04-20 11:04
+ */
+@Slf4j
+@Component
+public class AmountSyncJob implements Job,Serializable {
+
+    @Autowired
+    public AmountSynService amountSynService;
+
+    private static final long serialVersionUID = 5386891083300321324L;
+
+    @Override
+    public void execute(JobExecutionContext context) throws JobExecutionException {
+        // 1,获取推送配置信息
+        JobDetail jobDetail = context.getJobDetail();
+        JobDataMap jobDataMap = jobDetail.getJobDataMap();
+        Integer siteId = jobDataMap.getInt("siteId");
+        Integer customerId = jobDataMap.getInt("customerId");
+
+        // 2,调用推送方法
+        log.info("invoke AmountSyncJob , customerId = {}",customerId);
+        amountSynService.amountUpdate(siteId,customerId);
+        log.info("invoked AmountSyncJob , customerId = {}",customerId);
+    }
+
+
+}

+ 248 - 0
smart-city-platform/src/main/java/com/bz/smart_city/quartz/service/impl/AmountSynDayServiceImpl.java

@@ -0,0 +1,248 @@
+package com.bz.smart_city.quartz.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.bz.smart_city.commom.util.DateTimeUtil;
+import com.bz.smart_city.commom.util.HttpClientUtils;
+import com.bz.smart_city.dao.CustomerMapper;
+import com.bz.smart_city.dao.pay.AmountWaterUsedAmountMapper;
+import com.bz.smart_city.dao.pay.BaseClosingAccountInfoMapper;
+import com.bz.smart_city.dto.pay.*;
+import com.bz.smart_city.entity.Customer;
+import com.bz.smart_city.entity.pay.AmountWaterUsedAmountByDay;
+import com.bz.smart_city.entity.pay.DeviceReplaceRecord;
+import com.bz.smart_city.entity.pay.archives.PayBaseCustomerandmeterrela;
+import com.bz.smart_city.quartz.entity.QuartzEntity;
+import com.bz.smart_city.quartz.job.AmountSyncByDayJob;
+import com.bz.smart_city.quartz.service.AmountSynByDayService;
+import com.bz.smart_city.quartz.service.AmountSynService;
+import com.bz.smart_city.quartz.service.JobAndTriggerService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * @description
+ * @auto wangli
+ * @data 2020-09-27 10:51
+ */
+@Slf4j
+@Component
+public class AmountSynDayServiceImpl implements AmountSynByDayService, InitializingBean {
+
+    @Value("1")
+    private BigInteger createBy;
+
+    @Value("http://114.135.61.188:58080/api/syncData/meterReadData")
+    private String amountDaySynUrl;
+
+    @Resource
+    private BaseClosingAccountInfoMapper baseClosingAccountInfoMapper;
+    @Resource
+    private AmountWaterUsedAmountMapper amountWaterUsedAmountMapper;
+    @Resource
+    private CustomerMapper customerMapper;
+    @Resource
+    private JobAndTriggerService jobAndTriggerService;
+
+    @Override
+    public void afterPropertiesSet() {
+        saveQrtzTask();
+    }
+
+    public void saveQrtzTask() {
+
+
+
+        // 1,查询需要批量推送的配置项目并构建定时任务
+        // 2,若对应定时任务不存在则创建
+        QuartzEntity entity = new QuartzEntity();
+        entity.setJobGroup("水量每天同步");
+        entity.setJobName("AmountSyncByDayJob" );
+        entity.setDescription("AmountSyncByDayJob" );
+        // modify by pengdi ,判断定时任务是否存在,不存在才进行新增
+
+        boolean exists = jobAndTriggerService.isExists(entity);
+        if(!exists){
+            String cron = "0 */1 * * * ?";
+            log.info("水量每天同步:" + cron);
+            entity.setCronExpression(cron);
+            entity.setJobClassName(AmountSyncByDayJob.class.getName());
+            jobAndTriggerService.save(entity);
+        }
+    }
+
+
+    public void deleteQrtzTask() {
+        // 1,查询需要批量推送的配置项目并构建定时任务
+        QuartzEntity entity = new QuartzEntity();
+        entity.setJobGroup("水量每天同步");
+        entity.setJobName("AmountSyncByDayJob");
+        if (jobAndTriggerService.isExists(entity)) {
+            jobAndTriggerService.deleteJob(entity);
+        }
+    }
+
+    public void start(){
+        List<PayBaseCustomerandmeterrela> payBaseCustomerandmeterrelas = amountWaterUsedAmountMapper.getCustIdAndSiteId();
+        for (PayBaseCustomerandmeterrela payBaseCustomerandmeterrela: payBaseCustomerandmeterrelas){
+            this.amountUpdateByDay(payBaseCustomerandmeterrela.getSiteId().intValue(),payBaseCustomerandmeterrela.getCustomerId().intValue());
+        }
+    }
+
+    @Override
+    public void amountUpdateByDay(Integer siteId, Integer customerId) {
+        //获取最新账期
+        BaseClosingAccountInfoDto baseClosingAccountInfoDto = baseClosingAccountInfoMapper.getLastClosingAccount(siteId, customerId);
+
+        if(baseClosingAccountInfoDto == null
+                || baseClosingAccountInfoDto .getYear() == null
+                || baseClosingAccountInfoDto.getMonth() == null){
+            log.info("每天同步水量失败:获取账期信息失败");
+            return ;
+        }
+        Integer year=baseClosingAccountInfoDto.getYear();
+        Integer month=baseClosingAccountInfoDto.getMonth();
+        //插入水量基础信息(同步计划)
+        Integer amountNumber = amountWaterUsedAmountMapper.getAllAmountCountByDay(siteId,customerId);
+        if(amountNumber == 0){
+            log.info("每天同步水量失败:生成同步计划失败");
+            return;
+        }
+        //获取客户编号
+        List<Customer> customers = customerMapper.getListById(customerId);
+        if(customers .size() != 1){
+            log.info("每天同步水量失败:查询客户信息异常");
+            return;
+        }
+        String customerNo=customers.get(0).getCustomerNo();
+        //获取同步计划
+        List<AmountWaterUsedAmountByDay> amountWaterUsedAmountDtos = amountWaterUsedAmountMapper.getAllAmountRecordByDay(siteId, customerId);
+
+
+        if(amountWaterUsedAmountDtos.size() == 0){
+            log.info("每天同步水量失败:获取同步计划失败");
+            return;
+        }
+        //提取出水表编码集合
+        List<String> metercodes = amountWaterUsedAmountDtos.stream().map(
+                AmountWaterUsedAmountByDay -> AmountWaterUsedAmountByDay.getMetercode()).collect(Collectors.toList());
+
+        //获取账期内换表记录
+        HashMap<String, DeviceReplaceRecord> replaceRecordMap = amountWaterUsedAmountMapper.getRepalceRecordCount(year,month,siteId,customerId);
+
+        //批量更新水量信息
+        List<AmountWaterUsedAmountByDay> updates = new ArrayList<>();
+
+        //抄表数据结果
+        List<AmountSynRespDto> lists =new ArrayList<>();
+
+        for(int i=0;i<metercodes.size();i+=500){
+            AmountDaySynParamDto amountDaySynParamDto= new AmountDaySynParamDto();
+            amountDaySynParamDto.setReadTime(DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now().plusDays(-1)));
+            amountDaySynParamDto.setCustomerNo(customerNo);
+            //一次查询五百条
+            List<String> selectList ;
+            if(i+500 >= metercodes.size()){
+                selectList=metercodes.subList(i,metercodes.size());
+            }else{
+                selectList=metercodes.subList(i,i+500);
+            }
+            amountDaySynParamDto.setFileNo(selectList);
+
+            String context=JSON.toJSON(amountDaySynParamDto).toString();
+            try {
+                String result= HttpClientUtils.doPostWithJson(amountDaySynUrl,context);
+                log.info("每天同步水量请求结果"+result);
+
+                JSONObject jsonObject= JSON.parseObject(result);
+                Integer status= jsonObject.getInteger("status");
+                if(status .equals(0)){   //返回正常
+                    JSONObject datas = jsonObject.getJSONObject("data");
+                    String total = datas.getString("total");
+                    if(StringUtils.isNotBlank(total) && Integer.valueOf(total) > 0){//有数据
+                        JSONArray jsonArray = datas.getJSONArray("list");
+                        List<AmountSynRespDto> list = jsonArray.toJavaList(AmountSynRespDto.class);
+
+                        lists.addAll(list);
+                    }
+                }
+            }catch (Exception e){
+                e.printStackTrace();
+            }
+        }
+
+        Map<String ,AmountSynRespDto> map = lists.stream().collect(Collectors.toMap(AmountSynRespDto::getFileNo, Function.identity(), (key1, key2) -> key2));
+
+
+        for (AmountWaterUsedAmountByDay amountWaterUsedAmountByDay : amountWaterUsedAmountDtos) {
+            BigInteger watermeterId = amountWaterUsedAmountByDay.getWatermeterId();
+            if (watermeterId != null && map.containsKey(amountWaterUsedAmountByDay.getMetercode())) {
+                AmountSynRespDto amountSynRespDto = map.get(amountWaterUsedAmountByDay.getMetercode());
+                BigDecimal readingOld = amountWaterUsedAmountByDay.getLastreading();//上期止度
+
+                if (amountSynRespDto.getReading() != null) {
+                    BigDecimal readingNew = new BigDecimal(amountSynRespDto.getReading()).setScale(0, BigDecimal.ROUND_DOWN);//本期止度
+
+                    BigDecimal payAmount ;//结算水量
+
+                    BigDecimal Amount ;//实际用水量
+
+                    BigDecimal replaceAmount = BigDecimal.ZERO;//旧表用水量
+
+                    String readDate = amountSynRespDto.getCurrentPeriodDate();
+
+                    Integer calculateway = amountWaterUsedAmountByDay.getCalculateway();
+
+                    //换表记录计算
+                    if(replaceRecordMap.containsKey(amountWaterUsedAmountByDay.getMetercode())){
+                        DeviceReplaceRecord deviceReplaceRecord = replaceRecordMap.get(amountWaterUsedAmountByDay.getMetercode());
+                        replaceAmount=deviceReplaceRecord.getOldAmount();
+                    }
+                    //实际水量=本期水量+换表前水量
+                     Amount = readingNew.subtract(readingOld).add(replaceAmount);
+
+                        //计量方式判断
+                        if (calculateway.equals(1))//按实际用量
+                            payAmount = Amount;
+                        else if (calculateway.equals(2))//按固定量
+                            payAmount = BigDecimal.valueOf(amountWaterUsedAmountByDay.getFixedamount());
+                        else
+                            payAmount = Amount;
+
+                        if (payAmount.compareTo(BigDecimal.ZERO) < 0) {
+                            continue;
+                        }
+                    amountWaterUsedAmountByDay.setReading(readingNew);
+                    amountWaterUsedAmountByDay.setRecorddate(DateTimeUtil.parseDate(readDate, DateTimeUtil.DATE_TIME_FORMAT_SECOND));
+                    amountWaterUsedAmountByDay.setAmount(Amount);
+                    amountWaterUsedAmountByDay.setPayamount(payAmount);
+                    updates.add(amountWaterUsedAmountByDay);
+                    }
+                }
+            }
+            if (updates.size() > 0) {
+
+                for (AmountWaterUsedAmountByDay amountWaterUsedAmountDto : updates) {
+                    amountWaterUsedAmountMapper.updateByDate(amountWaterUsedAmountDto);
+                }
+            }
+        log.info("每天水量同步结束:" + LocalDateTime.now());
+        }
+}

+ 86 - 95
smart-city-platform/src/main/java/com/bz/smart_city/quartz/service/impl/AmountSynServiceImpl.java

@@ -11,21 +11,25 @@ import com.bz.smart_city.dao.pay.BaseClosingAccountInfoMapper;
 import com.bz.smart_city.dao.pay.PayBaseConfigMapper;
 import com.bz.smart_city.dto.pay.*;
 import com.bz.smart_city.entity.Customer;
+import com.bz.smart_city.entity.pay.DeviceReplaceRecord;
+import com.bz.smart_city.quartz.entity.QuartzEntity;
+import com.bz.smart_city.quartz.job.AmountSyncJob;
 import com.bz.smart_city.quartz.service.AmountSynService;
 import com.bz.smart_city.quartz.service.JobAndTriggerService;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.InitializingBean;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.math.BigInteger;
-import java.time.Duration;
 import java.time.LocalDateTime;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 
@@ -36,7 +40,7 @@ import java.util.stream.Collectors;
  */
 @Slf4j
 @Component
-public class AmountSynServiceImpl implements AmountSynService {
+public class AmountSynServiceImpl implements AmountSynService , InitializingBean {
 
     @Value("1")
     private BigInteger createBy;
@@ -51,12 +55,58 @@ public class AmountSynServiceImpl implements AmountSynService {
     @Resource
     private CustomerMapper customerMapper;
     @Resource
-    private PayBaseConfigMapper payBaseConfigMapper;
-    @Resource
     private JobAndTriggerService jobAndTriggerService;
+    @Resource
+    private PayBaseConfigMapper payBaseConfigMapper;
+
     @Override
+    public void afterPropertiesSet() {
+        //获取系统参数
+        List<PayBaseConfigDto> payBaseConfigDtos = payBaseConfigMapper.getAllList("AUTO_SYNUAMOUNT_TIME",null,null,null);
+
+        //循环添加定时任务
+        for(PayBaseConfigDto payBaseConfigDto :payBaseConfigDtos){
+            saveQrtzTask(payBaseConfigDto);
+        }
+    }
+
     public void saveQrtzTask(PayBaseConfigDto payBaseConfigDto) {
 
+
+        String  value = payBaseConfigDto.getValue();
+        if(value == null|| value==""){   //获取定时corn失败
+            return;
+        }
+        // 1,查询需要批量推送的配置项目并构建定时任务
+        // 2,若对应定时任务不存在则创建
+        QuartzEntity entity = new QuartzEntity();
+        entity.setJobGroup("水量同步");
+        entity.setJobName("AmountSyncJob"+payBaseConfigDto.getCustomerId());
+        entity.setDescription("AmountSyncJob"+payBaseConfigDto.getCustomerId());
+        boolean exists = jobAndTriggerService.isExists(entity);
+        if(!exists){
+            String[] values = value.split("_");
+            String cron = "0 */"+values[2]+" * "+values[0]+"-"+values[1]+" * ?";
+            log.info("水量同步cron:"+cron);
+            entity.setCronExpression(cron);
+            entity.setJobClassName(AmountSyncJob.class.getName());
+            HashMap<String, Object> jobData = new HashMap<String, Object>();
+            jobData.put("siteId", payBaseConfigDto.getSiteId().intValue());
+            jobData.put("customerId", payBaseConfigDto.getCustomerId().intValue());
+            entity.setJobData(jobData);
+            jobAndTriggerService.save(entity);
+        }
+    }
+
+
+    public void deleteQrtzTask(BigInteger id) {
+        // 1,查询需要批量推送的配置项目并构建定时任务
+        QuartzEntity entity = new QuartzEntity();
+        entity.setJobGroup("水量同步");
+        entity.setJobName("AmountSyncJob"+id);
+        if(jobAndTriggerService.isExists(entity)){
+            jobAndTriggerService.deleteJob(entity);
+        }
     }
 
     @Override
@@ -91,20 +141,25 @@ public class AmountSynServiceImpl implements AmountSynService {
             log.info("同步水量失败:获取同步计划失败");
             return;
         }
+        //提取出水表编码集合
         List<String> metercodes = amountWaterUsedAmountDtos.stream().map(
                 AmountWaterUsedAmountDto -> AmountWaterUsedAmountDto.getMetercode()).collect(Collectors.toList());
-//        List<String> metercodes =amountWaterUsedAmountMapper.GetAmountSynInfo(year,month,siteId,customerId);
+
+        //获取账期内换表记录
+        HashMap<String, DeviceReplaceRecord> replaceRecordMap = amountWaterUsedAmountMapper.getRepalceRecordCount(year,month,siteId,customerId);
 
         //批量更新水量信息
         List<AmountWaterUsedAmountDto> updates = new ArrayList<>();
 
+        //抄表数据结果
         List<AmountSynRespDto> lists =new ArrayList<>();
+
         for(int i=0;i<metercodes.size();i+=500){
             AmountSynParamDto amountSynParamDto= new AmountSynParamDto();
             amountSynParamDto.setYyyymm(year+""+month);
             amountSynParamDto.setCustomerNo(customerNo);
             //一次查询五百条
-            List<String> selectList = new ArrayList<>();
+            List<String> selectList ;
             if(i+500 >= metercodes.size()){
                 selectList=metercodes.subList(i,metercodes.size());
             }else{
@@ -125,107 +180,51 @@ public class AmountSynServiceImpl implements AmountSynService {
                     if(StringUtils.isNotBlank(total) && Integer.valueOf(total) > 0){//有数据
                         JSONArray jsonArray = datas.getJSONArray("list");
                         List<AmountSynRespDto> list = jsonArray.toJavaList(AmountSynRespDto.class);
+
                         lists.addAll(list);
                     }
                 }
-
             }catch (Exception e){
                 e.printStackTrace();
             }
         }
 
-
-
-
         Map<String ,AmountSynRespDto> map = lists.stream().collect(Collectors.toMap(AmountSynRespDto::getFileNo, Function.identity(), (key1, key2) -> key2));
 
-
-
         //换表记录
-        HashMap<BigInteger, ReplaceMeterCountDto> replaceMap = new HashMap<>();
-        LocalDateTime stTime = LocalDateTime.ofInstant(baseClosingAccountInfoDto.getStartTime().toInstant(), ZoneId.systemDefault());
-        HashMap<BigInteger, ReplaceMeterCountDto> childReplaceMap = amountWaterUsedAmountMapper.getRepalceRecordCount(stTime,null,null,null,customerId);
-        if(childReplaceMap.size() >0){
-            List<ReplaceMeterDto> replaceMeterDtoList = amountWaterUsedAmountMapper.getRepalceRecordDetail(stTime,null,null,null,customerId);
-            if(replaceMeterDtoList.size() >0){
-                for(int i=0;i<replaceMeterDtoList.size();i++){
-                    if(childReplaceMap.containsKey(replaceMeterDtoList.get(i).getDeviceId())){
-                        ReplaceMeterCountDto replaceMeterCountDto = childReplaceMap.get(replaceMeterDtoList.get(i).getDeviceId());
-                        if(replaceMeterCountDto.getReplaceMeterDtoList() == null)
-                        {
-                            replaceMeterCountDto.setReplaceMeterDtoList(new ArrayList<>());
-                        }
-                        replaceMeterCountDto.getReplaceMeterDtoList().add(replaceMeterDtoList.get(i));
-                    }
-                }
-            }
-            replaceMap.putAll(childReplaceMap);
-        }
+
 
         for (AmountWaterUsedAmountDto amountWaterUsedAmountDto : amountWaterUsedAmountDtos) {
             BigInteger watermeterId = amountWaterUsedAmountDto.getWatermeterId();
             if (watermeterId != null && map.containsKey(amountWaterUsedAmountDto.getMetercode())) {
                 AmountSynRespDto amountSynRespDto = map.get(amountWaterUsedAmountDto.getMetercode());
-                BigInteger amountId = amountWaterUsedAmountDto.getId();//水量id
                 BigDecimal readingOld = amountWaterUsedAmountDto.getLastreading();//上期止度
+
                 if (amountSynRespDto.getReading() != null) {
                     BigDecimal readingNew = new BigDecimal(amountSynRespDto.getReading()).setScale(0, BigDecimal.ROUND_DOWN);//本期止度
-                    BigInteger meterid = amountWaterUsedAmountDto.getWatermeterId();//水表id
-                    BigDecimal payAmount = BigDecimal.ZERO;//结算水量
-                    Date lastAmountDate = amountWaterUsedAmountDto.getLastrecorddate();
-                    BigDecimal Amount = BigDecimal.ZERO;//实际用水量
-                    BigDecimal tempReading = BigDecimal.ZERO;
-                    tempReading = readingOld;//起度或上期的止度
+
+                    BigDecimal payAmount ;//结算水量
+
+                    BigDecimal Amount ;//实际用水量
+
+                    BigDecimal replaceAmount = BigDecimal.ZERO;//旧表用水量
+
                     String readDate = amountSynRespDto.getCurrentPeriodDate();
+
                     Integer calculateway = amountWaterUsedAmountDto.getCalculateway();
 
                     //换表记录计算
-                    boolean replace = false;
-                    ReplaceMeterCountDto replaceMeterCountDto=null;
-                    if(replaceMap.containsKey(watermeterId)){
-                        replaceMeterCountDto = replaceMap.get(watermeterId);
-                        //有换表记录且换表时间在两次同步之间 用水量=(换表中的旧表止度-上次抄表止度) + (本次止度-换表中的新表起度)
-                        if(replaceMeterCountDto != null){
-                            LocalDateTime currTime = LocalDateTime.parse(readDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));//本次抄表时间
-                            LocalDateTime previousTime = LocalDateTime.ofInstant(amountWaterUsedAmountDto.getLastrecorddate().toInstant(),ZoneId.systemDefault()); //上个帐期的结算抄表时间
-
-                            ReplaceMeterDto oldReplaceMeterDto = null;
-                            for(int i = 0;i<replaceMeterCountDto.getReplaceMeterDtoList().size();i++){
-                                LocalDateTime replaceTime = replaceMeterCountDto.getReplaceMeterDtoList().get(i).getReplaceTime();   //换表时间
-
-                                Duration duration1 = Duration.between(previousTime,replaceTime);
-                                Duration duration2 = Duration.between(replaceTime,currTime);
-                                if(duration1.toMillis() > 0  && duration2.toMinutes() > 0){
-                                    BigDecimal replaceEndData = new BigDecimal(replaceMeterCountDto.getReplaceMeterDtoList().get(i).getOldEnd()).setScale(2,BigDecimal.ROUND_DOWN);//换表中的旧表止度
-                                    BigDecimal replaceData = BigDecimal.ZERO;
-                                    if(oldReplaceMeterDto == null)
-                                        replaceData = tempReading;
-                                    else
-                                        replaceData = new BigDecimal(oldReplaceMeterDto.getNewBegin()).setScale(0,BigDecimal.ROUND_DOWN);//换表中的起度
-                                    BigDecimal oldMeterUse = replaceEndData.subtract(replaceData); //旧表用量
-
-                                    Amount = Amount.add(oldMeterUse);
-                                    replace = true;
-
-                                    oldReplaceMeterDto = replaceMeterCountDto.getReplaceMeterDtoList().get(i);
-                                }
-                                else {
-                                    break;
-                                }
-                            }
-
-                            //新表用量
-                            if(oldReplaceMeterDto != null){
-                                BigDecimal replaceNewDate = new BigDecimal(oldReplaceMeterDto.getNewBegin()).setScale(0,BigDecimal.ROUND_DOWN);//换表中的新表起度
-                                BigDecimal newMeterUse = readingNew.subtract(replaceNewDate);//新表用量
-                                Amount = Amount.add(newMeterUse);
-                            }
-                        }
+                    if(replaceRecordMap.containsKey(amountWaterUsedAmountDto.getMetercode())){
+                        DeviceReplaceRecord deviceReplaceRecord = replaceRecordMap.get(amountWaterUsedAmountDto.getMetercode());
+
+                        replaceAmount=deviceReplaceRecord.getOldAmount();
+
+                    }
+
+
+                    //实际水量=本期水量+换表前水量
+                     Amount = readingNew.subtract(readingOld).add(replaceAmount);
 
-                        if(!replace){
-                            if (readingNew.compareTo(tempReading) > 0)
-                                Amount = Amount.add(readingNew.subtract(tempReading));
-                        }
 
                         //计量方式判断
                         if (calculateway.equals(1))//按实际用量
@@ -238,17 +237,13 @@ public class AmountSynServiceImpl implements AmountSynService {
                         if (payAmount.compareTo(BigDecimal.ZERO) < 0) {
                             continue;
                         }
-
                         amountWaterUsedAmountDto.setReading(readingNew);
                         amountWaterUsedAmountDto.setRecorddate(DateTimeUtil.parseDate(readDate, DateTimeUtil.DATE_TIME_FORMAT_SECOND));
                         amountWaterUsedAmountDto.setAmount(Amount);
                         amountWaterUsedAmountDto.setPayamount(payAmount);
-
                         updates.add(amountWaterUsedAmountDto);
-
                     }
                 }
-
             }
             if (updates.size() > 0) {
                 //List<List<AmountWaterUsedAmountDto>> lists = Lists.partition(updates, 500);
@@ -256,10 +251,6 @@ public class AmountSynServiceImpl implements AmountSynService {
                     amountWaterUsedAmountMapper.batchUpdate(amountWaterUsedAmount);
                 }
             }
-        }
-
-
         log.info("水量同步结束:" + LocalDateTime.now());
-
-    }
+        }
 }

+ 14 - 23
smart-city-platform/src/main/resources/mapper/pay/AmountWaterUsedAmountMapper.xml

@@ -332,7 +332,7 @@
 		) SELECT
 		c.id,
 		c.office_id,
-		ifnull( lastwua.reading, ifnull(sil.new_meter_start,0) ),
+		ifnull( lastwua.reading, ifnull(device.new_meter_start,0) ),
 		ifnull( lastwua.recorddate, c.create_date ),
 		c.metercode,
 		c.watermeter_id,
@@ -354,7 +354,7 @@
 		NULL
 		FROM
 		pay_base_customerandmeterrela c
-		LEFT JOIN sc_install_list sil ON sil.device_id = c.watermeter_id
+		LEFT JOIN sc_device device ON device.id = c.watermeter_id
 		LEFT JOIN pay_amount_waterusedamount_day amount ON amount.watermeter_id = c.watermeter_id
 		AND amount.read_date = DATE_FORMAT( DATE_SUB( now(), INTERVAL 1 DAY ), '%Y%m%d' )
 		LEFT JOIN (
@@ -423,6 +423,7 @@
 		rela.calculateway,
 		rela.fixedamount,
 		amount.watermeter_id watermeterId,
+		amount.metercode,
 		amount.recorddate,
 		rela.id customerandmeterrelaId,
 		amount.waterproperty_id waterpropertyId,
@@ -669,30 +670,20 @@
 		and a.`year`=#{year} and a.`month`=#{month}
 	</select>
 
-	<resultMap id="ReplaceMeterCountMap" type="com.bz.smart_city.dto.pay.ReplaceMeterCountDto">
+	<resultMap id="ReplaceMeterCountMap" type="com.bz.smart_city.entity.pay.DeviceReplaceRecord">
 
 	</resultMap>
 	<select id="getRepalceRecordCount" resultMap="ReplaceMeterCountMap">
-		SELECT
-		COUNT(*) as number,
-		pc.device_id AS deviceId
-		FROM sc_water_meter_replace_log pc LEFT JOIN sc_device scd on pc.device_id = scd.id
-		<where>
-			<if test="stTime != null"> and pc.date_create >= #{stTime,jdbcType=TIMESTAMP}</if>
-			<if test="etTime != null"> and pc.date_create &lt;= #{etTime,jdbcType=TIMESTAMP}</if>
-			<if test="siteId != null"> and scd.site_id = #{siteId}</if>
-			<if test="customerId != null"> and scd.customer_id = #{customerId}</if>
-			<if test="list != null and list.size() != 0">
-				and pc.device_id IN
-				<foreach collection="list" item="listItem" open="(" close=")" separator=",">
-					<if test="listItem != null and listItem != ''">
-						#{listItem}
-					</if>
-				</foreach>
-			</if>
-
-		</where>
-		GROUP BY pc.device_id
+		select
+			id
+			,watermeter_id as "watermeterId"
+			,metercode
+			,create_date as "createDate"
+			,old_lastreading as "oldLastreading"
+			,old_reading as "oldReading"
+			,old_amount as "oldAmount"
+		from pay_device_replace_record
+		where site_id=#{siteId} and customer_id=#{customerId} and year=#{year} and month =#{month}
 	</select>