package com.fjhx.mes.service.report.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.item.entity.product.po.ProductInfo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.mes.entity.report.dto.ReportLossesDetailsDto;
import com.fjhx.mes.entity.report.dto.ReportLossesDetailsSelectDto;
import com.fjhx.mes.entity.report.po.ReportLossesDetails;
import com.fjhx.mes.entity.report.vo.ReportLossesDetailsVo;
import com.fjhx.mes.mapper.report.ReportLossesDetailsMapper;
import com.fjhx.mes.service.report.ReportLossesDetailsService;
import com.fjhx.tenant.utils.DeptUstil;
import com.fjhx.wms.entity.stock.emums.JournalType;
import com.fjhx.wms.entity.stock.po.StockWait;
import com.fjhx.wms.entity.stock.po.StockWaitDetails;
import com.fjhx.wms.service.stock.StockWaitDetailsService;
import com.fjhx.wms.service.stock.StockWaitService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 报损管理 服务实现类
 * </p>
 *
 * @author
 * @since 2024-01-26
 */
@Service
public class ReportLossesDetailsServiceImpl extends ServiceImpl<ReportLossesDetailsMapper, ReportLossesDetails> implements ReportLossesDetailsService {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private StockWaitService stockWaitService;
    @Autowired
    private StockWaitDetailsService stockWaitDetailsService;

    @Override
    public Page<ReportLossesDetailsVo> getPage(ReportLossesDetailsSelectDto dto) {
        IWrapper<ReportLossesDetails> wrapper = getWrapper();

        //类型过滤
        wrapper.eq("rld", ReportLossesDetailsVo::getType, dto.getType());

        //时间范围过滤
        wrapper.ge("rld", ReportLossesDetails::getRepoTime, dto.getBeginTime());
        wrapper.le("rld", ReportLossesDetails::getRepoTime, dto.getEndTime());

        //近n天过滤
        Integer pastDay = dto.getPastDay();
        if (ObjectUtil.isNotEmpty(pastDay)) {
            wrapper.ge("DATEDIFF(NOW(),rld.repo_time)", 0);
            wrapper.le("DATEDIFF(NOW(),rld.repo_time)", pastDay);
        }


        //关键字检索
        if (ObjectUtil.isNotEmpty(dto.getKeyword())) {
            List<Long> pIds = productInfoService.listObject(ProductInfo::getId, q -> q
                    .like(ProductInfo::getCustomCode, dto.getKeyword())
                    .or().like(ProductInfo::getName, dto.getKeyword())
            );
            wrapper.and(q -> q
                    .in("rld.material_id", pIds)
                    .or().like("rld.repo_time", dto.getKeyword())
                    .or().like("po.code", dto.getKeyword())
            );
        }

        //权限过滤：报损统计-子公司看自己的,总公司看全部
        Long companyId = SecurityUtils.getCompanyId();
        if (!Objects.equals(companyId, 100L)) {
            wrapper.eq("rld", ReportLossesDetails::getCompanyId, companyId);
        } else {
            wrapper.eq("rld", ReportLossesDetails::getCompanyId, dto.getCompanyId());
        }


        wrapper.groupBy("rld.id");

        wrapper.orderByDesc("rld", ReportLossesDetails::getId);
        Page<ReportLossesDetailsVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);

        List<ReportLossesDetailsVo> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return page;
        }

        //获取生产公司信息
        List<Long> companyIds = records.stream().map(ReportLossesDetailsVo::getCompanyId).collect(Collectors.toList());
        Map<Long, String> companyNameMap = DeptUstil.getDeptNameMap(companyIds);

        for (ReportLossesDetailsVo record : records) {
            //赋值生产公司名称
            record.setCompanyName(companyNameMap.get(record.getCompanyId()));
        }

        //赋值产品信息
        productInfoService.attributeAssign(records, ReportLossesDetailsVo::getMaterialId, (item, product) -> {
            item.setMaterialCode(product.getCustomCode());
            item.setMaterialName(product.getName());
            item.setMaterialLength(product.getLength());
            item.setMaterialWidth(product.getWidth());
            item.setMaterialHeight(product.getHeight());
        });

        return page;
    }

    @Override
    public ReportLossesDetailsVo detail(Long id) {
        ReportLossesDetails ReportLossesDetails = this.getById(id);
        ReportLossesDetailsVo result = BeanUtil.toBean(ReportLossesDetails, ReportLossesDetailsVo.class);
        return result;
    }

    @DSTransactional
    @Override
    public void add(ReportLossesDetailsDto dto) {

        Long companyId = SecurityUtils.getCompanyId();
        dto.setCompanyId(companyId);

        this.save(dto);

        //保存附件
        ObsFileUtil.saveFile(dto.getFileList(), dto.getId());

        JournalType journalType = Objects.equals(dto.getType(), 1) ? JournalType.REPAIR_EXCEED_OUT : JournalType.LOSE_EXCEED_OUT;

        //生成待出库数据
        StockWait stockWait = new StockWait();
        stockWait.setType(2);
        stockWait.setBusinessType(journalType.getDetailType());
        stockWait.setBusinessId(dto.getId());
        stockWait.setStatus(0);
        stockWaitService.save(stockWait);
        StockWaitDetails stockWaitDetails = new StockWaitDetails();
        stockWaitDetails.setStockWaitId(stockWait.getId());
        stockWaitDetails.setProductId(dto.getMaterialId());
        stockWaitDetails.setQuantity(dto.getQuantity());
        stockWaitDetails.setReceiptQuantity(BigDecimal.ZERO);
        stockWaitDetailsService.save(stockWaitDetails);
    }

    @Override
    public void edit(ReportLossesDetailsDto dto) {

        //保存附件
        ObsFileUtil.editFile(dto.getFileList(), dto.getId());

        this.updateById(dto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

    @Override
    public JSONObject lossesStatistics(ReportLossesDetailsSelectDto dto) {
        IWrapper<Object> wrapper = IWrapper.getWrapper();

        //权限过滤：报损统计-子公司看自己的,总公司看全部
        Long companyId = SecurityUtils.getCompanyId();
        if (!Objects.equals(companyId, 100L)) {
            wrapper.eq("rld", ReportLossesDetails::getCompanyId, companyId);
        } else {
            wrapper.eq("rld", ReportLossesDetails::getCompanyId, dto.getCompanyId());
        }

        //近n天过滤
        Integer pastDay = dto.getPastDay();
        if (ObjectUtil.isNotEmpty(pastDay)) {
            wrapper.ge("DATEDIFF(NOW(),rld.repo_time)", 0);
            wrapper.le("DATEDIFF(NOW(),rld.repo_time)", pastDay);
        }
        return baseMapper.lossesStatistics(wrapper);
    }

}
