package vip.xiaonuo.quality.service.impl;

import cn.hutool.core.date.DateTime;
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.quality.entity.QualityMiddleware;
import vip.xiaonuo.quality.entity.QualityProduce;
import vip.xiaonuo.quality.mapper.QualityMiddlewareMapper;
import vip.xiaonuo.quality.param.QualityMiddlewareParam;
import vip.xiaonuo.quality.service.IQualityMiddlewareService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 中间体质量趋势 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-11
 */
@Service
public class QualityMiddlewareServiceImpl extends ServiceImpl<QualityMiddlewareMapper, QualityMiddleware> implements IQualityMiddlewareService {

    @Autowired
    private QualityMiddlewareMapper middlewareMapper;

    @Override
    public List<QualityMiddleware> getList(QualityMiddlewareParam middlewareParam) {
        String location = middlewareParam.getLocation();
        String orgId = middlewareParam.getOrgId();
        String produce = middlewareParam.getProduce();
        Integer timeType = middlewareParam.getTimeType();

        QueryWrapper<QualityMiddleware> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.select(" CONVERT(IFNULL(avg(batch_value),'0'),decimal(10,2)) batchValue,CONVERT(IFNULL(avg(standard_value),'0'),decimal(10,2)) standardValue," +
                "create_time createTime");
        queryWrapper.eq(StringUtils.isNotBlank(location), "location", location)
                .eq(StringUtils.isNotBlank(produce), "produce_name", produce);
        if (0 == timeType) {
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y')");
        } else {
            DateTime dateTime = DateUtil.beginOfYear(new Date());
            queryWrapper.ge("create_time", dateTime);
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y-%m')");
        }
        queryWrapper.orderByAsc("create_time");
        return middlewareMapper.selectList(queryWrapper);
    }

}
