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

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.report.*;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.basic.mapper.BmReportMapper;
import com.bonus.material.basic.service.BmReportService;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BmReportServiceImpl
 * @Author ma_sh
 * @create 2025/1/22 9:53
 */
@Service
public class BmReportServiceImpl implements BmReportService {

    @Resource
    private BmReportMapper bmReportMapper;

    @Resource
    private BmFileInfoMapper fileInfoMapper;
    /**
     * 新购入库报表查询
     * @param bean
     * @return
     */
    @Override
    public List<PurChaseReportInfo> getPurChaseReportList(PurChaseReportInfo bean) {
        bean.setUserId(SecurityUtils.getLoginUser().getUserid());
        BigDecimal totalPurchaseNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPassNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPurchasePrice = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        BigDecimal totalPurchasePriceNoTax = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        BigDecimal totalPendingInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<PurChaseReportInfo> list = bmReportMapper.getPurChaseReportList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            for (PurChaseReportInfo purChaseReportInfo : list) {
                totalPurchaseNum = totalPurchaseNum.add(purChaseReportInfo.getPurchaseNum());
                totalPassNum = totalPassNum.add(purChaseReportInfo.getPassNum());
                totalInputNum = totalInputNum.add(purChaseReportInfo.getInputNum());
                totalPurchasePrice = totalPurchasePrice.add(purChaseReportInfo.getPurchasePrice());
                totalPurchasePriceNoTax = totalPurchasePriceNoTax.add(purChaseReportInfo.getPurchasePriceNoTax());
                totalPendingInputNum = totalPendingInputNum.add(purChaseReportInfo.getPendingInputNum());
            }
        }
        if (bean.getIsExport() == 0) {
            PurChaseReportInfo info = new PurChaseReportInfo();
            info.setPurchaseNum(totalPurchaseNum);
            info.setPassNum(totalPassNum);
            info.setInputNum(totalInputNum);
            info.setPurchasePrice(totalPurchasePrice);
            info.setPurchasePriceNoTax(totalPurchasePriceNoTax);
            info.setPendingInputNum(totalPendingInputNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }

    /**
     * 新购入库报表查询详情
     * @param bean
     * @return
     */
    @Override
    public List<PurChaseReportDetails> getPurChaseReportDetailsList(PurChaseReportInfo bean) {
        return bmReportMapper.getPurChaseReportDetailsList(bean);
    }

    /**
     * 新购入库报表查询详情
     * @param bean
     * @return
     */
    @Override
    public List<PurChaseReportDetails> getPurChaseReportSuccessList(PurChaseReportInfo bean) {
        return bmReportMapper.getPurChaseReportSuccessList(bean);
    }

    /**
     * 新购入库数量报表详情查询
     * @param bean
     * @return
     */
    @Override
    public List<PurChaseReportDetails> getPurChaseReportInBoundList(PurChaseReportInfo bean) {
        return bmReportMapper.getPurChaseReportInBoundList(bean);
    }

    /**
     * 新购未入库数量报表详情查询
     * @param bean
     * @return
     */
    @Override
    public List<PurChaseReportDetails> getPurChaseReportNotInBoundList(PurChaseReportInfo bean) {
        return bmReportMapper.getPurChaseReportNotInBoundList(bean);
    }

    /**
     * 领料出库报表查询
     * @param bean
     * @return
     */
    @Override
    public List<LeaseOutInfo> getLeaseOutList(LeaseOutInfo bean) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        BigDecimal totalLeaseNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalOutNumNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPendingOutNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<LeaseOutInfo> list = bmReportMapper.getLeaseOutList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            // 将list集合中userId不为空，且和userId相等的数据过滤处理
            list = list.stream().filter(item -> item.getUserId() != null && item.getUserId().equals(userId))
                    .collect(Collectors.toList());
            for (LeaseOutInfo leaseOutInfo : list) {
                totalLeaseNum = totalLeaseNum.add(leaseOutInfo.getLeaseNum());
                totalOutNumNum = totalOutNumNum.add(leaseOutInfo.getOutNum());
                totalPendingOutNum = totalPendingOutNum.add(leaseOutInfo.getPendingOutNum());
                //判断是否是领用任务
                if (StringUtils.isNotNull(leaseOutInfo)  && leaseOutInfo.getTaskType()==19){
                    LeaseOutInfo leaseOutInfoNew = bmReportMapper.getLeaseInfoById(leaseOutInfo.getParentId());
                    leaseOutInfo.setLeaseUnitName(leaseOutInfoNew.getLeaseUnitName());
                    leaseOutInfo.setLeaseProjectName(leaseOutInfoNew.getLeaseProjectName());
                }
            }
        }
        //模糊查询
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            String keyWord = bean.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                list = list.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        if (bean.getIsExport() == 0) {
            LeaseOutInfo info = new LeaseOutInfo();
            info.setLeaseNum(totalLeaseNum);
            info.setOutNum(totalOutNumNum);
            info.setPendingOutNum(totalPendingOutNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }
    private boolean containsKeyword(LeaseOutInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getLeaseUnitName() != null && item.getLeaseUnitName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getLeaseProjectName() != null && item.getLeaseProjectName().contains(keyWord)) ||
                (item.getLeasePersonName()!= null && item.getLeasePersonName().contains(keyWord));
    }

