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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.item.entity.product.po.ProductInfo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.mes.entity.completion.dto.CompletionInfoDto;
import com.fjhx.mes.entity.completion.dto.CompletionInfoSelectDto;
import com.fjhx.mes.entity.completion.po.CompletionInfo;
import com.fjhx.mes.entity.completion.vo.CompletionInfoVo;
import com.fjhx.mes.entity.production.po.ProductionPlan;
import com.fjhx.mes.entity.production.po.ProductionTask;
import com.fjhx.mes.entity.production.vo.ProductionTaskVo;
import com.fjhx.mes.entity.work.po.WorkOrder;
import com.fjhx.mes.mapper.completion.CompletionInfoMapper;
import com.fjhx.mes.service.completion.CompletionInfoService;
import com.fjhx.mes.service.production.ProductionPlanService;
import com.fjhx.mes.service.production.ProductionTaskService;
import com.fjhx.mes.service.work.WorkOrderService;
import com.fjhx.wms.entity.stock.emums.StockWaitType;
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.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.stream.Collectors;


/**
 * <p>
 * 完工入库 服务实现类
 * </p>
 *
 * @author
 * @since 2023-03-31
 */
@Service
public class CompletionInfoServiceImpl extends ServiceImpl<CompletionInfoMapper, CompletionInfo> implements CompletionInfoService {
    @Autowired
    StockWaitService stockWaitService;
    @Autowired
    StockWaitDetailsService stockWaitDetailsService;
    @Autowired
    ProductionTaskService productionTaskService;
    @Autowired
    ProductInfoService productInfoService;
    @Autowired
    ProductionPlanService productionPlanService;
    @Autowired
    WorkOrderService workOrderService;

    @Override
    public Page<CompletionInfoVo> getPage(CompletionInfoSelectDto dto) {
        IWrapper<CompletionInfo> wrapper = getWrapper();
        wrapper.orderByDesc("ci", CompletionInfo::getId);
        Page<CompletionInfoVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<CompletionInfoVo> records = page.getRecords();
        List<Long> productionTaskIds = records.stream().map(CompletionInfo::getProductionTaskId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(productionTaskIds)) {
            List<ProductionTaskVo> productionTaskVoList = productionTaskService.myListByIds(productionTaskIds);
            Map<Long, ProductionTaskVo> productionTaskVoMap = productionTaskVoList.stream().collect(Collectors.groupingBy(ProductionTaskVo::getId,
                    Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
            List<Long> productIds = productionTaskVoList.stream().map(ProductionTaskVo::getProductId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(productIds)) {
                List<ProductInfo> productInfos = productInfoService.listByIds(productIds);
                Map<Long, ProductInfo> productInfoMap = productInfos.stream().collect(Collectors.groupingBy(ProductInfo::getId,
                        Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
                for (CompletionInfoVo completionInfoVo : records) {
                    ProductionTaskVo productionTaskVo = productionTaskVoMap.get(completionInfoVo.getProductionTaskId());
                    if (ObjectUtil.isNotEmpty(productionTaskVo)) {
                        //赋值产品名
                        ProductInfo productInfo = productInfoMap.get(productionTaskVo.getProductId());
                        if (ObjectUtil.isNotEmpty(productInfo)) {
                            completionInfoVo.setProductName(productInfo.getName());
                        }
                        //复制任务编号
                        completionInfoVo.setProductionTaskCode(productionTaskVo.getCode());
                    }
                }
            }
        }
        return page;
    }

    @Override
    public CompletionInfoVo detail(Long id) {
        CompletionInfo CompletionInfo = this.getById(id);
        CompletionInfoVo result = BeanUtil.toBean(CompletionInfo, CompletionInfoVo.class);
        Long productionTaskId = result.getProductionTaskId();
        ProductionTaskVo productionTask = productionTaskService.detail(productionTaskId);
        if (ObjectUtil.isNotEmpty(productionTask)) {
            result.setProductionTaskCode(productionTask.getCode());
            result.setProductName(productionTask.getProductName());
            result.setProductionTaskQuantity(productionTask.getQuantity());
            result.setPersonLiableName(productionTask.getPersonLiableName());
            result.setProductionTaskDueDate(productionTask.getDueDate());
        }
        return result;
    }

    @Override
    public void add(CompletionInfoDto completionInfoDto) {
        this.save(completionInfoDto);
        //查询任务信息
        ProductionTaskVo detail = productionTaskService.detail(completionInfoDto.getProductionTaskId());
        //添加一条完工入库类型的待入库数据
        StockWait stockWait = new StockWait();
        stockWait.setType(1);
        stockWait.setBusinessType(StockWaitType.COMPLETION_IN.getDetailType());
        stockWait.setBusinessId(completionInfoDto.getId());
        stockWait.setStatus(0);
        stockWaitService.save(stockWait);
        StockWaitDetails stockWaitDetails =new StockWaitDetails();
        stockWaitDetails.setStockWaitId(stockWait.getId());
        stockWaitDetails.setProductId(detail.getProductId());
        stockWaitDetails.setQuantity(completionInfoDto.getQuantity());
        stockWaitDetails.setReceiptQuantity(BigDecimal.ZERO);
        stockWaitDetailsService.save(stockWaitDetails);
        //判断完工数量是否等于任务数量如果是修改任务状态为完成
        if (completionInfoDto.getQuantity().compareTo(detail.getQuantity()) >= 0) {
            detail.setStatus(2);
            productionTaskService.updateById(detail);

            //检查生产计划下的任务完成数量是否等于计划数量是就修改状态 生产计划状态
            ProductionPlan productionPlan = productionPlanService.getById(detail.getProductionPlanId());
            List<ProductionTask> productionTaskList = productionTaskService.list(q -> q.eq(ProductionTask::getProductionPlanId,
                    detail.getProductionPlanId()).eq(ProductionTask::getStatus, 2));
            BigDecimal count = productionTaskList.stream().map(ProductionTask::getQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            if (productionPlan.getQuantity().compareTo(count) >= 0) {
                productionPlan.setStatus(2);
                productionPlanService.updateById(productionPlan);
            }
            //检查工单下的计划完成数量是否等于工单数量是就修改状态 工单状态
            List<ProductionPlan> productionPlanList = productionPlanService.list(q -> q.eq(ProductionPlan::getWorkOrderId,
                    productionPlan.getWorkOrderId()).eq(ProductionPlan::getStatus, 2));
            BigDecimal count1 = productionPlanList.stream().map(ProductionPlan::getQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            WorkOrder workOrder = workOrderService.getById(productionPlan.getWorkOrderId());
            if (workOrder.getQuantity().compareTo(count1) >= 0) {
                workOrder.setStatus(2);
                workOrderService.updateById(workOrder);
            }
        }
    }

    @Override
    public void edit(CompletionInfoDto completionInfoDto) {
        this.updateById(completionInfoDto);
    }

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

}
