package com.jisco.dynamicweight.dynamicworkupdata.service.impl;

import cn.hutool.core.lang.Assert;
import com.jisco.dynamicweight.dtcrb.mapper.DtcrbMapper;
import com.jisco.dynamicweight.dynamicbasebatchstation.mapper.DynamicBaseBatchStationMapper;
import com.jisco.dynamicweight.dynamicbasebatchstation.model.DynamicBaseBatchStation;
import com.jisco.dynamicweight.dynamicbasereciever.model.DynamicBaseReciever;
import com.jisco.dynamicweight.dynamicworkdata.model.DynamicWorkData;
import com.jisco.dynamicweight.dynamicworkdata.service.IDynamicWorkDataService;
import com.jisco.dynamicweight.dynamicworkupdata.dto.CalNewCokeDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.CokeComputeDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.InbatchDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.ReturnedDustDto;
import com.jisco.dynamicweight.dynamicworkupdata.mapper.DynamicWorkUpdataMapper;
import com.jisco.dynamicweight.dynamicworkupdata.model.DynamicWorkUpdata;
import com.jisco.dynamicweight.dynamicworkupdata.service.IDynamicWorkUpdataService;
import com.jisco.dynamicweight.dynamicworkupdata.vo.AuditDataVO;
import com.jisco.dynamicweight.dynamicworkupdata.vo.DailyReportVO;
import com.jisco.dynamicweight.util.UserUtil;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
import com.steerinfo.baseinfo.combaseinfo.service.IComBaseInfoService;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.meterwork.meterworkcaractual.service.IMeterWorkCarActualService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * DynamicWorkUpdata服务实现：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2022-01-18 10:14
 * 类描述
 * 修订历史：
 * 日期：2022-01-18
 * 作者：generator
 * 参考：
 * 描述：DynamicWorkUpdata服务实现
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@Service(value = "dynamicWorkUpdataService")
public class DynamicWorkUpdataServiceImpl extends BaseServiceImpl<DynamicWorkUpdata, String> implements IDynamicWorkUpdataService {

    @Autowired
    private DynamicWorkUpdataMapper dynamicWorkUpdataMapper;

    @Autowired
    private IDynamicWorkDataService dynamicWorkDataService;

    @Autowired
    private DtcrbMapper dtcrbMapper;

    @Autowired
    private IComBaseInfoService comBaseInfoService;

    @Autowired
    IMeterWorkCarActualService meterWorkCarActualService;

    @Override
    protected IBaseMapper<DynamicWorkUpdata, String> getMapper() {
        return dynamicWorkUpdataMapper;
    }

    /**
     * 重新获取动态秤称重数据
     */
    @Override
    public void recalc() {
        dynamicWorkUpdataMapper.recalc();
    }

    /**
     * 数据分批总重量
     *
     * @param updataNo
     * @return
     */
    @Override
    public BigDecimal inbatchsTotalWeight(String updataNo, Date startTime, Date endTime) {
        DynamicWorkUpdata byId = this.getById(updataNo);
        Assert.notNull(byId, "记录不存在");
        Assert.notNull(byId.getStationCode(), "记录站点编码为空，无法计算分批总重量");
//        Assert.notNull(byId.getMaterialCode(), "记录物料编码为空，无法计算分批总重量");
//        Assert.notNull(byId.getEndTime(), "记录结束时间为空，无法计算分批总重量");
//        Assert.notNull(byId.getStationCode(), "记录所属站点为空，无法计算分批总重量");
        BigDecimal weight = dynamicWorkUpdataMapper.inbatchsTotalWeight(byId.getStationCode(), byId.getMaterialName(), startTime, endTime);
        return weight;
    }

