package com.bonus.material.push.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.config.DateTimeHelper;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.push.domain.AccProjectLeaseMoneyBean;
import com.bonus.material.push.domain.ConsProjectLeaseMoneyBean;
import com.bonus.material.push.domain.IwsCostPushBean;
import com.bonus.material.push.domain.RentalCostsBean;
import com.bonus.material.push.mapper.AccProjectLeaseMoneyMapper;
import com.bonus.material.push.mapper.ConsProjectLeaseMoneyMapper;
import com.bonus.material.push.mapper.IwsCostPushMapper;
import com.bonus.material.push.mapper.RentalCostsMapper;
import com.bonus.material.push.service.IwsCostPushService;
import com.bonus.material.push.service.RentalCostsService;
import com.bonus.material.settlement.domain.SltAgreementInfo;
import com.bonus.material.settlement.domain.vo.SltInfoVo;
import com.bonus.material.settlement.service.ISltAgreementInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : 阮世耀
 * @version : 1.0
 * @PackagePath: com.bonus.material.push.service.impl
 * @CreateTime: 2025-01-23  14:48
 * @Description: 描述
 */
@Service
public class RentalCostsServiceImpl implements RentalCostsService {

    @Autowired
    private RentalCostsMapper dao;

    @Autowired
    private AccProjectLeaseMoneyMapper accDao;

