package com.cxyxiaomo.epp.access.controller;

import com.cxyxiaomo.epp.access.rpc.UserServiceFeign;
import com.cxyxiaomo.epp.access.service.ReportServiceImpl;
import com.cxyxiaomo.epp.common.pojo.Report;
import com.cxyxiaomo.epp.common.pojo.User;
import com.cxyxiaomo.epp.common.response.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Calendar;
import java.util.List;

@Controller
@RequestMapping("/access/report")
public class ReportController {

    @Autowired
    private UserServiceFeign userService;

    @Autowired
    private ReportServiceImpl reportService;

    /**
     * 体温上报
     *
     * @param id
     * @param address
     * @param timestamp
     * @param temperature
     * @return
     */
    @PostMapping("/submit")
    @ResponseBody
    public Res submit(@RequestParam("userId") Integer id,
                      @RequestParam("address") String address,
                      @RequestParam("timestamp") Long timestamp,
                      @RequestParam("temperature") Integer temperature) {
        User user = userService.getUserById(id);
        if (user == null) {
            return Res.error("用户不存在");
        }

        // 查询数据库，判断当天是否已经填报过

        Calendar instance = Calendar.getInstance();
        instance.setTimeInMillis(timestamp);

        Report report = new Report();
        report.setAddress(address);
        report.setName(user.getRealname());
        report.setTime(instance.getTime());
        report.setUserId(user.getId());
        report.setTemperature(temperature);

        reportService.addRecord(report);

        return Res.success();
    }

    /**
     * 获取用户填报信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/getRecordList")
    @ResponseBody
    public Res getRecordList(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Res.error("用户不存在");
        }
        List<Report> records = reportService.getRecordListByUserId(user.getId());
        return Res.success(records);
    }
    /**
     * 获取最近一次用户填报信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/getLatestRecord")
    @ResponseBody
    public Res getLatestRecord(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Res.error("用户不存在");
        }
        Report records = reportService.getLatestRecordByUserId(user.getId());
        return Res.success(records);
    }
}
