package com.ylcm.sys.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ylcm.sys.common.DateUtil;
import com.ylcm.sys.domain.Log;
import com.ylcm.sys.mapper.LogMapper;
import com.ylcm.sys.service.LogService;

@Service
public class LogServiceImpl implements LogService {

	@Autowired
	LogMapper logMapper;

	@Override
	public void saveLog(String type, String login, String name, String ip, String content) {
		Log record = new Log();
		record.setLogin(login);
		record.setType(type);
		record.setName(name);
		record.setIp(ip);
		record.setContent(content);
		record.setCrtTime(new Date());

		this.logMapper.insert(record);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<Log> getLogList(String login, String startDate, String endDate, String pageSize, String pageNo) {
		Map map = new HashMap<>();
		map.put("login", login);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("pageSize", StringUtils.isNotBlank(pageSize) ? Integer.valueOf(pageSize) : null);
		Integer offSet = StringUtils.isNotBlank(pageNo) ? (Integer.valueOf(pageNo) - 1) * Integer.valueOf(pageSize) : null;
		map.put("offSet", offSet);

		return this.logMapper.selectByCondition(map);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Integer getLogCount(String login, String startDate, String endDate) {
		Map map = new HashMap<>();
		map.put("login", login);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		return this.logMapper.getCount(map);
	}

	@Override
	public Workbook createExcelForLog(List<Log> logs) {
		String[] heads = {"账号","内容", "ip地址", "登录时间" };
		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建工作表
		HSSFSheet sheet = wb.createSheet("系统日志");
		HSSFRow row = sheet.createRow(0);
		HSSFCellStyle style = wb.createCellStyle();

		// 设置表头
		for (int i = 0; i < heads.length; i++) {
			style.setAlignment(HorizontalAlignment.CENTER);
			// 创建一个居中格式
			row.setRowStyle(style);
			row.createCell(i).setCellValue(heads[i]);
		}
		
		// 插入数据
		for(int i = 0; i< logs.size(); i++){
			Log log = logs.get(i);
			row = sheet.createRow(i + 1);
			row.createCell(0).setCellValue(log.getLogin());
			row.createCell(1).setCellValue(log.getContent());
			row.createCell(2).setCellValue(log.getIp());
			row.createCell(3).setCellValue(DateUtil.date2Str(log.getCrtTime(), "yyyy-MM-dd HH:mm:ss"));
		}
		return wb;
	}
}
