package com.judong.chuanyiserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.judong.chuanyiserver.dao.LogDao;
import com.judong.chuanyiserver.entity.Log;
import com.judong.chuanyiserver.enums.ResultEnum;
import com.judong.chuanyiserver.service.LogService;
import com.judong.chuanyiserver.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional
public class LogServiceImpl implements LogService {

    @Autowired
    private LogDao logDao;

    @Override
    public Result getLogPage(int page, int limit, String serverName, String modelName, String content, String userId,String ipAddress, String methodName,String startDate,String endDate) {
        JSONObject jsonObject = new JSONObject();
        Long count = logDao.getLogCount(serverName, modelName, content, userId,ipAddress, methodName,startDate,endDate);
        Long startNum = Long.valueOf((page - 1) * limit);
        List<Log> logList = logDao.getLogPage(startNum, Long.valueOf(limit), serverName, modelName, content, userId,ipAddress, methodName,startDate,endDate);
        jsonObject.put("count", count);
        jsonObject.put("logList", logList);
        return Result.ok(jsonObject);
    }

    @Override
    public Result insertLog(Log log) {
        if (logDao.insertLog(log) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "添加日志失败");
        }
        return Result.ok("添加日志成功");
    }

    @Override
    public Result logDeleteByTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MONDAY,-6);
        String date = simpleDateFormat.format(instance.getTime());
        return Result.ok(logDao.logDeleteByTime(date));
    }
}
