package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.OverviewService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
public class OverviewController {

    @Resource
    OverviewService overviewService;

    @GetMapping("/homepage/countStats")
    public String getCountStats() {
        ReturnT<JSONObject> returnT;
        try {
            returnT = new ReturnT<>(200, "", overviewService.getHomepageStats());
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/homepage/dategroup")
    public String getItemCountGroupByDate(@RequestBody String params) {
        ReturnT<Object> returnT;
        JSONArray resultMap = overviewService.getItemCountGroupByDate(params);
        returnT = new ReturnT<>(200, "", resultMap);
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/homepage/dategroup")
    public String getItemCountGroupByDate() {
        ReturnT<Object> returnT;
        JSONArray resultMap = overviewService.getItemCountGroupByDate();
        returnT = new ReturnT<>(200, "", resultMap);
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/homepage/taskgroup")
    public String getItemCountGroupByTask(@RequestBody String params) {
        ReturnT<Object> returnT;
        JSONObject paramObj = JSONObject.parseObject(params);
        Date startTime = new Date(paramObj.getLong("startTime"));
        Date endTime = new Date(paramObj.getLong("endTime"));
        List<List<Object[]>> resultMap = overviewService.getItemCountGroupByTask(startTime, endTime);
        returnT = new ReturnT<>(200, "", resultMap);
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/homepage/taskgroup")
    public String getItemCountGroupByTask() {
        ReturnT<Object> returnT;
        Date endTime = new Date();
        Date startTime = new Date(endTime.getTime() - 24 * 3600 * 1000);
        List<List<Object[]>> resultMap = overviewService.getItemCountGroupByTask(startTime, endTime);
        returnT = new ReturnT<>(200, "", resultMap);
        return JSON.toJSONString(returnT);
    }

}
