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

import cn.hutool.core.lang.Assert;
import com.jisco.dynamicweight.dynamicbasebatchstation.mapper.DynamicBaseBatchStationMapper;
import com.jisco.dynamicweight.dynamicbasebatchstation.model.DynamicBaseBatchStation;
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.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
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 java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

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

    @Autowired
    private DynamicWorkUpdataMapper dynamicWorkUpdataMapper;

    @Autowired
    private DynamicBaseBatchStationMapper stationMapper;

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

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

    /**
     * 数据分批总重量
     * @param stationCode
     * @return
     */
    @Override
    public BigDecimal inbatchsTotalWeight(String stationCode, Date date) {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        Map<String, Object> params = new HashMap<>();
        params.put("pikaCode", stationCode);
        List<DynamicBaseBatchStation> stations = stationMapper.selectByParameters(params);
        Assert.isTrue(!CollectionUtils.isEmpty(stations), "站点不存在：" + stationCode);
        Assert.isTrue(stations.size() == 1, "站点存在多条记录：" + stationCode);
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = sdf.parse(sdf.format(date));
            date1.setHours(0);
            date1.setMinutes(0);
            date1.setSeconds(0);
            date2 = sdf.parse(sdf.format(date));
            date2.setHours(23);
            date2.setMinutes(59);
            date2.setSeconds(59);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式转换错误");
        }
        BigDecimal weight = dynamicWorkUpdataMapper.inbatchsTotalWeight(stationCode, date1, date2);
        return weight;
    }

    /**
     * 返粉总重量
     * @param id
     * @return
     */
    @Override
    public BigDecimal returnedDustWeight(String id) {
        DynamicWorkUpdata updata = this.getById(id);
        Assert.notNull(updata, "记录不存在：" + id);
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = sdf.parse(sdf.format(updata.getEndTime()));
            date1.setHours(0);
            date1.setMinutes(0);
            date1.setSeconds(0);
            date2 = sdf.parse(sdf.format(updata.getEndTime()));
            date2.setHours(23);
            date2.setMinutes(59);
            date2.setSeconds(59);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式转换错误");
        }
        BigDecimal weight = null;
        Map<String, Object> map = new HashMap<>();
//        if (updata.getMaterialCode() == null) {
//            updata.setMaterialCode("123123");
//        }
        map.put("meterialCode", updata.getMaterialCode());
        map.put("date1", date1);
        map.put("date2", date2);
        map.put("weight", weight);
        dynamicWorkUpdataMapper.returnedDustWeight(map);
        if (map.get("weight") == null) {
            map.put("weight", new BigDecimal(0));
//            weight = new BigDecimal(0);
        }
        Assert.isTrue(map.get("weight") !=null,"未获取到重量！");
        weight = new BigDecimal(map.get("weight").toString());
        return weight;
    }

    /**
     * 返粉
     * @param id
     * @param list
     */
    @Transactional
    @Override
    public void returnedDust(String id, List<ReturnedDustDto> list) {
        DynamicWorkUpdata updata = this.getById(id);
        Assert.isTrue( updata !=null && updata.getIsReturnedDust()!=null && updata.getIsReturnedDust().compareTo(new BigDecimal(1))==0, updata.getMaterialName() + "不能进行返粉！");
        BigDecimal weight = this.returnedDustWeight(id);
        Assert.isTrue(weight.compareTo(new BigDecimal(0)) > 0, updata.getStationName() + "重量为0,不能进行返粉!");
        BigDecimal total = new BigDecimal(0);
        for (ReturnedDustDto returnedDustDto : list) {
            DynamicWorkUpdata data = new DynamicWorkUpdata();
            BeanUtils.copyProperties(updata, data);
            data.setId(null);
            data.setUpdataNo(null);
            data.setMaterialCode(returnedDustDto.getMaterialCode());
            data.setMaterialName(returnedDustDto.getMaterialName());
            data.setStationCode(returnedDustDto.getStationCode());
            data.setStationName(returnedDustDto.getStationName());
            data.setRecieverCode(returnedDustDto.getRecieverCode());
            data.setRecieverName(returnedDustDto.getRecieverName());
            data.setWeight(returnedDustDto.getWeight());
            data.setCreateManNo(UserUtil.getCurrentUserId());
            data.setCreateManName(UserUtil.getCurrentUserName());
            data.setCreateTime(new Date());
            data.setUpdateManNo(null);
            data.setUpdateManName(null);
            data.setUpdateTime(null);
            this.add(data);
            total = total.add(data.getWeight());
        }
        Assert.isTrue(weight.compareTo(total) == 0, "返粉重量之和与总重量不相等！");
    }

    @Transactional
    @Override
    public void inbatchs(String id, List<InbatchDto> list) {
        DynamicWorkUpdata updata = this.getById(id);
        Assert.isTrue(updata.getIsInbatches().compareTo(new BigDecimal(1))==0, updata.getStationName() + "不能进行分批！");
        BigDecimal weight = this.inbatchsTotalWeight(updata.getStationCode(), updata.getEndTime());
        Assert.isTrue(weight.compareTo(new BigDecimal(0)) > 0, updata.getStationName() + "重量为0,不能进行分批!");
        BigDecimal total = new BigDecimal(0);
        for (InbatchDto inbatchDto : list) {
            DynamicWorkUpdata data = new DynamicWorkUpdata();
            BeanUtils.copyProperties(updata, data);
            data.setId(null);
            data.setUpdataNo(null);
            data.setMaterialCode(inbatchDto.getMaterialCode());
            data.setMaterialName(inbatchDto.getMaterialName());
            data.setWeight(inbatchDto.getWeight());
            data.setCreateManNo(UserUtil.getCurrentUserId());
            data.setCreateManName(UserUtil.getCurrentUserName());
            data.setCreateTime(new Date());
            this.add(data);
            total = total.add(data.getWeight());
        }
        Assert.isTrue(weight.compareTo(total) == 0, "分批重量之和与总重量不相等！");
    }

    /**
     * 重新计算焦炭量
     * @param k
     * @param list
     */
    @Transactional
    @Override
    public void recalcCoke(BigDecimal k, List<DynamicWorkUpdata> list) {
        for (DynamicWorkUpdata updata : list) {
            Assert.isTrue(updata.getIsCoke().compareTo(new BigDecimal(1))==0, updata.getMaterialName() + "不是焦炭，不能计算");
            updata.setWeight(updata.getWeight().multiply(k));
            dynamicWorkUpdataMapper.updateByPrimaryKey(updata);
        }
    }

    @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) {
        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;
        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);
        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;
    }
}
