package com.sqx.scheduler.indent;

import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.scheduler.config.SchedulerLock;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 跑腿订单定时任务
 *
 * @author : codingliang
 * @date : 2024-09-09 12:28
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IndentScheduler {

    private final CommonInfoService commonInfoService;
    private final TbIndentDao tbIndentDao;
    private final GoodsShopDao goodsShopDao;
    private final UserService userService;
    private final UserDao userDao;

    private final RedissonClient redissonClient;

    /**
     * 定时自动给骑手推单
     * 每分钟运行一次
     */
    @Async
    @Scheduled(cron = "0 * * * * ?", zone = "Asia/Shanghai")
    public void autoSendOrder(){
        RLock lock = redissonClient.getLock(SchedulerLock.INDENT_AUTO_PUSH_LOCK);
        lock.lock();
        try {
            log.info("自动给骑手推单任务开始运行");
            CommonInfo three = commonInfoService.findOne(304);
            if("是".equals(three.getValue())){
                //查看所有支付以后两分钟后的订单（排除同城服务订单）
                CommonInfo two = commonInfoService.findOne(302);
                CommonInfo one = commonInfoService.findOne(303);
                CommonInfo four = commonInfoService.findOne(273);
                CommonInfo five = commonInfoService.findOne(310);
                Integer maxNum = Integer.parseInt(commonInfoService.findOne(342).getValue());
                Double cashDeposit = Double.valueOf(four.getValue());
                Double distance = Double.valueOf(one.getValue());
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                String date = getCurrentTime(Integer.valueOf(two.getValue()));
                List<TbIndent> tbIndents = tbIndentDao.selectSendOrder(date);
                //遍历这些订单，查出距离这些订单最近的骑手（骑手需要没有接单，且在订单位置xx米内）
                for(int i = 0;i<tbIndents.size();i++){
                    GoodsShop goodsShop = goodsShopDao.selectById(tbIndents.get(i).getShopId());
                    try{
                        if("3".equals(tbIndents.get(i).getIndentType())&&"0".equals(tbIndents.get(i).getBuyType())){
                            //没有起点位置，只有终点位置。通过终点位置查距离内最近的骑手
                            Long userId = tbIndentDao.selectRiderByDictance(tbIndents.get(i).getUserLng(), tbIndents.get(i).getUserLat(),
                                    distance,cashDeposit,maxNum);
                            if(userId!=null){
                                tbIndentDao.indentReceiv(userId, tbIndents.get(i).getIndentNumber(), format,"4");
                                //自动推单以后，消息通知骑手
                                UserEntity userEntity = userDao.selectById(userId);
                                List<String> msgList=new ArrayList<>();
                                msgList.add("接单项目");
                                msgList.add(userEntity.getNickName());
                                msgList.add(format);
                                msgList.add("系统自动推单");
                                SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(),five.getValue(),msgList,4);
                                userService.pushToSingleRider("系统自动推单", "系统已为您自动派单，请及时前往派送！", userEntity.getRiderClientid());
                                userService.sendMsgDXB(userEntity.getPhone(), "autosend", 0);
                            }
                        }else {
                            if(goodsShop!=null&&goodsShop.getAutoSendOrder()!=null&&goodsShop.getAutoSendOrder()==0){
                                //有起点位置，通过起点位置查距离内最近的骑手
                                Long userId = tbIndentDao.selectRiderByDictance(tbIndents.get(i).getShopLng(), tbIndents.get(i).getShopLat(),
                                        distance, cashDeposit,maxNum);
                                if(userId!=null){
                                    tbIndentDao.indentReceiv(userId, tbIndents.get(i).getIndentNumber(), format,"3");
                                    //           tbIndentDao.indentReceiving(userId, tbIndents.get(i).getIndentNumber(), format);
                                    //自动推单以后，消息通知骑手
                                    UserEntity userEntity = userDao.selectById(userId);
                                    List<String> msgList=new ArrayList<>();
                                    msgList.add("接单项目");
                                    msgList.add(userEntity.getNickName());
                                    msgList.add(format);
                                    msgList.add("系统自动推单");
                                    SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(),five.getValue(),msgList,4);
                                    userService.pushToSingleRider("系统自动推单", "系统已为您自动派单，请及时前往派送！", userEntity.getRiderClientid());
                                    userService.sendMsgDXB(userEntity.getPhone(), "autosend", 0);
                                }
                            }
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                        log.error("定时任务自动退单异常，异常订单id:"+tbIndents.get(i).getIndentId()+"，异常："+e.getMessage(),e);
                    }
                }
            }
            log.info("自动给骑手推单任务运行成功");
        } catch (Exception e) {
            log.error("自动给骑手推单任务开始运行失败，【{}】", e);
        } finally {
            lock.unlock();
        }
    }

    private String getCurrentTime(int i){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -i);
        Date beforeD = beforeTime.getTime();
        String time = sdf.format(beforeD);
        return time;
    }
}