    /**
     * 返粉总重量
     *
     * @param updataNo
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public BigDecimal returnedDustWeight(String updataNo, Date startTime, Date endTime) {
        DynamicWorkUpdata updata = this.getById(updataNo);
        Assert.notNull(updata, "记录不存在：" + updataNo);
        //检查所选记录的物料、站点、收货库房是否是配置表中配置的需要返粉的物料、站点、收货库房
        //物料
        List<String> materialCodes = getMaterialCodeForReturnedDust();
        Assert.isTrue(materialCodes.contains(updata.getMaterialCode()), updata.getMaterialName() + "不能进行返粉");
        //站点
        List<String> stationCodes = getStationCodesForReturnedDust();
        Assert.isTrue(stationCodes.contains(updata.getStationCode()), updata.getStationName() + "不能进行返粉");
        //收货库房
        List<String> receiverCodes = getReceiverCodesReturnedDust();
        Assert.isTrue(receiverCodes.contains(updata.getRecieverCode()), updata.getRecieverName() + "不能进行返粉");
        Map<String, Object> map = new HashMap<>();
        map.put("meterialCode", updata.getMaterialCode());
        map.put("stationCodes", stationCodes);
        map.put("receiverCodes", receiverCodes);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        BigDecimal weight = dynamicWorkUpdataMapper.returnedDustWeight(map);
        Assert.isTrue(weight != null && weight.compareTo(BigDecimal.ZERO) != 0, "未获取到重量！");
        return weight;
    }

    private List<String> getReceiverCodesReturnedDust() {
        Map param = new HashedMap();
        param.put("pBaseCode", "001050003");
        List<ComBaseInfo> infos = comBaseInfoService.query(param);
        Assert.isTrue(!CollectionUtils.isEmpty(infos), "未配置返粉收货库房，请检查配置表");
        List<String> receiverCodes = infos.stream().map(item -> item.getMemo()).collect(Collectors.toList());
        return receiverCodes;
    }

    private List<String> getStationCodesForReturnedDust() {
        Map param = new HashedMap();
        param.put("pBaseCode", "001050002");
        List<ComBaseInfo> infos = comBaseInfoService.query(param);
        Assert.isTrue(!CollectionUtils.isEmpty(infos), "未配置返粉站点，请检查配置表");
        List<String> stationCodes = infos.stream().map(item -> item.getMemo()).collect(Collectors.toList());
        return stationCodes;
    }

    private List<String> getMaterialCodeForReturnedDust() {
        Map param = new HashedMap();
        param.put("pBaseCode", "001050001");
        List<ComBaseInfo> infos = comBaseInfoService.query(param);
        Assert.isTrue(!CollectionUtils.isEmpty(infos), "未配置返粉物料，请检查配置表");
        List<String> materialCodes = infos.stream().map(item -> item.getMemo()).collect(Collectors.toList());
        return materialCodes;
    }

    /**
     * 返粉
     *
     * @param updataNo
     * @param startTime
     * @param endTime
     * @param list
     */
    @Transactional
    @Override
    public void returnedDust(String updataNo, Date startTime, Date endTime, List<ReturnedDustDto> list) {
        //计算返粉总重量，与计算返粉总重量方法代码相同，但是这里需要物料、站点、收货库房信息，为了减少查询数据库次数，这里又复制了一份代码
        DynamicWorkUpdata updata = this.getById(updataNo);
        Assert.notNull(updata, "记录不存在：" + updataNo);
        //检查所选记录的物料、站点、收货库房是否是配置表中配置的需要返粉的物料、站点、收货库房
        //物料
        List<String> materialCodes = getMaterialCodeForReturnedDust();
        Assert.isTrue(materialCodes.contains(updata.getMaterialCode()), updata.getMaterialName() + "不能进行返粉");
        //站点
        List<String> stationCodes = getStationCodesForReturnedDust();
        Assert.isTrue(stationCodes.contains(updata.getStationCode()), updata.getStationName() + "不能进行返粉");
        //收货库房
        List<String> receiverCodes = getReceiverCodesReturnedDust();
        Assert.isTrue(receiverCodes.contains(updata.getRecieverCode()), updata.getRecieverName() + "不能进行返粉");
        Map<String, Object> map = new HashMap<>();
        map.put("meterialCode", updata.getMaterialCode());
        map.put("stationCodes", stationCodes);
        map.put("receiverCodes", receiverCodes);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        BigDecimal weight = dynamicWorkUpdataMapper.returnedDustWeight(map);
        Assert.isTrue(weight != null && weight.compareTo(BigDecimal.ZERO) != 0, "未获取到重量！");
        BigDecimal total = BigDecimal.ZERO;
        List<DynamicWorkUpdata> newUpdatas = new ArrayList<>();
        for (ReturnedDustDto returnedDustDto : list) {
            DynamicWorkUpdata data = new DynamicWorkUpdata();
            data.setId(null);
            data.setUpdataNo(null);
            data.setMaterialCode(updata.getMaterialCode());
            data.setMaterialName(updata.getMaterialName());
            data.setStationCode(returnedDustDto.getStationCode());
            data.setStationName(returnedDustDto.getStationName());
            data.setRecieverCode(returnedDustDto.getRecieverCode());
            data.setRecieverName(returnedDustDto.getRecieverName());
            data.setRecieverType(returnedDustDto.getRecieverType());
            data.setSenderCode(updata.getSenderCode());
            data.setSenderName(updata.getSenderName());
            data.setSenderType(updata.getSenderType());
            data.setWeight(returnedDustDto.getWeight());
            data.setStartTime(startTime);
            data.setEndTime(endTime);
            data.setCreateManNo(UserUtil.getCurrentUserId());
            data.setCreateManName(UserUtil.getCurrentUserName());
            data.setCreateTime(new Date());
            data.setUpdateManNo(null);
            data.setUpdateManName(null);
            data.setUpdateTime(null);
            newUpdatas.add(data);
            total = total.add(data.getWeight());
        }
//        Assert.isTrue(weight.compareTo(total) == 0, "返粉重量之和与总重量不相等！");
        Assert.isTrue(weight.subtract(total).abs().compareTo(new BigDecimal(1)) < 0, "返粉重量之和与总重量不相等！");
        dynamicWorkUpdataMapper.disableForReturnedDust(map);
        this.batchAdd(newUpdatas);
    }