    /**
     * 领料出库报表查询详情
     * @param bean
     * @return
     */
    @Override
    public List<LeaseOutDetails> getLeaseOutDetailsList(LeaseOutInfo bean) {
        return bmReportMapper.getLeaseOutDetailsList(bean);
    }

    /**
     * 退料报表查询
     * @param bean
     * @return
     */
    @Override
    public List<BackInputInfo> getBackInputList(BackInputInfo bean) {
        Long userid = SecurityUtils.getLoginUser().getUserid();
        BigDecimal totalBackNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<BackInputInfo> list = bmReportMapper.getBackInputList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            list = list.stream().filter(item -> item.getUserId() != null && item.getUserId().equals(userid))
                    .collect(Collectors.toList());
            for (BackInputInfo backInputInfo : list) {
                totalBackNum = totalBackNum.add(backInputInfo.getBackNum());
            }
        }
        if (bean.getIsExport() == 0) {
            BackInputInfo info = new BackInputInfo();
            info.setBackNum(totalBackNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }

    /**
     * 退料报表查询详情
     * @param bean
     * @return
     */
    @Override
    public List<BackInputDetails> getBackDetailsInputList(BackInputInfo bean) {
        return bmReportMapper.getBackDetailsInputList(bean);
    }

    /**
     * 维修报表
     * @param bean
     * @return
     */
    @Override
    public List<RepairInfo> getRepairList(RepairInfo bean) {
        bean.setUserId(SecurityUtils.getLoginUser().getUserid());
        BigDecimal totalBackNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalRepairedNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPendingScrapNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPendingRepairNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<RepairInfo> list = bmReportMapper.getRepairList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            for (RepairInfo repairInfo : list) {
                if (!StringHelper.isNullOrEmptyString(repairInfo.getNickName())){
                    repairInfo.setRepairPersonName(repairInfo.getNickName());
                }
                totalBackNum = totalBackNum.add(repairInfo.getBackNum());
                totalRepairedNum = totalRepairedNum.add(repairInfo.getRepairedNum());
                totalPendingScrapNum = totalPendingScrapNum.add(repairInfo.getPendingScrapNum());
                totalPendingRepairNum = totalPendingRepairNum.add(repairInfo.getPendingRepairNum());
            }
        }
        if (bean.getIsExport() == 0) {
            RepairInfo info = new RepairInfo();
            info.setBackNum(totalBackNum);
            info.setRepairedNum(totalRepairedNum);
            info.setPendingScrapNum(totalPendingScrapNum);
            info.setPendingRepairNum(totalPendingRepairNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }

    /**
     * 维修报表详情
     * @param bean
     * @return
     */
    @Override
    public List<RepairDetails> getRepairDetailsList(RepairInfo bean) {
        List<RepairDetails> list = bmReportMapper.getRepairDetailsList(bean);
        if (list.size()>0){
            //处理数据库中维修人字段既有Id也有人员的问题
            for (RepairDetails repairDetails : list){
                if (!StringHelper.isNullOrEmptyString(repairDetails.getNickName())){
                    repairDetails.setRepairPersonName(repairDetails.getNickName());
                }
            }
        }
        return list;
    }

    /**
     * 修饰入库报表
     * @param bean
     * @return
     */
    @Override
    public List<RepairInputDto> getRepairInputList(RepairInputDto bean) {
        bean.setUserId(SecurityUtils.getLoginUser().getUserid());
        BigDecimal totalRepairedNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPendingInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<RepairInputDto> list = bmReportMapper.getRepairInputList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            for (RepairInputDto repairInputInfo : list) {
                totalRepairedNum = totalRepairedNum.add(repairInputInfo.getRepairedNum());
                totalInputNum = totalInputNum.add(repairInputInfo.getInputNum());
                totalPendingInputNum = totalPendingInputNum.add(repairInputInfo.getPendingInputNum());
            }
        }
        if (bean.getIsExport() == 0) {
            RepairInputDto info = new RepairInputDto();
            info.setRepairedNum(totalRepairedNum);
            info.setInputNum(totalInputNum);
            info.setPendingInputNum(totalPendingInputNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }

    /**
     * 修饰入库报表查询详情查询
     * @param bean
     * @return
     */
    @Override
    public List<RepairInputDetails> getRepairInputDetailsList(RepairInputDto bean) {
        return bmReportMapper.getRepairInputDetailsList(bean);
    }

    /**
     * 报废报表
     * @param bean
     * @return
     */
    @Override
    public List<ScrapInfo> getScrapList(ScrapInfo bean) {
        bean.setUserId(SecurityUtils.getLoginUser().getUserid());
        BigDecimal totalScrapNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<ScrapInfo> list = bmReportMapper.getScrapList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            String keyWord = bean.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                list = list.stream()
                        .filter(item -> containsScrapKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
            for (ScrapInfo scrapInfo : list) {
                BigDecimal totalCost = scrapInfo.getScrapNum().multiply(scrapInfo.getBuyPrice());
                scrapInfo.setScrapPrice(totalCost);
                totalScrapNum = totalScrapNum.add(scrapInfo.getScrapNum());
                BmFileInfo bmFileInfo = new BmFileInfo();
                if (scrapInfo.getRepairId() != null) {
                    bmFileInfo.setModelId(scrapInfo.getRepairId());
                    bmFileInfo.setTaskType(4);
                    List<BmFileInfo> fileInfos = fileInfoMapper.selectBmFileInfoList(bmFileInfo);
                    if (CollectionUtils.isNotEmpty(fileInfos)) {
                        scrapInfo.setFileList(fileInfos);
                    }
                } else {
                    bmFileInfo.setTaskType(TmTaskTypeEnum.TM_TASK_PART_SCRAP.getTaskTypeId());
                    bmFileInfo.setFileType(6L);
                    bmFileInfo.setTaskId(scrapInfo.getTaskId());
                    List<BmFileInfo> bmFileInfos = fileInfoMapper.selectBmFileInfoList(bmFileInfo);
                    if (CollectionUtils.isNotEmpty(bmFileInfos)) {
                        scrapInfo.setFileList(bmFileInfos);
                    }
                }
            }
        }
        if (bean.getIsExport() == 0) {
            ScrapInfo info = new ScrapInfo();
            info.setScrapNum(totalScrapNum);
            info.setUnitName("合计");
            list.add(0, info);
        }
        return list;
    }

    /**
     * 报废报表关键字过滤
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsScrapKeyword(ScrapInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getScrapCode() != null && item.getScrapCode().contains(keyWord)) ||
                (item.getScrapPersonName() != null && item.getScrapPersonName().contains(keyWord)) ||
                (item.getBackUnit() != null && item.getBackUnit().contains(keyWord)) ||
                (item.getBackPro() != null && item.getBackPro().contains(keyWord)) ||
                (item.getScrapReason() != null && item.getScrapReason().contains(keyWord)) ||
                (item.getScrapType() != null && item.getScrapType().contains(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord));
    }

    /**
     * 报废报表查询详情
     * @param bean
     * @return
     */
    @Override
    public List<ScrapDetailsInfo> getScrapDetailsList(ScrapInfo bean) {
        return bmReportMapper.getScrapDetailsList(bean);
    }

    /**
     * 判断字符串是否为纯数字（可用于判断是否为用户ID）
     */
    private boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}
