package com.wisedu.mooc.app.log.service.impl;

import com.wisedu.coeus.core.db.PageMaker;
import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.util.DateUtils;
import com.wisedu.mooc.app.log.bo.LogUserVisit;
import com.wisedu.mooc.app.log.bo.LogUserVisitPos;
import com.wisedu.mooc.app.log.dao.LogUserVisitDao;
import com.wisedu.mooc.app.log.service.LogUserVisitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("logUserVisitService")
public class LogUserVisitServiceImpl implements LogUserVisitService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogUserVisitServiceImpl.class);

    @Autowired
    private LogUserVisitDao logUserVisitDao;

    @Override
    public void insertLog(LogUserVisit logUserVisit, LogUserVisitPos logUserVisitPos) {
        logUserVisitDao.insertLog(logUserVisit, logUserVisitPos);
    }

    @Override
    public void queryLogUserVisit(Map<String, Object> resultMap, Long userId, String searchKey, Integer periodType, Integer orderType, int pageIndex, int pageSize) {
        PageMaker pageMaker = this.logUserVisitDao.queryLogUserVisit(userId, searchKey, periodType, orderType, pageIndex, pageSize);
        List<LogUserVisit> logUserVisits = pageMaker.getList();
        for (LogUserVisit logUserVisit : logUserVisits) {
            Integer visitDuration = logUserVisit.getVisitDuration();
            if (null != visitDuration) {
                logUserVisit.setUseTime(DateUtils.turnSecondsToTimestring(visitDuration / 1000));
            }
        }

        resultMap.put("pageMaker", pageMaker);

        Long visitPages = this.logUserVisitDao.countVisitPages(userId, searchKey, periodType);
        if (null == visitPages) {
            visitPages = 0L;
        }
        resultMap.put("visitPages", visitPages);
        Long visitTimes = this.logUserVisitDao.sumVisitTimes(userId, searchKey, periodType);
        if (null == visitTimes) {
            visitTimes = 0L;
        }
        resultMap.put("visitTimes", DateUtils.turnSecondsToTimestring(visitTimes / 1000));

        resultMap.put("userId", userId);
    }

    @Override
    public void queryUserVisitPoss(Map<String, Object> resultMap, String logId) {
        LogUserVisit userVisit = this.logUserVisitDao.queryUserVisit(logId);
        List<LogUserVisitPos> userVisitPoss = this.logUserVisitDao.queryUserVisitPoss(logId);
        for (LogUserVisitPos userVisitPos : userVisitPoss) {
            Integer visitDuration = userVisitPos.getVisitDuration();
            if (null != visitDuration) {
                userVisitPos.setUseTime(DateUtils.turnSecondsToTimestring(visitDuration / 1000));
            }
        }

        resultMap.put("userVisit", userVisit);
        resultMap.put("userVisitPoss", userVisitPoss);
    }
}
