package cn.com.ty.lift.enterprise.oa.service;

import cn.com.ty.lift.enterprise.oa.dto.AttendanceRequest;
import cn.com.ty.lift.enterprise.oa.dto.AttendanceResponse;
import cn.com.ty.lift.enterprise.oa.entity.Attendance;
import cn.com.ty.lift.enterprise.oa.mapper.AttendanceMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 * 打卡签到记录 服务类
 * </p>
 *
 * @author wcz
 * @since 2019-12-12
 */
@Service
public class AttendanceService extends ServiceImpl<AttendanceMapper,Attendance> {

    /**
     * 根据条件分页查找签到记录
     * @param request AttendanceRequest
     * @return IPage<AttendanceResponse>
     */
    public IPage<AttendanceResponse> pageByCondition(AttendanceRequest request) {
        return baseMapper.pageByCondition(request.getPage(), request);
    }

    /**
     * 根据用户分页查找记录
     * @param request AttendanceRequest
     * @return IPage<AttendanceResponse>
     */
    public IPage<AttendanceResponse> pageByUser(AttendanceRequest request) {
        return baseMapper.pageByUser(request.getPage(), request);
    }

    public List<AttendanceResponse> listByIdList(AttendanceRequest request) {
        return baseMapper.listByIdList(request);
    }

    /**
     * 根据用户和打卡类型统计打卡记录条数
     * @param mtCompanyId 维保公司id
     * @param userId 用户id
     * @param type 打卡类型
     * @return int
     */
    public Attendance sameByUserAndType(Long mtCompanyId, Long userId, Integer type) {
        LambdaQueryWrapper<Attendance> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Attendance::getMtCompanyId, mtCompanyId);
        lambdaQueryWrapper.eq(Attendance::getUserId, userId);
        lambdaQueryWrapper.eq(Attendance::getType, type);
        //查询当天的打卡记录
        LocalDateTime today = LocalDateTime.now();
        lambdaQueryWrapper.between(Attendance::getCreateDate, today.with(LocalTime.MIN), today.with(LocalTime.MAX));
        lambdaQueryWrapper.last("LIMIT 1");
        return getOne(lambdaQueryWrapper);
    }

    /**
     * 根据id查询，带关联信息
     * @param request
     * @return
     */
    public AttendanceResponse infoById(AttendanceRequest request){
        return baseMapper.infoById(request);
    }

    public long countByMtCompany(Long mtCompanyId){
        LambdaQueryWrapper<Attendance> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Attendance::getMtCompanyId, mtCompanyId);
        return count(lambdaQueryWrapper);
    }
}