package lingtao.net.controller;

import com.github.pagehelper.PageHelper;
import lingtao.net.bean.Msg;
import lingtao.net.bean.UpdateLog;
import lingtao.net.service.UpdateLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
public class UpdateLogControllef {

	@Autowired
	private UpdateLogService updateLogService;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@RequestMapping("/getUpdateLogs")
	public Msg getUpdateLogs(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, UpdateLog updateLog) {
		PageHelper.startPage(page, limit);
		List<UpdateLog> updateLogList = updateLogService.getUpdateLogs(updateLog);
		for (UpdateLog log : updateLogList) {
			log.setAddTimeStr(sdf.format(log.getAddTime()));
		}
		return Msg.success().add("list", updateLogList);
	}

	/**
	 * 添加更新日志
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/addLog")
	public Msg addLog(UpdateLog updateLog, HttpSession session) throws Exception {
		// 把字符串转为日期格式
		updateLog.setAddTime(sdf.parse(updateLog.getAddTimeStr()));
		updateLogService.addLog(updateLog, session);
		// 更新日志后，把所有用户的阅读更新日志状态改为未读:0
		updateLogService.changeReadLogStatus();
		return Msg.success();
	}

	/**
	 * 修改更新日志
	 */
	@RequestMapping("/updateLog")
	public Msg updateLog(UpdateLog updateLog, HttpSession session) {
		updateLogService.updateLogById(updateLog, session);
		return Msg.success();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/deleteLog")
	public Msg deleteLog(@RequestParam("id") Integer id) {
		updateLogService.deleteLogById(id);
		return Msg.success();
	}
}
