package com.mosty.wzzx.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.mosty.base.model.dto.wzzx.LocationInfo;
import com.mosty.base.model.entity.wzzx.TbWzSswz;
import com.mosty.base.utils.CoordinateTransform;
import com.mosty.base.utils.DateUtils;
import com.mosty.common.base.domain.BaseController;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.wzzx.service.LocationInfoService;
import com.mosty.wzzx.service.impl.TbWzSswzServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @author ydb
 * 位置信息实体Controller
 * @since 2022年4月21日
 */
@RestController
@AllArgsConstructor
@RequestMapping("/gxga/locationInfo")
@Api(tags = "位置信息实体", value = "位置信息实体")
public class LocationInfoController extends BaseController {

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

    private final TbWzSswzServiceImpl tbWzSswzService;
    private final LocationInfoService locationInfoService;

    @PostMapping("/now")
    @ApiOperation(value = "根据条件获取当前最新一条位置信息", notes = "位置信息实体")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String"),
            @ApiImplicitParam(name = "accessNumber", value = "接入编号", dataType = "String")
    })
    public ResponseResult<TbWzSswz> getNowLoaction(String userId, String accessNumber) {
        Map<String, Object> requestMap = Maps.newHashMap();
        if (!StrUtil.isBlank(userId)) {
            requestMap.put("USER_ID", userId);
        }
        if (!StrUtil.isBlank(accessNumber)) {
            requestMap.put("ACCESS_NUMBER", accessNumber);
        }
        if (requestMap.isEmpty()) {
            return ResponseResult.fail("请确保至少传入一个查询参数");
        }
        return ResponseResult.success(tbWzSswzService.querySswzNow(userId, accessNumber));
    }

    /**
     * 获取位置信息实体详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiImplicitParam(name = "id", value = "参数键名", dataTypeClass = String.class, required = true, paramType = "path")
    @ApiOperation(value = "位置信息实体-详细信息", notes = "位置信息实体")
    public ResponseResult<TbWzSswz> queryById(@PathVariable("id") String id) {
        TbWzSswz sswz = this.tbWzSswzService.queryById(id);
        return ResponseResult.success(sswz);
    }

    /**
     * 新增位置信息实体
     */
    @PostMapping(value = "add")
    @ApiOperation(value = "新增位置信息实体", notes = "位置信息实体")
    public ResponseResult<LocationInfo> add(@Validated @RequestBody LocationInfo locationInfo, BindingResult result) {
        System.out.println(DateUtils.getQueryDateString(new Date(), "02") + "收到位置服务上报 ：{" + JSONObject.toJSONString(locationInfo) + "}");
        if (result.hasErrors() && result.getFieldError() != null) {
            return ResponseResult.fail(result.getFieldError().getDefaultMessage());
        }
        if (locationInfo.getLat() == 0 || locationInfo.getLng() == 0) {// 后台验证
            return ResponseResult.fail("报送错误! 定位坐标信息不能为空!");
        }
        if (StringUtils.isBlank(locationInfo.getUserId())) {
            return ResponseResult.fail("用户ID不存在，该位置不上报！");
        }
        locationInfo.setSourceName("移动设备");
        locationInfo.setSourceCode("02");
//        Long startTime = System.currentTimeMillis();
        //  入库之前将坐标进行转换
        locationInfo.setSourceLat(locationInfo.getLat());
        locationInfo.setSourceLng(locationInfo.getLng());
        double[] transfromPonint = CoordinateTransform.transformGCJ02ToWGS84(locationInfo.getLng(),
                locationInfo.getLat());
        // 只保留8位小数
        BigDecimal reLngBd = BigDecimal.valueOf(transfromPonint[0]);
        double reLngDouble = reLngBd.setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
        locationInfo.setLng(reLngDouble);
        // 只保留8位小数
        BigDecimal reLatBd = BigDecimal.valueOf(transfromPonint[1]);
        double reLatDouble = reLatBd.setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
        locationInfo.setLat(reLatDouble);
        //上传坐标转行
        if (locationInfo.getLastLng() != null && locationInfo.getLastLat() != null) {
            double[] lastTransfromPonint = CoordinateTransform.transformGCJ02ToWGS84(locationInfo.getLastLng(),
                    locationInfo.getLastLat());
            // 只保留8位小数
            BigDecimal lastReLngBd = BigDecimal.valueOf(lastTransfromPonint[0]);
            double lastReLngDouble = lastReLngBd.setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
            locationInfo.setLastLng(lastReLngDouble);
            // 只保留8位小数
            BigDecimal lastReLatBd = BigDecimal.valueOf(lastTransfromPonint[1]);
            double lastReLatDouble = lastReLatBd.setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
            locationInfo.setLastLat(lastReLatDouble);
        }
        if (locationInfo.getTime() == null) {
            locationInfo.setTime(new Date());
        }
        //实时存储位置
        locationInfoService.locationReceive(locationInfo);
        Long endTime = System.currentTimeMillis();
//        System.out.println("位置服务上报保存时长 ：{" + (endTime - startTime) + "}---用户{"+locationInfo.getUserId()+"}");
        locationInfo.setLastLat(locationInfo.getLat());
        locationInfo.setLastLng(locationInfo.getLng());
        return ResponseResult.success("添加成功", locationInfo);
    }
}
