package vip.xiaonuo.production.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.production.entity.ProductionTarget;
import vip.xiaonuo.production.mapper.ProductionTargetMapper;
import vip.xiaonuo.production.param.ProductionParam;
import vip.xiaonuo.production.service.IProductionTargetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * <p>
 * 生产管控指标 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-12
 */
@Service
public class ProductionTargetServiceImpl extends ServiceImpl<ProductionTargetMapper, ProductionTarget> implements IProductionTargetService {

    @Autowired
    private ProductionTargetMapper targetMapper;

    @Override
    public ProductionTarget getTarget(ProductionParam productionParam) {
        String orgId = productionParam.getOrgId();
        String time = productionParam.getTime();
        String locationName = productionParam.getLocationName();
        QueryWrapper<ProductionTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        queryWrapper.select(" IFNULL(sum(plan_production),'0') planProduction," +
                "convert(IFNULL(avg(plan_complete_rate),'0'),decimal(10,2)) planCompleteRate,IFNULL(sum(actual_production),'0') actualProduction," +
                "convert(IFNULL(avg(receive_rate),'0'),decimal(10,2)) receiveRate,IFNULL(sum(production_energy),'0') productionEnergy");
        queryWrapper.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
        ProductionTarget productionTarget = targetMapper.selectOne(queryWrapper);
        BigDecimal math = new BigDecimal("10000");
        BigDecimal bg = new BigDecimal(productionTarget.getActualProduction());
        productionTarget.setActualProduction(bg.divide(math, 2, RoundingMode.HALF_UP).toString());
        return productionTarget;
    }

}
