package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.dto.DeviceDto;
import com.aiotagro.cattletrade.business.dto.ServerLocationDto;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.JbqServer;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.JbqServerLogMapper;
import com.aiotagro.cattletrade.business.mapper.JbqServerMapper;
import com.aiotagro.cattletrade.business.service.IJbqServerService;
import com.aiotagro.cattletrade.business.vo.ServerClientVo;
import com.aiotagro.cattletrade.business.vo.ServerLocationVo;
import com.aiotagro.common.core.utils.DateUtils;
import com.aiotagro.common.core.utils.LngLonUtil;
import com.aiotagro.common.core.utils.StringUtils;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 智能主机表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-12-26
 */
@Service
public class JbqServerServiceImpl extends ServiceImpl<JbqServerMapper, JbqServer> implements IJbqServerService {

    @Autowired
    private JbqServerMapper jbqServerMapper;
    @Autowired
    private JbqServerLogMapper jbqServerLogMapper;
    @Autowired
    private DeliveryMapper deliveryMapper;
    @Override
    public PageResultResponse serverList(DeviceDto dto) {
        Page<ServerClientVo> result = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ServerClientVo> list = jbqServerMapper.serverList(dto);
        return new PageResultResponse(result.getTotal(), list);
    }

    @Override
    public AjaxResult serverLocation(ServerLocationDto dto) {
        if (!StringUtils.hasText(dto.getServerDeviceId())){
            return AjaxResult.error("主机编号不能为空");
        }
        LambdaQueryWrapper<JbqServer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JbqServer::getDeviceId, dto.getServerDeviceId());
        //查询主机数据
        JbqServer server = jbqServerMapper.selectOne(wrapper);
        if (server == null) {
            return AjaxResult.error("未找到对应的设备信息");
        }
        // 获取设备的经纬度
        String latitude = server.getLatitude();
        String longitude = server.getLongitude();

        // 判断经纬度是否为空或为0
        if (isInvalidLocation(latitude, longitude)) {
            return AjaxResult.error("暂无定位信息");
        }

        // 转换为百度经纬度
        double lat = Double.parseDouble(latitude);
        double lon = Double.parseDouble(longitude);
        double[] baiduLocation = LngLonUtil.gps84_To_bd09(lat, lon);

        ServerLocationVo serverLocationVo = new ServerLocationVo();
        serverLocationVo.setDeviceId(dto.getServerDeviceId());
        serverLocationVo.setLatitude(String.valueOf(baiduLocation[0]));
        serverLocationVo.setLongitude(String.valueOf(baiduLocation[1]));
        serverLocationVo.setUpdateTime(server.getUpdateTime());
        return AjaxResult.success(serverLocationVo);
    }

    @Override
    public AjaxResult serverTrack(ServerLocationDto dto) {
        if (dto.getDeliveryId() == null) {
            return AjaxResult.error("id不能为空");
        }
        if (!StringUtils.hasText(dto.getServerDeviceId())){
            return AjaxResult.error("主机编号不能为空");
        }
        //启运时间
        Delivery delivery = deliveryMapper.selectById(dto.getDeliveryId());
        if (delivery == null) {
            return AjaxResult.error("未找到相关运单信息");
        }

        Date deliverTime = delivery.getCreateTime();
        Date checkTime = (delivery.getCheckTime() != null) ? delivery.getCheckTime() :
                DateUtils.stringToDate(DateUtils.getTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);

        if (deliverTime == null) {
            return AjaxResult.error("启运时间为空");
        }
        // 轨迹
            List<ServerLocationVo> serverLocations = jbqServerLogMapper.selectServerLocationByTime(dto.getServerDeviceId(), deliverTime, checkTime);

            if (serverLocations != null && !serverLocations.isEmpty()) {
                // 过滤掉经纬度/坐标转换
                serverLocations = serverLocations.stream()
                        .filter(location -> {
                            return StringUtils.hasText(location.getLatitude())
                                    && StringUtils.hasText(location.getLongitude())
                                    && !"0".equals(location.getLatitude())
                                    && !"0".equals(location.getLongitude());
                        })
                        .peek(location -> {
                            double latitude = Double.parseDouble(location.getLatitude());
                            double longitude = Double.parseDouble(location.getLongitude());
                            double[] bd09 = LngLonUtil.gps84_To_bd09(latitude, longitude);

                            location.setLatitude(String.valueOf(bd09[0]));
                            location.setLongitude(String.valueOf(bd09[1]));
                        })
                        .collect(Collectors.toList());
                return AjaxResult.success(serverLocations);
            } else {
                return AjaxResult.error("没有找到符合条件的设备位置信息");
            }

    }



    public boolean isInvalidLocation(String latitude, String longitude) {
        return latitude == null || latitude.isEmpty() || "0".equals(latitude) ||
                longitude == null || longitude.isEmpty() || "0".equals(longitude);
    }
}
