package com.qmth.paper.library.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.business.bean.result.ScanStatExportResult;
import com.qmth.paper.library.business.bean.result.ScanStatResult;
import com.qmth.paper.library.business.entity.PaperLibrary;
import com.qmth.paper.library.business.mapper.PaperLibraryMapper;
import com.qmth.paper.library.business.service.PaperLibraryService;
import com.qmth.paper.library.business.service.PaperScanStatService;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.service.SysUserService;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class PaperScanStatServiceImpl extends ServiceImpl<PaperLibraryMapper, PaperLibrary> implements PaperScanStatService {

    private final Logger logger = LoggerFactory.getLogger(PaperScanStatServiceImpl.class);

    @Resource
    private PaperLibraryService paperLibraryService;

    @Resource
    private SysUserService sysUserService;

    @Override
    public IPage<ScanStatResult> pageScanStat(Long scanDate, String scanner, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        //日期转换
        String scanDateStr = null;
        if(scanDate != null && scanDate > 0) {
            scanDateStr = DateFormatUtils.format(scanDate, SystemConstant.SHORT_DATE_PATTERN);
        }

        //获取查询条件中的用户
        Long userId = getUserId(scanner);

        IPage<ScanStatResult> scanStatPage = baseMapper.listScanStat(new Page<>(pageNumber, pageSize), schoolId, scanDateStr, userId);
        for (ScanStatResult scanStatResult : scanStatPage.getRecords()) {
            //设置扫描学生数
            int studentCount = paperLibraryService.countScanStudentByScannerAndDate(schoolId, scanStatResult.getCreateId(), scanStatResult.getScanDateStr());
            scanStatResult.setStudentCount(studentCount);
            SysUser user = sysUserService.getById(scanStatResult.getCreateId());
            scanStatResult.setScanner(Objects.isNull(user) ?  null : user.getLoginName()+"(" + user.getRealName()+")");
        }
        return scanStatPage;
    }

    @Override
    public List<ScanStatExportResult> listScanStat(Long scanDate, String scanner) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        String scanDateStr = null;
        if(scanDate != null && scanDate > 0) {
            scanDateStr = DateFormatUtils.format(scanDate, SystemConstant.SHORT_DATE_PATTERN);
        }

        //获取查询条件中的用户
        Long userId = getUserId(scanner);

        List<ScanStatExportResult> scanStatList = baseMapper.listScanStatExport(schoolId, scanDateStr, userId);
        for(ScanStatExportResult scanStatExportResult : scanStatList) {
            //设置扫描学生数
            int studentCount = paperLibraryService.countScanStudentByScannerAndDate(schoolId, scanStatExportResult.getCreateId(), scanStatExportResult.getScanDateStr());
            scanStatExportResult.setStudentCount(studentCount);
            SysUser user = sysUserService.getById(scanStatExportResult.getCreateId());
            scanStatExportResult.setScanner(Objects.isNull(user) ?  null : user.getLoginName()+"(" + user.getRealName()+")");
        }

        return scanStatList;
    }

    private @Nullable Long getUserId(String scanner) {
        Long userId = null;
        if (StringUtils.isNotEmpty(scanner)) {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getLoginName, scanner.trim());
            SysUser user = sysUserService.getOne(queryWrapper);
            if (user != null) {
                userId = user.getId();
            } else {
                userId = -1L;
            }
        }
        return userId;
    }

    private Long getLongDate(String dateStr) {
        Date date;
        try {
            date = DateUtils.parseDate(dateStr+" 00:00:00", SystemConstant.DEFAULT_DATE_PATTERN);
        } catch (ParseException e) {
            logger.error(String.format("[扫描统计管理]日期转换失败,dateStr:%s", dateStr), e);
            return null;
        }
        return date.getTime();
    }

}
