package com.tofly.watermeter.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.custom.dto.ReadrecolrdDto;
import com.tofly.watermeter.entity.Readrecolrd;
import com.tofly.watermeter.mapper.ReadrecolrdMapper;
import com.tofly.watermeter.service.ReadrecolrdService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * @author 泡泡
 */
@Service("readrecolrdService")
public class ReadrecolrdServiceImpl extends ServiceImpl<ReadrecolrdMapper, Readrecolrd> implements ReadrecolrdService {

    @Override
    public boolean batchInsert(ReadrecolrdDto dto) {
        if (dto == null || dto.getReadrecolrd() == null || dto.getReadrecolrd().isEmpty()) {
            throw new ToflyDeniedException("上传数据为空");
        }
        List<Readrecolrd> readrecolrd = dto.getReadrecolrd();
        for (Readrecolrd r : readrecolrd) {
            r.setUpdateTime(new Date());
            r.setFlag("1");
            save(r);
        }
        return true;
    }

    @Override
    public Page getInfo(Page page, ReadrecolrdDto dto) {
        String month = dto.getMonth();
        Long user = dto.getUser();
        Date start = StringUtils.isEmpty(dto.getStart()) ? null : DateUtil.parse(dto.getStart(), "yyyy-MM-dd HH:mm:ss");
        Date end = StringUtils.isEmpty(dto.getEnd()) ? null : DateUtil.parse(dto.getEnd(), "yyyy-MM-dd HH:mm:ss");
        String inputStr = dto.getInputStr();

        return page(page, Wrappers.<Readrecolrd>lambdaQuery().eq(!StringUtils.isEmpty(month), Readrecolrd::getCbyf, month)
                .eq(user != null, Readrecolrd::getCreateUserid, user)
                .between(start != null && end != null, Readrecolrd::getCreateDate, start, end)
                .and(!StringUtils.isEmpty(inputStr), q -> {
                    q.like(Readrecolrd::getYhbh, inputStr).or()
                            .like(Readrecolrd::getYhxm, inputStr).or()
                            .like(Readrecolrd::getSbbh, inputStr);
                }));
    }
}
