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

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.mes.entity.production.dto.ProductionSchedulingDto;
import com.fjhx.mes.entity.production.dto.ProductionSchedulingSelectDto;
import com.fjhx.mes.entity.production.po.ProductionScheduling;
import com.fjhx.mes.entity.production.vo.ProductionSchedulingVo;
import com.fjhx.mes.mapper.production.ProductionSchedulingMapper;
import com.fjhx.mes.service.production.ProductionSchedulingService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产排程 服务实现类
 * </p>
 *
 * @author
 * @since 2024-02-03
 */
@Service
public class ProductionSchedulingServiceImpl extends ServiceImpl<ProductionSchedulingMapper, ProductionScheduling> implements ProductionSchedulingService {

    @Override
    public Map<String, List<ProductionSchedulingVo>> listMap(ProductionSchedulingSelectDto dto) {
        IWrapper<ProductionScheduling> wrapper = getWrapper();
        //权限过滤：生产排程统计
        wrapper.in("ps", ProductionScheduling::getCompanyId, SecurityUtils.getCompanyIds());
        wrapper.eq("ps", ProductionScheduling::getCompanyId, dto.getCompanyId());

        //数据分组
        wrapper.groupBy("ps.scheduling_date", "ps.processes_id");
        //时间范围过滤
        wrapper.ge("ps", ProductionScheduling::getSchedulingDate, dto.getBeginTime());
        wrapper.le("ps", ProductionScheduling::getSchedulingDate, dto.getEndTime());
        //排序
        wrapper.orderByAsc("ps", ProductionScheduling::getSchedulingDate);
        List<ProductionSchedulingVo> list = this.baseMapper.listSumQuantity(wrapper);
        return list.stream().collect(Collectors.groupingBy(ProductionSchedulingVo::getSchedulingDateStr));
    }

    @DSTransactional
    @Override
    public void add(List<ProductionScheduling> dtoList) {
        for (ProductionScheduling productionSchedulingDto : dtoList) {
            productionSchedulingDto.setCompanyId(SecurityUtils.getCompanyId());
        }
        this.saveBatch(dtoList);
    }

    @Override
    public void edit(ProductionSchedulingDto productionSchedulingDto) {
        this.updateById(productionSchedulingDto);
    }

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

}