    @Transactional
    @Override
    public void inbatchs(String updataNo, Date startTime, Date endTime, List<InbatchDto> list) {
        BigDecimal weight = this.inbatchsTotalWeight(updataNo, startTime, endTime);
        Assert.isTrue(weight.compareTo(new BigDecimal(0)) > 0, "重量为0,不能进行分批!");
        DynamicWorkUpdata updata = this.getById(updataNo);
        BigDecimal total = new BigDecimal(0);
        List<DynamicWorkUpdata> updataList = new ArrayList<>();
        for (InbatchDto inbatchDto : list) {
            DynamicWorkUpdata data = new DynamicWorkUpdata();
            data.setId(null);
            data.setUpdataNo(null);
            data.setStationCode(updata.getStationCode());
            data.setStationName(updata.getStationName());
            data.setMaterialCode(inbatchDto.getMaterialCode());
            data.setMaterialName(inbatchDto.getMaterialName());
            data.setRecieverCode(updata.getRecieverCode());
            data.setRecieverName(updata.getRecieverName());
            data.setRecieverType(updata.getRecieverType());
            data.setSenderCode(updata.getSenderCode());
            data.setSenderName(updata.getSenderName());
            data.setSenderType(updata.getSenderType());
            data.setWeight(inbatchDto.getWeight());
            data.setStartTime(startTime);
            data.setEndTime(endTime);
            data.setCreateManNo(UserUtil.getCurrentUserId());
            data.setCreateManName(UserUtil.getCurrentUserName());
            data.setCreateTime(new Date());
            updataList.add(data);
            total = total.add(data.getWeight());
        }
        Assert.isTrue(weight.compareTo(total) == 0, "分批重量之和与总重量不相等！");
        int batchAdd = this.batchAdd(updataList);
        Assert.isTrue(list.size() == batchAdd, "保存分批数据失败");
        // 作废原数据
        dynamicWorkUpdataMapper.batchDisable(updata.getStationCode(), updata.getMaterialName(), startTime, endTime, UserUtil.getCurrentUserId(), UserUtil.getCurrentUserName(), new Date());
    }

