package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.system.domain.TUserGps;
import com.zehong.system.mapper.TUserGpsMapper;
import com.zehong.system.service.ITUserGpsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author zehong
 * @date 2024-02-29
 */
@Service
public class TUserGpsServiceImpl implements ITUserGpsService 
{
    private static final Logger logger = LoggerFactory.getLogger(TUserGpsServiceImpl.class);
    @Autowired
    private TUserGpsMapper tUserGpsMapper;

    @Value("${gps.currentTrack}")
    private String gpsCurrentTrack;

    @Value("${gps.historyTrack}")
    private String gpsHistoryTrack;

    @Value("${gps.moreDeviceTrack}")
    private String moreDeviceTrack;


    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public TUserGps selectTUserGpsById(Long id)
    {
        return tUserGpsMapper.selectTUserGpsById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param tUserGps 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TUserGps> selectTUserGpsList(TUserGps tUserGps){
        List<TUserGps> userGpsList = tUserGpsMapper.selectTUserGpsList(tUserGps);
        String ids = userGpsList.stream().map(item -> item.getImei()).collect(Collectors.joining(","));
        if(StringUtils.isNotEmpty(ids)){
            JSONArray gpsInfo = moreDeviceTrack("ids=" + ids + "&mapType=gaode&key=20161222HLXTJDMW730XY");
            //防止有人员与设备重复绑定遍历赋值
            gpsInfo.stream().forEach(deviceInfo ->{
                userGpsList.stream().filter(item -> item.getImei().equals(((JSONObject) deviceInfo).getString("sn"))).forEach(item ->{
                    item.setPositionTime(((JSONObject)deviceInfo).getString("positionTime"));
                    item.setSpeed(((JSONObject)deviceInfo).getString("speed"));
                    item.setLocateMethod(getLocationMethod(((JSONObject)deviceInfo).getString("isGPS")));
                    String[] status = ((JSONObject)deviceInfo).getString("status").split("-");
                    item.setStatus(StringUtils.isNotEmpty(status[0]) ? getStatus((status[0])) : "未知");
                    item.setElectricQuan((status.length > 1 && StringUtils.isNotEmpty(status[1])) ? status[1].substring(3) : "未知");
                });
            });
        }
        return userGpsList;
    }

    /**
     * 获取gps更多设备信息
     * @param param 入参格式name=value&age=1
     * @return
     */
    private JSONArray moreDeviceTrack(String param){
        try{
            String result = HttpUtils.sendGet(moreDeviceTrack,param);
            JSONObject resultJson = JSON.parseObject(result);
            if(StringUtils.isNotEmpty(result) && "0".equals(resultJson.getString("state"))){
                return JSONArray.parseArray(resultJson.getString("devices"));
            }
            logger.info("获取更多设备gps信息返回信息:",result);
            return  new JSONArray();
        }catch (Throwable e){
            logger.error("获取更多设备gps信息接口错误",e);
            return new JSONArray();
        }
    }

    /**
     * gps状态
     * @param status 状态码
     * @return
     */
    private String getStatus(String status){
        switch (status){
            case "0":
                return "未启用";
            case "1":
                return "运动";
            case "2":
                return "静止";
            case "3":
                return "离线";
            default:
                return "";
        }
    }

    /**
     * gps定位方式
     * @param locationCode 定位方式码
     * @return
     */
    private String getLocationMethod(String locationCode){
        switch (locationCode){
            case "0":
                return "LBS";
            case "1":
                return "GPS";
            case "2":
                return "WIFI";
            default:
                return "";
        }
    }

    /**
     * 获取当前位置
     * @param id 设备编号
     * @return
     */
    @Override
    public JSONObject getCurrentLocation(String id){
        try{
            String result = HttpUtils.sendGet(gpsCurrentTrack,"id="+ id +"&mapType=gaode&key=20161222HLXTJDMW730XY");
            JSONObject resultJson = JSON.parseObject(result);
            if(StringUtils.isNotEmpty(result) && "0".equals(resultJson.getString("state"))){
                return resultJson;
            }
            logger.info("获取当前位置信息失败:", result);
            return null;
        }catch (Throwable a){
            logger.error("获取当前定位接口失败:",a);
            return null;
        }
    }


    /**
     * 获取用户当前位置
     * @return
     */
    @Override
    public JSONObject getCurrentLocationByUser() throws Exception {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        TUserGps tUserGps = new TUserGps();
        tUserGps.setUserId(userId);
        List<TUserGps> tUserGpsList = tUserGpsMapper.selectTUserGpsList(tUserGps);
        if(CollectionUtils.isEmpty(tUserGpsList)) throw new CustomException("用户未绑定设备");
        return getCurrentLocation(tUserGpsList.get(0).getImei());
    }

    /**
     * 定位历史轨迹
     * @param id 设备编号
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public JSONObject historyTrack(String id,String startTime,String endTime){
        try{
            String result = HttpUtils.sendGet(gpsHistoryTrack, "id="+ id +"&mapType=gaode&key=20161222HLXTJDMW730XY&startTime="+ startTime.replace(" ","%20") +"&endTime=" + endTime.replace(" ","%20"));
            JSONObject resultJson = JSON.parseObject(result);
            if(StringUtils.isNotEmpty(result) && "0".equals(resultJson.getString("state"))){
                JSONArray devices = resultJson.getJSONArray("devices");
                List<List<String>> historyTrack = new ArrayList<>();
                devices.stream().forEach(item ->{
                    List<String> track = new ArrayList<>();
                    JSONObject device = (JSONObject)item;
                    track.add(device.getString("lng"));
                    track.add(device.getString("lat"));
                    historyTrack.add(track);
                });
                resultJson.put("historyTrack",historyTrack);
                return resultJson;
            }
            if(StringUtils.isNotEmpty(result) && "2002".equals(resultJson.getString("state"))){
                return resultJson;
            }
            logger.info("获取历史轨迹信息失败:", result);
            return null;
        }catch (Throwable a){
            logger.error("获取历史轨迹接口失败:",a);
            return null;
        }
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param tUserGps 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTUserGps(TUserGps tUserGps){
        TUserGps userGpsInfo = new TUserGps();
        userGpsInfo.setUserId(tUserGps.getUserId());
        List<TUserGps> userGpsList = tUserGpsMapper.selectTUserGpsList(userGpsInfo);
        if(!CollectionUtils.isEmpty(userGpsList)){
            userGpsList.get(0).setImei(tUserGps.getImei());
            return updateTUserGps(userGpsList.get(0));
        }
        tUserGps.setCreateTime(DateUtils.getNowDate());
        return tUserGpsMapper.insertTUserGps(tUserGps);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param tUserGps 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTUserGps(TUserGps tUserGps){
        return tUserGpsMapper.updateTUserGps(tUserGps);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteTUserGpsByIds(Long[] ids)
    {
        return tUserGpsMapper.deleteTUserGpsByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteTUserGpsById(Long id)
    {
        return tUserGpsMapper.deleteTUserGpsById(id);
    }
}
