package cn.edu.whu.boot.allocation.controllers;


import cn.edu.whu.boot.allocation.entities.RouteLine;
import cn.edu.whu.boot.allocation.services.RouteLineService;
import cn.edu.whu.boot.allocation.services.TaskUserRoleService;
import cn.edu.whu.boot.collection.dto.Feature;
import cn.edu.whu.boot.collection.dto.GeometryType;
import cn.edu.whu.boot.common.domain.CommonConstant;
import cn.edu.whu.boot.common.domain.ResultMessage;
import cn.edu.whu.boot.common.utils.collection.PostgreSqlUtil;
import cn.edu.whu.boot.user.entities.User;
import cn.edu.whu.boot.user.services.UserService;
import cn.edu.whu.boot.xml.domain.Task;
import cn.edu.whu.boot.xml.service.ITaskService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.validation.constraints.NotEmpty;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("route")
public class RouteLineController {

    @Autowired
    private RouteLineService routeLineService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskUserRoleService taskUserRoleService;

    private static Logger logger = LoggerFactory.getLogger(RouteLineController.class);

    /**
     * 上传轨迹数据
     * @param detail 轨迹数据，格式为 JSON 字符串
     */
    @RequestMapping(value="insert",produces="text/html;charset=UTF-8")
    public String uploadRoute(@RequestParam("detail") @NotEmpty(message = "数据不能为空") String detail)
    {

        JSONObject jsonObject = JSON.parseObject(detail);
        int taskId = jsonObject.getInteger("taskId");
        JSONObject routeLineJsonObj = jsonObject.getJSONObject("routeLine");
        RouteLine routeLine = JSON.toJavaObject(routeLineJsonObj, RouteLine.class);
        routeLine.setUploadTime(new Date());
        byte[] result = Base64.getDecoder().decode(routeLine.getPolyline());

        // routeLine的Polyline为标准的GeoJson格式，主要是方便网页端获取,要判断前端传来的是path还是point
        Feature feature = new Feature();
        feature.setType(CommonConstant.FEATURE);
        GeometryType geometryType = new GeometryType();
        JSONObject shapeJson = JSON.parseObject(new String(result));
        if (shapeJson.containsKey(CommonConstant.PATHS)){
            geometryType.setType(CommonConstant.LINESTRING);
            List<List<Double>> pathList = ((List<List<List<Double>>>)shapeJson.get(CommonConstant.PATHS)).get(0);
            geometryType.setCoordinates(pathList);
        }
        else{
            geometryType.setType(CommonConstant.POINT);
            List<Double> coordinateList = new ArrayList<>();
            coordinateList.add(shapeJson.getDouble(CommonConstant.X));
            coordinateList.add(shapeJson.getDouble(CommonConstant.Y));
            geometryType.setCoordinates(coordinateList);
        }
        feature.setGeometry(geometryType);
        routeLine.setPolyline(JSON.toJSONString(feature));
        Task task = taskService.getTaskById(taskId);
        routeLineService.insertRouteLine(PostgreSqlUtil.transformString(task.getDatabaseName()), routeLine);
        return new ResultMessage(true, "轨迹上传成功").toString();
    }

    /**
     * 获取某个任务下所有工作人员的名单
     * @param taskId 任务id
     */
    @RequestMapping(value="getWorkerForTask",produces="text/html;charset=UTF-8")
    public String getWorkerForTask(Integer taskId)
    {
        List<Map<String, String>> result = taskService
                .getWorkersByTask(taskId)
                .stream()
                .map(user -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("userId", String.valueOf(user.getId()));
                    map.put("userName", user.getUsername());
                    return map;
                })
                .collect(Collectors.toList());
        return result.isEmpty() ? new ResultMessage<>(false,"该任务下无工作人员", null).toString() : new ResultMessage<>(true,CommonConstant.SUCCEED, result).toString();
    }

    /**
     * 获取某用户id在某个时间段内的轨迹数据，并以标准的Feature格式传给前端。数据库中的记录只要与该时间端相交就返回
     * @param taskId    任务Id
     * @param userId    用户Id
     * @param beginTime 开始时间
     * @param stopTime  结束时间
     */
    @RequestMapping(value="getRouteByUserId",produces="text/html;charset=UTF-8")
    public String getRoute(Integer taskId, Integer userId, String beginTime, String stopTime)
    {
        Task task = taskService.getTaskById(taskId);
        User user = userService.findById(userId).get();
        List<RouteLine> routeLineStringList;
        if (beginTime != null && !beginTime.equals("") && stopTime != null && !stopTime.equals(""))
        {
            routeLineStringList = routeLineService.findByNameAndTime(PostgreSqlUtil.transformString(task.getDatabaseName()),
                                                                     user.getUsername(), beginTime, stopTime);
        }
        else
        {
            routeLineStringList = routeLineService.findByName(PostgreSqlUtil.transformString(task.getDatabaseName()),
                                                              user.getUsername());
        }
        if (routeLineStringList == null)
        {
            return new ResultMessage<>(false, "轨迹为空", null).toString();
        }
        else
        {
            return new ResultMessage<>(true, CommonConstant.SUCCEED, routeLineStringList).toString();
        }
    }

}
