package com.bonus.sgzb.material.remind.service;

import com.bonus.sgzb.base.api.domain.SltAgreementInfo;
import com.bonus.sgzb.common.core.utils.DateTimeHelper;
import com.bonus.sgzb.material.domain.AgreementInfo;
import com.bonus.sgzb.material.domain.CalMonthlyBean;
import com.bonus.sgzb.material.domain.ProjectMonthCosts;
import com.bonus.sgzb.material.domain.ProjectMonthDetail;
import com.bonus.sgzb.material.mapper.CalMonthlyMapper;
import com.bonus.sgzb.material.mapper.SltAgreementInfoMapper;
import com.bonus.sgzb.material.service.AgreementInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class CalcMonthlyServiceImp implements CalcMonthlyService {

    @Resource
    CalMonthlyMapper calMonthlyMapper;

    @Resource
    private AgreementInfoService agreementInfoService;

    @Resource
    private SltAgreementInfoMapper sltAgreementInfoMapper;

    @Override
    public void calcMonthInfo(int day) {
        String month;
        String startTime;
        String endTime;
        if (day == 1) {
            month = DateTimeHelper.getPrevMonth();
            startTime = DateTimeHelper.getPreMonthFirstDay();
            endTime = DateTimeHelper.getCurrentMonthFirstDay();
        } else {
            month = DateTimeHelper.getCurrentMonth();
            startTime = DateTimeHelper.getPreMonthCalStartDay(day);
            endTime = DateTimeHelper.getCurrentMonthCalEndDay(day);
        }
        CalMonthlyBean record = new CalMonthlyBean();
        record.setMonth(month);
        cleanSameMonthOldRecords(record);
        List<AgreementInfo> list = agreementInfoService.getAllAgreementId();
        list.forEach(t -> {
            t.setStartTime(startTime);
            t.setEndTime(endTime);
        });
        addProjectMonthCosts(list, record);
    }

    private void cleanSameMonthOldRecords(CalMonthlyBean record) {
        List<CalMonthlyBean> list = calMonthlyMapper.getCalcRecords(record);
        if (!CollectionUtils.isEmpty(list)) {
            for (CalMonthlyBean bean : list) {
                //清除上月之前计算过的记录 calc_project_month
                calMonthlyMapper.deleteCalcRecord(bean);

                //清除上月之前计算过的记录 project_month_detail, project_month_costs
                calMonthlyMapper.deleteMonthlyDetail(bean);
                calMonthlyMapper.deleteMonthlyCosts(bean);
            }
        }
    }

    private List<SltAgreementInfo> addProjectMonthCosts(List<AgreementInfo> list, CalMonthlyBean record) {
        List<SltAgreementInfo> leaseList = new ArrayList<>();
        calMonthlyMapper.insertCalcRecord(record);
        String taskId = record.getId();
        for (AgreementInfo bean : list) {
            if (StringUtils.isNotBlank(bean.getStartTime()) && StringUtils.isNotBlank(bean.getEndTime())) {
                List<SltAgreementInfo> monthList = sltAgreementInfoMapper.getLeaseListMonthNotNull(bean);
                monthList.stream().filter(Objects::nonNull);

                for (SltAgreementInfo sltAgreementInfo : monthList) {
                    ProjectMonthCosts projectMonthCosts = new ProjectMonthCosts();
                    projectMonthCosts.setAgreementId(Integer.parseInt(sltAgreementInfo.getAgreementId()));
                    projectMonthCosts.setSltMonthId(Integer.parseInt(taskId));
                    projectMonthCosts.setTaskId(Integer.parseInt(taskId));
                    projectMonthCosts.setUnitId(sltAgreementInfo.getUnitId());
                    projectMonthCosts.setProjectId(sltAgreementInfo.getLotId());
                    projectMonthCosts.setMonth(record.getMonth());
                    projectMonthCosts.setCostBearingParty(sltAgreementInfo.getCostBearingParty());
                    calMonthlyMapper.insertProMonCosts(projectMonthCosts);
                    // project_month_costs的主键id
                    int pmcId = projectMonthCosts.getId();

                    AgreementInfo agreementInfo = new AgreementInfo();
                    agreementInfo.setAgreementId(bean.getAgreementId());
                    agreementInfo.setCostBearingParty(sltAgreementInfo.getCostBearingParty());
                    agreementInfo.setStartTime(sltAgreementInfo.getBeginTime());
                    agreementInfo.setIds(sltAgreementInfo.getIds());
                    sltAgreementInfo.setMonth(bean.getMonth());
                    agreementInfo.setEndTime(sltAgreementInfo.getOffTime());
                    List<SltAgreementInfo> leaseListOneMonth = addProjectMonthDetail(agreementInfo, sltAgreementInfo, pmcId);
                    projectMonthCosts.setCosts(sltAgreementInfo.getCosts());
                    calMonthlyMapper.updateProMonCosts(projectMonthCosts);
                    sltAgreementInfo.setNode(leaseListOneMonth);
                }
                leaseList.addAll(monthList);
            }
        }
        return leaseList;
    }


    private List<SltAgreementInfo> addProjectMonthDetail(AgreementInfo agreementInfo, SltAgreementInfo sltAgreementInfo, Integer pmcId) {
        ArrayList<String> idList = new ArrayList<>();
        String[] ids = agreementInfo.getIds().split(",");
        for (String id : ids) {
            idList.add(id);
        }
        List<SltAgreementInfo> leaseList = sltAgreementInfoMapper.getLeaseListOneMonth(agreementInfo, idList);
        BigDecimal leaseCostOne = BigDecimal.ZERO;
        for (SltAgreementInfo bean : leaseList) {
            if (StringUtils.isEmpty(bean.getLeasePrice())) {
                bean.setLeasePrice("0");
            }
            if (StringUtils.isEmpty(bean.getNum())) {
                bean.setNum("0");
            }
            if (StringUtils.isEmpty(bean.getLeaseDays())) {
                bean.setLeaseDays("0");
            }
            if (Objects.isNull(bean.getTrimDay())) {
                bean.setTrimDay(0);
            }
            BigDecimal leasePrice = new BigDecimal(bean.getLeasePrice());
            BigDecimal num = new BigDecimal(bean.getNum());
            BigDecimal leaseDays = new BigDecimal(bean.getLeaseDays());
            // 实际结算天数（领料天数 + 调整天数(可以为负整数)）
            BigDecimal realDays = leaseDays.add(new BigDecimal(bean.getTrimDay()));
            // 实际结算金额
            BigDecimal realCosts = leasePrice.multiply(num).multiply(realDays);
            // 应结算金额
            BigDecimal costs = leasePrice.multiply(num).multiply(leaseDays);
            bean.setCosts(String.valueOf(costs));
            bean.setRealDays(realDays);
            bean.setRealCosts(String.valueOf(realCosts));
            leaseCostOne = leaseCostOne.add(costs);
            bean.setMonth(sltAgreementInfo.getMonth());

            ProjectMonthDetail projectMonthDetail = new ProjectMonthDetail();
            projectMonthDetail.setTypeId(Integer.valueOf(bean.getTypeId()));
            if (bean.getMaId() != null){
                projectMonthDetail.setMaId(Integer.valueOf(bean.getMaId()));
            }
            projectMonthDetail.setUnit(bean.getNuitName());
            projectMonthDetail.setStartTime(bean.getStartTime());
            projectMonthDetail.setEndTime(bean.getEndTime());
            projectMonthDetail.setSltDays(bean.getLeaseDays());
            projectMonthDetail.setNum(bean.getNum());
            projectMonthDetail.setLeasePrice(bean.getLeasePrice());
            projectMonthDetail.setSltCosts(bean.getCosts());
            projectMonthDetail.setMonthTemporarilyCosts(bean.getRealCosts());
            projectMonthDetail.setProMonthCostId(pmcId);
            calMonthlyMapper.insertProjectMonthDetail(projectMonthDetail);
        }
        sltAgreementInfo.setCosts(String.valueOf(leaseCostOne));
        return leaseList;
    }

}
