package com.yx.face.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yx.face.boot.core.SnowflakeIdWorker;
import com.yx.face.boot.uitls.JsonUtils;
import com.yx.face.boot.uitls.RedisUtil;
import com.yx.face.service.FaceTBService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @description: AdminFaceController <br>
 * @date: 2021/6/2 12:44 <br>
 * @author: PWB <br>
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "C 天波人脸服务推送 API")
@RestController
public class TBFaceController {

    private final FaceTBService faceTBService;

    @ApiOperation("设备连接推送")
    @PostMapping("connect")
    public Map<String, Object> connect(HttpServletRequest request) {
        try {
            return faceTBService.connect(getParam(request));
        } catch (Exception e) {
            log.info("设备连接推送 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }


    @ApiOperation("设备断开推送")
    @PostMapping("disconnect")
    public Map<String, Object> disconnect(HttpServletRequest request) {
        try {
            return faceTBService.disconnect(getParam(request));
        } catch (Exception e) {
            log.info("设备断开推送 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }

    @ApiOperation("设备信息上报")
    @PostMapping("report")
    public Map<String, Object> report(HttpServletRequest request) {
        try {
            return faceTBService.report(getParam(request));
        } catch (Exception e) {
            log.info("设备信息上报 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }


    @ApiOperation("推送刷脸刷卡记录")
    @PostMapping("EventRecords")
    public Map<String, Object> EventRecords(HttpServletRequest request) {
        try {
            return faceTBService.eventRecords(getParam(request));
        } catch (Exception e) {
            log.info("推送刷脸刷卡记录 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }


    @ApiOperation("推送设备录入人员")
    @PostMapping("pushUsers")
    public Map<String, Object> pushUsers(HttpServletRequest request) {
        try {
            return faceTBService.pushUsers(getParam(request));
        } catch (Exception e) {
            log.info("推送设备录入人员 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;

    }

    @ApiOperation("推送设备人员删除信息")
    @PostMapping("delUser")
    public Map<String, Object> delUser(HttpServletRequest request) {

        try {
            return faceTBService.delUser(getParam(request));
        } catch (Exception e) {
            log.info("推送设备人员删除信息 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }

    @ApiOperation("上报任务结果处理")
    @PostMapping("pushTaskResult")
    public Map<String, Object> pushTaskResult(HttpServletRequest request) {
        try {
            return faceTBService.pushTaskResult(getParam(request));
        } catch (Exception e) {
            log.info("上报任务结果处理 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }


    @ApiOperation("批量上传人员")
    @PostMapping("syncUsers")
    public Map<String, Object> syncUsers(HttpServletRequest request) {
        try {
            return faceTBService.syncUsers(getParam(request));
        } catch (Exception e) {
            log.info("上报任务结果处理 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }

    @ApiOperation("获取任务ID")
    @PostMapping("getTaskId")
    public Map<String, Object> getTaskId(HttpServletRequest request) {
        try {
            return faceTBService.getTaskId(getParam(request));
        } catch (Exception e) {
            log.info("获取任务ID 异常={}", e.getMessage());
        }
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        result.put("taskId", SnowflakeIdWorker.getSnowId());
        return result;
    }


//    @ApiOperation("获取设备人员列表")
//    @PostMapping("pushUsersOnline")
//    public Map<String, Object> pushUsersOnline(HttpServletRequest request) {
////        List<Map<String, String>> list = new ArrayList<>();
////        try {
////            JSONObject paramJson = getParamJson(request);
////            JSONArray data = paramJson.getJSONArray("data");
////            for (Object datum : data) {
////                Map<String, String> map = new HashMap<>();
////                map.put(JSONObject.parseObject(datum.toString()).getString("cardid"), paramJson.getString("SN"));
////                map.put("SN", paramJson.getString("SN"));
////                map.put("taskId", paramJson.getString("taskId"));
////                    list.add(map);
////            }
////            if (!list.isEmpty()){
////                faceTBService.pushUsersOnline(list);
////            }
////        } catch (Exception e) {
////            log.info("推送刷脸刷卡记录 异常={}", e.getMessage());
////        }
//        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
//        result.put("errCode", "00");
//        return result;
//    }


//    private JSONObject getParamJson(HttpServletRequest request) {
//        StringBuilder sb = new StringBuilder();
//        try (InputStream is = request.getInputStream();
//             BufferedInputStream bis = new BufferedInputStream(is)) {
//            byte[] buffer = new byte[1024];
//            int read;
//            while ((read = bis.read(buffer)) != -1) {
//                sb.append(new String(buffer, 0, read, StandardCharsets.UTF_8));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String paramStr = sb.toString();
//        JSONObject jsonObject = JSONObject.parseObject(paramStr);
//        return jsonObject;
//    }


    private Map<String, Object> getParam(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (InputStream is = request.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = bis.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, read, StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            return Collections.EMPTY_MAP;
        }
        String paramStr = sb.toString();
        if (!StringUtils.hasText(paramStr)) {
            return Collections.EMPTY_MAP;
        }
        return JsonUtils.toMap(paramStr);
    }


}
