package com.sqx.modules.driver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.driver.dao.DriverDao;
import com.sqx.modules.driver.dao.DriverRouteDao;
import com.sqx.modules.driver.entity.Driver;
import com.sqx.modules.driver.entity.DriverRoute;
import com.sqx.modules.driver.service.DriverRouteService;
import com.sqx.modules.driver.service.DriverService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.orders.utils.LocationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
@Service
public class DriverRouteServiceImp extends ServiceImpl<DriverRouteDao, DriverRoute> implements DriverRouteService {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private DriverService driverService;

    @Override
    public Result insertDriverRoute(DriverRoute driverRoute){
        Driver driver = driverService.selectDriverByUserId(driverRoute.getUserId());
        if(driver.getStatus()!=2){
            return Result.error("实名审核未通过！");
        }
        driverRoute.setCreateTime(DateUtils.format(new Date()));
        driverRoute.setStatus(1);
        baseMapper.insert(driverRoute);
        return Result.success();
    }

    @Override
    public IPage<DriverRoute> selectDriverRouteListByUserId(Integer page,Integer limit,Long userId){
        return baseMapper.selectPage(new Page<>(page,limit),new QueryWrapper<DriverRoute>().eq("status",1).eq("user_id",userId).orderByDesc("create_time"));
    }

    @Override
    public Result selectDriverRouteList(Integer page, Integer limit, String shipProvince, String shipCity, String shipDistrict, String shipAddress,
                                                    String deliveryProvince, String deliveryCity, String deliveryDistrict, String deliveryAddress,
                                                    String userName, String phone,Long ordersId,Long userId,Integer status,String driverName,Integer isHighSpeedPrice){
        IPage<DriverRoute> driverRouteIPage = baseMapper.selectDriverRouteList(new Page<>(page, limit), shipProvince, shipCity, shipDistrict, shipAddress, deliveryProvince,
                deliveryCity, deliveryDistrict, deliveryAddress, userName, phone,ordersId,userId,status,driverName,isHighSpeedPrice);
        if(ordersId!=null){
            Orders orders = ordersService.getById(ordersId);
            for(DriverRoute driverRoute:driverRouteIPage.getRecords()){
                double[] start1 = {Double.parseDouble(driverRoute.getShipAddressLatitude()), Double.parseDouble(driverRoute.getShipAddressLongitude())};
                double[] end1 = {Double.parseDouble(driverRoute.getDeliveryAddressLatitude()), Double.parseDouble(driverRoute.getDeliveryAddressLongitude())};
                double[] start2 = {Double.parseDouble(orders.getShipAddressLatitude()), Double.parseDouble(orders.getShipAddressLongitude())};
                double[] end2 = {Double.parseDouble(orders.getDeliveryAddressLatitude()), Double.parseDouble(orders.getDeliveryAddressLongitude())};
                BigDecimal similarity = LocationUtils.calculateRouteSimilarity(start1, end1, start2, end2);
                driverRoute.setSimilarity(similarity.setScale(0,BigDecimal.ROUND_DOWN));
                driverRoute.setDriver(driverService.getById(driverRoute.getDriverId()));
                Double startDistance = LocationUtils.calculateDistanceUsingHaversine(start1, start2);
                Double endDistance = LocationUtils.calculateDistanceUsingHaversine(end1, end2);

                driverRoute.setStartDistance(BigDecimal.valueOf(startDistance).setScale(2,BigDecimal.ROUND_DOWN));
                driverRoute.setEndDistance(BigDecimal.valueOf(endDistance).setScale(2,BigDecimal.ROUND_DOWN));

            }
        }
        return Result.success().put("data",new PageUtils(driverRouteIPage));
    }

    @Override
    public Result insertMessageByDriver(Long ordersId,Long driverRouteId) {
        Orders orders = ordersService.getById(ordersId);
        DriverRoute driverRoute = baseMapper.selectById(driverRouteId);
        MessageInfo messageInfo = messageService.getOne(new QueryWrapper<MessageInfo>()
                .eq("platform", ordersId).eq("state", 4).eq("user_id", driverRoute.getUserId()));
        if (messageInfo != null) {
            return Result.error("已经邀请过车主了！");
        }
        messageInfo = new MessageInfo();
        messageInfo.setTitle("邀请接单");
        UserEntity user = userService.getById(orders.getUserId());
        UserEntity driverUser = userService.getById(driverRoute.getUserId());
        messageInfo.setContent("用户“" + user.getNickName() + "”邀请您接单，单号：" + orders.getOrdersNo());
        messageInfo.setState("6");
        messageInfo.setUserId(driverRoute.getUserId().toString());
        messageInfo.setType("1");
        messageInfo.setPlatform(driverRouteId.toString());
        messageInfo.setIsSee("0");
        messageInfo.setUserName(driverUser.getNickName());
        messageInfo.setCreateAt(DateUtils.format(new Date()));
        messageInfo.setOrdersId(ordersId);
        messageService.save(messageInfo);
        return Result.success();
    }

}