    @Autowired
    ConsProjectLeaseMoneyMapper consDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calcMonthInfo() {
        RentalCostsBean o = new RentalCostsBean();
        // yyyy-MM 获取上个月的月份
        o.setMonth(DateTimeHelper.getPrevMonth());

        int res = accDao.insertCalcRecord(o);
        if (res == 0) {
            throw new RuntimeException("新增calc_project_month失败");
        }
        String taskId = o.getId();

        // 获取上个月的第一天日期:2024-05-01
        String startTime = DateTimeHelper.getPreFirstDay();
        // 获取上个月的最后一天:2024-05-31
        String endTime = DateTimeHelper.getPreLastDay();

        ConsProjectLeaseMoneyBean cons = new ConsProjectLeaseMoneyBean();
        cons.setStartTime(startTime);
        cons.setEndTime(endTime);

        List<ConsProjectLeaseMoneyBean> list = consDao.getRealtionList(cons);
        calcMonthInfoDetails(list, startTime, endTime, taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void iwsProjectCycle() {
        //查找iws的工程数据
        List<BmProject> list = consDao.getIwsProjectList();
        //修正bns_cloud_material数据
        if (list != null && list.size() > 0) {
            consDao.updateIwsProject(list);
        }

    }




    private void calcMonthInfoDetails(List<ConsProjectLeaseMoneyBean> list, String startTime, String endTime, String taskId) {
        int res;
        LocalDate date = LocalDate.parse(startTime, DateTimeFormatter.ISO_DATE);
        String month = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        List<ConsProjectLeaseMoneyBean> total = new ArrayList<>();
        for(ConsProjectLeaseMoneyBean bean : list){
            String agreementId = bean.getAgreementId();


            // 机具部分，中转表 project_month_info
            float leaseTotal = generatePushData4Machines(agreementId, startTime, endTime, taskId);

            //消耗品部分，中转表 project_month_info
            float consTotal = generatePushData4Consumables(agreementId, startTime, endTime, taskId);

            //报废费用，中转表 project_month_info
            float scrapTotal = generatePushData4Scrap(agreementId, startTime, endTime, taskId);

            //丢失费用，中转表 project_month_info
            float lostTotal = generatePushData4Lost(agreementId, startTime, endTime, taskId);

            //维修费用，中转表 project_month_info
            float repairTotal = generatePushData4Repair(agreementId, startTime, endTime, taskId);

            if (leaseTotal > 0 || consTotal > 0 || scrapTotal > 0 || lostTotal > 0) {
                bean.setLeaseTotal(leaseTotal + "");
                bean.setConsTotal(consTotal + "");
                bean.setScrapTotal(scrapTotal + "");
                bean.setLostTotal(lostTotal + "");
                bean.setRepairTotal(repairTotal + "");
                bean.setTaskId(taskId);
                bean.setMonth(month);
                total.add(bean);
            }
        }
        res = consDao.insertProjectMonthCosts(total);
        if (res == 0) {
            throw new RuntimeException("新增project_month_costs失败");
        }
    }

    private float generatePushData4Machines(String agreementId,String startTime, String endTime, String taskId) {
        System.out.println("开始机具费用数据收集定时任务");
        AccProjectLeaseMoneyBean o = new AccProjectLeaseMoneyBean();
        o.setStartTime(startTime);
        o.setEndTime(endTime);
        o.setAgreementId(agreementId);


        BigDecimal total = new BigDecimal("0");
        List<AccProjectLeaseMoneyBean> infos = accDao.getLeaseMoneyDetail(o);
        if (infos != null && infos.size() > 0) {
            for(AccProjectLeaseMoneyBean info : infos){
                info.setTaskId(taskId);
                info.setAgreementId(agreementId);

                total = total.add(new BigDecimal(info.getLeaseMoney()));
            }
            int res = accDao.insertProjectMonthInfo(infos);
            if (res == 0) {
                throw new RuntimeException("新增project_month_info失败");
            }
        }

        return total.setScale(2).floatValue();

    }

    private float generatePushData4Consumables(String agreementId,String startTime, String endTime, String taskId) {
        System.out.println("开始消耗品费用数据收集定时任务");
        ConsProjectLeaseMoneyBean o = new ConsProjectLeaseMoneyBean();
        o.setStartTime(startTime);
        o.setEndTime(endTime);
        o.setAgreementId(agreementId);


        BigDecimal total = new BigDecimal("0");
        List<ConsProjectLeaseMoneyBean> infos = consDao.getConsMonthMoney(o);
        if (infos != null && infos.size() > 0) {
            for(ConsProjectLeaseMoneyBean info : infos){
                info.setTaskId(taskId);
                info.setAgreementId(agreementId);

                total = total.add(new BigDecimal(info.getLeaseMoney()));
            }
            int res = consDao.insertProjectConsMonthInfo(infos);
            if (res == 0) {
                throw new RuntimeException("新增project_month_info失败");
            }
        }
        return total.setScale(2).floatValue();
    }

    private float generatePushData4Scrap(String agreementId,String startTime, String endTime, String taskId) {
        System.out.println("开始报废费用数据收集定时任务");
        ConsProjectLeaseMoneyBean o = new ConsProjectLeaseMoneyBean();
        o.setStartTime(startTime);
        o.setEndTime(endTime);
        o.setAgreementId(agreementId);


        BigDecimal total = new BigDecimal("0");
        List<ConsProjectLeaseMoneyBean> infos = consDao.getScrapMoney(o);
        if (infos != null && infos.size() > 0) {
            for(ConsProjectLeaseMoneyBean info : infos){
                info.setTaskId(taskId);
                info.setAgreementId(agreementId);
                info.setType("4");
                total = total.add(new BigDecimal(info.getLeaseMoney()));
            }
            int res = consDao.insertProjectOthersMonthInfo(infos);
            if (res == 0) {
                throw new RuntimeException("新增project_month_info失败");
            }
        }
        return total.setScale(2).floatValue();
    }

    private float generatePushData4Lost(String agreementId,String startTime, String endTime, String taskId) {
        System.out.println("开始丢失费用数据收集定时任务");
        ConsProjectLeaseMoneyBean o = new ConsProjectLeaseMoneyBean();
        o.setStartTime(startTime);
        o.setEndTime(endTime);
        o.setAgreementId(agreementId);


        BigDecimal total = new BigDecimal("0");
        List<ConsProjectLeaseMoneyBean> infos = consDao.getLostMoney(o);
        if (infos != null && infos.size() > 0) {
            for(ConsProjectLeaseMoneyBean info : infos){
                info.setTaskId(taskId);
                info.setAgreementId(agreementId);
                info.setType("5");
                total = total.add(new BigDecimal(info.getLeaseMoney()));
            }
            int res = consDao.insertProjectOthersMonthInfo(infos);
            if (res == 0) {
                throw new RuntimeException("新增project_month_info失败");
            }
        }
        return total.setScale(2).floatValue();
    }

    private float generatePushData4Repair(String agreementId,String startTime, String endTime, String taskId) {
        System.out.println("开始维修费用数据收集定时任务");
        ConsProjectLeaseMoneyBean o = new ConsProjectLeaseMoneyBean();
        o.setStartTime(startTime);
        o.setEndTime(endTime);
        o.setAgreementId(agreementId);


        BigDecimal total = new BigDecimal("0");
        List<ConsProjectLeaseMoneyBean> infos = consDao.getRepairMoney(o);
        if (infos != null && infos.size() > 0) {
            for(ConsProjectLeaseMoneyBean info : infos){
                info.setTaskId(taskId);
                info.setAgreementId(agreementId);
                info.setType("3");
                total = total.add(new BigDecimal(info.getLeaseMoney()));
            }
            int res = consDao.insertProjectOthersMonthInfo(infos);
            if (res == 0) {
                throw new RuntimeException("新增project_month_info失败");
            }
        }
        return total.setScale(2).floatValue();
    }

}
