package vip.xiaonuo.production.service.impl;

import cn.hutool.core.date.DateUtil;
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.ProductionYield;
import vip.xiaonuo.production.mapper.ProductionYieldMapper;
import vip.xiaonuo.production.param.ProductionYieldParam;
import vip.xiaonuo.production.service.IProductionYieldService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 生成管控产量情况 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-12
 */
@Service
public class ProductionYieldServiceImpl extends ServiceImpl<ProductionYieldMapper, ProductionYield> implements IProductionYieldService {

    @Autowired
    private ProductionYieldMapper yieldMapper;

    @Override
    public List<ProductionYield> getList(ProductionYieldParam yieldParam) {
        String orgId = yieldParam.getOrgId();
        Integer timeType = yieldParam.getTimeType();
        String locationName = yieldParam.getLocationName();
        String produceName = yieldParam.getProduceName();
        QueryWrapper<ProductionYield> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId)
                .eq(StringUtils.isNotBlank(produceName),"produce_name",produceName)
                .eq(StringUtils.isNotBlank(locationName),"location_name",locationName);
        queryWrapper.select(" IFNULL(sum(plan_production),'0') planProduction,IFNULL(sum(actual_production),'0') actualProduction," +
                "convert(IFNULL(avg(complete_rate),'0'),decimal(10,2)) completeRate,create_time createTime");
        if (0 == timeType) {
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y')");
        } else {
            queryWrapper.ge("create_time", DateUtil.beginOfYear(new Date()));
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y-%m')");
        }
        queryWrapper.orderByAsc("create_time");
        List<ProductionYield> productionYields = yieldMapper.selectList(queryWrapper);
        BigDecimal math = new BigDecimal("10000");
        for (ProductionYield productionYield : productionYields) {
            BigDecimal bg = new BigDecimal(productionYield.getActualProduction());
            productionYield.setActualProduction(bg.divide(math, 2, RoundingMode.HALF_UP).toString());
        }
        return productionYields;
    }

}