    /**
     * 重新计算焦炭量
     */
    @Transactional
    @Override
    public void recalcCoke(@RequestBody CokeComputeDto model) {
        Assert.notNull(model.getDate(), "日期不能为空");
        Assert.notNull(model.getK(), "系数不能为空");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("endTime1", sdf.format(model.getDate()) + " 00:00:00");
        params.put("endTime2", sdf.format(model.getDate()) + " 23:59:59");
        params.put("isCoke", "1");
        List<DynamicWorkUpdata> updatas = this.dynamicWorkUpdataMapper.selectLikeByParameters(params);
        BigDecimal k = model.getK();
        for (DynamicWorkUpdata updata : updatas) {
            updata.setWeight(updata.getWeight().multiply(k).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        dynamicWorkUpdataMapper.batchUpdate(updatas);
    }

    @Override
    public List<DailyReportVO> dailyReport(String date) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime bl8start = null;
        LocalDateTime bl8end = null;
        LocalDateTime bl16start = null;
        LocalDateTime bl16end = null;
        LocalDateTime bl24start = null;
        LocalDateTime bl24end = null;
        LocalDateTime rzlstart = null;
        LocalDateTime rzlend = null;
        LocalDateTime yzlstart = null;
        LocalDateTime yzlend = null;
        LocalDateTime nzlstart = null;
        LocalDateTime nzlend = null;
        bl8start = LocalDateTime.parse(date + " 00:00:00", df);
        bl8end = LocalDateTime.parse(date + " 07:59:59", df);
        bl16start = LocalDateTime.parse(date + " 08:00:00", df);
        bl16end = LocalDateTime.parse(date + " 15:59:59", df);
        bl24start = LocalDateTime.parse(date + " 16:00:00", df);
        bl24end = LocalDateTime.parse(date + " 23:59:59", df);
        rzlstart = LocalDateTime.parse(date + " 00:00:00", df);
        rzlend = LocalDateTime.parse(date + " 23:59:59", df);
        yzlstart = LocalDateTime.parse(date + " 00:00:00", df);
        if (yzlstart.plusMonths(1).withDayOfMonth(1).minusDays(3).isAfter(yzlstart)) {
            yzlstart = yzlstart.withDayOfMonth(1).minusDays(3);
        } else {
            yzlstart = yzlstart.plusMonths(1).withDayOfMonth(1).minusDays(3);
        }
        yzlend = LocalDateTime.parse(date + " 23:59:59", df);
//        yzlend = yzlend.plusMonths(1).withDayOfMonth(1).minusDays(3);
        nzlstart = LocalDateTime.parse(date + " 00:00:00", df);
        nzlstart = nzlstart.withMonth(1).withDayOfMonth(1);
        nzlend = LocalDateTime.parse(date + " 23:59:59", df);
        List<DailyReportVO> dailyReportVOS = dynamicWorkUpdataMapper.dailyReport(bl8start, bl8end, bl16start, bl16end, bl24start, bl24end, rzlstart, rzlend, yzlstart, yzlend, nzlstart, nzlend);
        return dailyReportVOS;
    }

    /**
     * 查询待审核数据
     *
     * @param date
     * @return
     */
    @Override
    public List<AuditDataVO> getAuditData(String date) {
        String bl8start = null;
        String bl8end = null;
        String bl16start = null;
        String bl16end = null;
        String bl24start = null;
        String bl24end = null;
        bl8start = date + " 00:00:00";
        bl8end = date + " 07:59:59";
        bl16start = date + " 08:00:00";
        bl16end = date + " 15:59:59";
        bl24start = date + " 16:00:00";
        bl24end = date + " 23:59:59";
        List<AuditDataVO> auditDataVOS = dynamicWorkUpdataMapper.getAuditData(bl8start, bl8end, bl16start, bl16end, bl24start, bl24end);
        for (AuditDataVO auditDataVO : auditDataVOS) {
            if (Objects.isNull(auditDataVO.getBl8())) {
                auditDataVO.setBl8(BigDecimal.ZERO);
            }
            if (Objects.isNull(auditDataVO.getBl16())) {
                auditDataVO.setBl16(BigDecimal.ZERO);
            }
            if (Objects.isNull(auditDataVO.getBl24())) {
                auditDataVO.setBl24(BigDecimal.ZERO);
            }
            auditDataVO.setRzl(auditDataVO.getBl8().add(auditDataVO.getBl16()).add(auditDataVO.getBl24()));
        }
        return auditDataVOS;
    }

    /**
     * 启用
     *
     * @param id
     * @return
     */
    @Override
    public boolean enable(String id) {
        DynamicWorkUpdata byId = this.getById(id);
        Assert.notNull(byId, "记录不存在");
        if (byId.getValidFlag().equals("1")) return false;
        DynamicWorkUpdata config = new DynamicWorkUpdata();
        config.setUpdataNo(id);
        setUpdateManInfo(config);
        return dynamicWorkUpdataMapper.enable(config) == 1;
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public boolean disable(String id) {
        DynamicWorkUpdata byId = this.getById(id);
        if (byId.getValidFlag() == "0") return false;
        DynamicWorkUpdata config = new DynamicWorkUpdata();
        config.setUpdataNo(id);
        setUpdateManInfo(config);
        return dynamicWorkUpdataMapper.disable(config) == 1;
    }

    private void setUpdateManInfo(DynamicWorkUpdata config) {
        config.setUpdateManNo(UserUtil.getCurrentUserId());
        config.setUpdateManName(UserUtil.getCurrentUserName());
        config.setUpdateTime(new Date());
    }

    /**
     * 重新生成数据,删除上传数据表中的数据，并修改采集数据表中的过期标识expire_flag为0，重新生成上传数据表的数据
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public void reGenerate(String id) {
        DynamicWorkUpdata byId = this.getById(id);
        Assert.notNull(byId, "记录不存在");
        Assert.isTrue(StringUtils.isNotBlank(byId.getOriginalValue()), "人工添加数据无法重新生成");
        this.delete(id);
        DynamicWorkData dynamicWorkData = new DynamicWorkData();
        dynamicWorkData.setDataNo(byId.getOriginalValue());
        dynamicWorkData.setExpireFlag("0");
        dynamicWorkDataService.modify(dynamicWorkData);
    }

    /**
     * 重新采集数据,删除上传数据表中的数据和采集数据表中的数据，重新采集数据
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public void reCollect(String id) {
        DynamicWorkUpdata byId = this.getById(id);
        Assert.notNull(byId, "记录不存在");
        Assert.isTrue(StringUtils.isNotBlank(byId.getOriginalValue()), "人工添加数据无法重新生成");
        this.delete(id);
        dynamicWorkDataService.delete(byId.getOriginalValue());
    }

    /**
     * 新焦炭计算
     *
     * @param calNewCokeDto
     */
    @Transactional
    @Override
    public synchronized void calNewCoke(CalNewCokeDto calNewCokeDto) {
        Assert.notNull(calNewCokeDto, "参数不能为空");
        Assert.notNull(calNewCokeDto.getStartTime(), "开始时间不能为空");
        Assert.notNull(calNewCokeDto.getEndTime(), "结束时间不能为空");
        Assert.isTrue(!CollectionUtils.isEmpty(calNewCokeDto.getStationNums()), "3-6#高炉料斗秤列表不能为空");
        //必须先计算3-6炉，再计算7炉，因为计算7炉时会修改料斗秤编号列表
        calNewCoke3_6(calNewCokeDto);
        // 计算7炉新焦炭
        calNewCoke7(calNewCokeDto);
    }

    private void calNewCoke7(CalNewCokeDto calNewCokeDto) {
        //        二、7#高炉焦炭结算
//        1、统计“动态秤称重数据维护”内，综1A、综1B、综1C、综1D皮带秤，物料品名包含“焦”，收货库房为“2546”的数据，并求和；假设结果为A，并作废原始数据
        calNewCokeDto.setReceiverCode("2546");
        BigDecimal a = dynamicWorkUpdataMapper.getTotalCoke(calNewCokeDto);
//        2、查询“动态秤日报”内返焦4皮带总量；假设结果为B
        calNewCokeDto.setStationNums(Arrays.asList("001336"));
        BigDecimal b = dtcrbMapper.getTotalWeight(calNewCokeDto);
//        3、统计“物资量系统”内，汽车衡，物料品名包含“焦”，发货库房为“2548”的数据；并求和；假设结果为C
        calNewCokeDto.setReceiverCode(null);
        calNewCokeDto.setSenderCode("2548");
        BigDecimal c = getTotalCokeOfCar(calNewCokeDto);
//        4、统计“动态称日报”内，7#高炉14-19#料斗秤数据，并求和；假设结果为D
        calNewCokeDto.setStationNums(Arrays.asList("002063", "002064", "002065", "002066", "002067", "002068"));
        BigDecimal d = dtcrbMapper.getTotalWeight(calNewCokeDto);
//        5、统计“动态称日报”内，煤焦E皮带秤，物料品名包含“焦”的数据（不包含粉焦），并求和；假设结果为E，并作废原始数据
        List<String> stationNums = dtcrbMapper.getMJEStationNums();
        calNewCokeDto.setStationNums(stationNums);
        BigDecimal e = dtcrbMapper.getTotalWeight(calNewCokeDto);
//        6、计算系数K=（C+D+B）/ (A+E)
        if (a == null || b == null || c == null || d == null || e == null || a.add(e).compareTo(BigDecimal.ZERO) == 0)
            return;
        BigDecimal k = c.add(d).add(b).divide(a.add(e), 5, RoundingMode.HALF_UP);
//        7、分别用“动态秤称重数据维护”内，综1A、综1B、综1C、综1D皮带秤，物料品名包含“焦”，收货库房为“2546”的数据，和煤焦E皮带秤，物料品名包含“焦”的数据乘以计算系数K，并将结果汇总存放“动态称数据审核”
        calNewCokeDto.setReceiverCode("2546");
        List<DynamicWorkUpdata> dynamicWorkUpdataList = dynamicWorkUpdataMapper.getCokeRecords(calNewCokeDto);
        //插入乘完k系统的新数据
        saveNewCoke(dynamicWorkUpdataList, k);
        // 作废原始数据
        int i = dynamicWorkUpdataMapper.batchDisableByIds(dynamicWorkUpdataList.stream().map(item -> item.getUpdataNo()).collect(Collectors.toList()));
        Assert.isTrue(i == dynamicWorkUpdataList.size(), "作废原数据失败");
    }

    private void calNewCoke3_6(CalNewCokeDto calNewCokeDto) {
        //        一、3#-6#高炉焦炭结算
//        1、统计“动态秤称重数据维护”内，综1A、综1B、综1C、综1D皮带秤，物料品名包含“焦”，收货库房为“2531”的数据，并求和；假设结果为A，并作废原始数据
        calNewCokeDto.setReceiverCode("2531");
        BigDecimal a = dynamicWorkUpdataMapper.getTotalCoke(calNewCokeDto);
//        2、统计“物资量系统”内，汽车衡，物料品名包含“焦”，收货库房为“2531”的数据；并求和；假设结果为B
        BigDecimal b = getTotalCokeOfCar(calNewCokeDto);
//        3、统计“物资量系统”内，汽车衡，物料品名包含“焦”，发货库房为“2533”的数据；并求和；假设结果为C
        calNewCokeDto.setReceiverCode(null);
        calNewCokeDto.setSenderCode("2533");
        BigDecimal c = getTotalCokeOfCar(calNewCokeDto);
//        4、统计“动态称日报”内，3#、4#、5#、6#高炉焦炭料斗秤（因3#料斗秤上料经常变料，故每座高炉的1#、2#、3#料斗秤应设置可勾选界面，由岗位根据权限可进行是否为焦炭勾选）、焦丁皮带秤数据，并求和；假设结果为D
        BigDecimal d = dtcrbMapper.getTotalWeight(calNewCokeDto);
//        5、统计“动态秤称重数据维护”内，36B1计量焦炭数据（不包含粉焦），并求和；假设结果为E，并作废原始数据
        BigDecimal e = getCokeByStation("PD0039", calNewCokeDto.getStartTime(), calNewCokeDto.getEndTime());
//        6、计算系数K=（C+D-E-B）/ A
        if (a == null || b == null || c == null || d == null || e == null || a.compareTo(BigDecimal.ZERO) == 0)
            return;
        BigDecimal k = c.add(d).subtract(b).subtract(e).divide(a, 5, RoundingMode.HALF_UP);
//        7、用“动态秤称重数据维护”内，综1A、综1B、综1C、综1D皮带秤，物料品名包含“焦”，收货库房为“2531”的数据，每条数据乘以系数K，并将结果汇总存放“动态称数据审核”
        calNewCokeDto.setReceiverCode("2531");
        List<DynamicWorkUpdata> dynamicWorkUpdataList = dynamicWorkUpdataMapper.getCokeRecords(calNewCokeDto);
        //插入乘完k系统的新数据
        saveNewCoke(dynamicWorkUpdataList, k);
        // 作废原始数据
        int i = dynamicWorkUpdataMapper.batchDisableByIds(dynamicWorkUpdataList.stream().map(item -> item.getUpdataNo()).collect(Collectors.toList()));
        Assert.isTrue(i == dynamicWorkUpdataList.size(), "作废原数据失败");
    }

    private void saveNewCoke(List<DynamicWorkUpdata> dynamicWorkUpdataList, BigDecimal k) {
        List<DynamicWorkUpdata> list = new ArrayList<>();
        for (DynamicWorkUpdata dynamicWorkUpdata : dynamicWorkUpdataList) {
            DynamicWorkUpdata data = new DynamicWorkUpdata();
            data.setUpdataNo(null);
            data.setMaterialName(dynamicWorkUpdata.getMaterialName());
            data.setMaterialCode(dynamicWorkUpdata.getMaterialCode());
            data.setStationName(dynamicWorkUpdata.getStationName());
            data.setStationCode(dynamicWorkUpdata.getStationCode());
            data.setRecieverName(dynamicWorkUpdata.getRecieverName());
            data.setRecieverCode(dynamicWorkUpdata.getRecieverCode());
            data.setRecieverType(dynamicWorkUpdata.getRecieverType());
            data.setSenderName(dynamicWorkUpdata.getSenderName());
            data.setSenderCode(dynamicWorkUpdata.getSenderCode());
            data.setSenderType(dynamicWorkUpdata.getSenderType());
            data.setWeight(dynamicWorkUpdata.getWeight().multiply(k));
            data.setUploaded(null);
            data.setStartTime(dynamicWorkUpdata.getStartTime());
            data.setEndTime(dynamicWorkUpdata.getEndTime());
            data.setMemo(null);
            data.setAuditingManNo(null);
            data.setAuditingManName(null);
            data.setAuditingTime(null);
            data.setAuditingFlag("0");
            data.setOriginalValue(null);
            data.setSyslog(null);
            data.setValidFlag("1");
            data.setCreateManNo(UserUtil.getCurrentUserId());
            data.setCreateManName(UserUtil.getCurrentUserName());
            data.setCreateTime(new Date());
            data.setUpdateManNo(null);
            data.setUpdateManName(null);
            data.setUpdateTime(null);
            list.add(data);
        }
        int batchAdd = this.batchAdd(list);
        Assert.isTrue(batchAdd == dynamicWorkUpdataList.size(), "插入新焦炭数据失败");
    }

    private BigDecimal getCokeByStation(String stationCode, Date startTime, Date endTime) {
        return dynamicWorkUpdataMapper.getCokeByStation(stationCode, startTime, endTime);
    }

    private BigDecimal getTotalCokeOfCar(CalNewCokeDto calNewCokeDto) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, Object> params = new HashMap<>();
        params.put("startTime", sdf.format(calNewCokeDto.getStartTime()));
        params.put("endTime", sdf.format(calNewCokeDto.getEndTime()));
        params.put("matterName", "焦");
        params.put("validFlag", "1");
        if (calNewCokeDto.getReceiverCode() != null) {
            params.put("receivingUintNo", calNewCokeDto.getReceiverCode());
        } else if (calNewCokeDto.getSenderCode() != null) {
            params.put("forwardingUnitNo", calNewCokeDto.getSenderCode());
        } else {
            throw new RuntimeException("必须选择发货库房或者收货库房");
        }
        BigDecimal b = BigDecimal.ZERO;
        PageList<MeterWorkCarActual> meterWorkCarActualPageList = meterWorkCarActualService.likeByDesc(params, 1, 2000);
        List<MeterWorkCarActual> meterWorkCarActuals = meterWorkCarActualPageList.getList();
        for (MeterWorkCarActual meterWorkCarActual : meterWorkCarActuals) {
            b = b.add(meterWorkCarActual.getNetWeight());
        }
        return b.divide(new BigDecimal(1000));
    }
}
