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.QualityProduce;
import vip.xiaonuo.quality.mapper.QualityProduceMapper;
import vip.xiaonuo.quality.param.QualityProduceParam;
import vip.xiaonuo.quality.service.IQualityProduceService;
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 QualityProduceServiceImpl extends ServiceImpl<QualityProduceMapper, QualityProduce> implements IQualityProduceService {

    @Autowired
    private QualityProduceMapper produceMapper;

    @Override
    public List<QualityProduce> getList(QualityProduceParam produceParam) {
        String orgId = produceParam.getOrgId();
        String produce = produceParam.getProduce();
        Integer timeType = produceParam.getTimeType();

        QueryWrapper<QualityProduce> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.select(" CONVERT(IFNULL(avg(batch_value),'0'),decimal(10,2)) batchValue,create_time createTime,standard_value standardValue");
        queryWrapper.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 produceMapper.selectList(queryWrapper);
    }

}
