package com.ruoyi.model.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.applet.pojo.dto.filterQualifiedUsersVo;
import com.ruoyi.common.core.sms.AliyunSmsUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.model.domain.*;
import com.ruoyi.model.mapper.AppUsersMapper;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletConfigService;
import com.ruoyi.model.service.IAppletOutDateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.model.mapper.AppletOrderMapper;
import com.ruoyi.model.service.IAppletOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 订单信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-28
 */
@Service
public class AppletOrderServiceImpl extends ServiceImpl<AppletOrderMapper, AppletOrder> implements IAppletOrderService {

    @Autowired
    private AppletOrderMapper appletOrderMapper;

    @Autowired
    private IAppUsersService appUsersService;

    @Autowired
    private IAppletConfigService appletConfigService;

    private static final Logger log = LoggerFactory.getLogger(AppletOrderServiceImpl.class);

    /**
     * 查询订单信息
     * 
     * @param id 订单信息主键
     * @return 订单信息
     */
    @Override
    public AppletOrder selectAppletOrderById(Long id)
    {
        return appletOrderMapper.selectAppletOrderById(id);
    }


    @Override
    public AppletOrder selectAppletOrderByOrderId(Long orderId){
        return appletOrderMapper.selectAppletOrderByOrderId(orderId);
    }

    /**
     * 查询订单信息列表
     * 
     * @param appletOrder 订单信息
     * @return 订单信息
     */
    @Override
    public List<AppletOrder> selectAppletOrderList(AppletOrder appletOrder)
    {
        return appletOrderMapper.selectAppletOrderList(appletOrder);
    }


    @Override
    public List<AppletOrder> selectAppletOrderListLikeUserIdJson(AppletOrder appletOrder){
        return appletOrderMapper.selectAppletOrderListLikeUserIdJson(appletOrder);
    }
    /**
     * 新增订单信息
     * 
     * @param appletOrder 订单信息
     * @return 结果
     */
    @Override
    public int insertAppletOrder(AppletOrder appletOrder, boolean sms)
    {
//        appletOrder.setCreateTime(new Date());
        appletOrder.setNoticeSystemFlag(0L);
        appletOrder.setNum(1);
        int i = appletOrderMapper.insert(appletOrder);

        if (sms){
            noticePersonalByOrderIds(Collections.singletonList(appletOrder.getId()));
        }
        return i;
    }

    /**
     * 修改订单信息
     * 
     * @param appletOrder 订单信息
     * @return 结果
     */
    @Override
    public int updateAppletOrder(AppletOrder appletOrder)
    {
//        appletOrder.setUpdateTime(DateUtils.getNowDate());

        AppletOrder one = lambdaQuery()
                .eq(AppletOrder::getId, appletOrder.getId())
                .one();

        appletOrder.setNewOrderTime(LocalDateTime.now());
        appletOrder.setNoticeSystemFlag(0L);
        appletOrder.setNum(one.getNum() == null ? 2 : one.getNum() + 1);

        noticePersonalByOrderIds(Collections.singletonList(appletOrder.getId()));

        return appletOrderMapper.updateAppletOrder(appletOrder);
    }

    /**
     * 批量删除订单信息
     * 
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteAppletOrderByIds(Long[] ids)
    {
        return appletOrderMapper.deleteAppletOrderByIds(ids);
    }

    /**
     * 删除订单信息信息
     * 
     * @param id 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteAppletOrderById(Long id)
    {
        return appletOrderMapper.deleteAppletOrderById(id);
    }


    /**
     * 个人订单超过未接单通知或者转成系统派单逻辑
     * @return 结果
     */
    @Override
    public int personalSystemTransferOrder() {

        //30分钟未接单，提示用户
        LocalDateTime time = LocalDateTime.now().minusMinutes(30);
        List<AppletOrder> orders = lambdaQuery()
                .eq(AppletOrder::getStatus, 0)
                .eq(AppletOrder::getType, 1)
                .le(AppletOrder::getNewOrderTime, time)
                .eq(AppletOrder::getNoticeSystemFlag, 0)
                .list();

        List<Long> ids = orders.stream().map(n -> n.getId()).collect(Collectors.toList());

        if (ids.size() > 0) {
            //修改订单状态
            lambdaUpdate()
                    .in(AppletOrder::getId, ids)
                    .set(AppletOrder::getUpdateTime, LocalDateTime.now())
                    .set(AppletOrder::getNoticeSystemFlag, 1)
                    .update();
        }

        log.info("[personalSystemTransferOrder] 开始检查个人订单超时转系统派单");
        LocalDateTime threeHoursAgo = LocalDateTime.now().minusHours(3);
        List<AppletOrder> timeoutOrders = lambdaQuery()
                .eq(AppletOrder::getStatus, 0)
                .eq(AppletOrder::getType, 1)
                .le(AppletOrder::getNewOrderTime, threeHoursAgo)
                .eq(AppletOrder::getNoticeSystemFlag, 1)
                .list();

        List<Long> ids2 = timeoutOrders.stream().map(n -> {
            orders.add(n);
            return n.getId();
        }).collect(Collectors.toList());

        if (ids2.size() > 0) {
            //修改
            lambdaUpdate()
                    .in(AppletOrder::getId, ids2)
                    .set(AppletOrder::getType, 0)
                    .set(AppletOrder::getUpdateTime, LocalDateTime.now())
                    .set(AppletOrder::getNoticeSystemFlag, 0)
                    .set(AppletOrder::getNewOrderTime, LocalDateTime.now())
                    .setSql("num = num + 1")
                    .update();
        }

        log.info("[personalSystemTransferOrder] 处理完成，转为系统派单订单数：{}", orders.size());

        //通知用户
        noticePersonalByOrderList(orders);

        return orders.size();
    }

    /**
     * 系统订单超过未接单通知逻辑
     * @return 结果
     */
    @Override
    public int systemOrderTimeoutNotice() {

        ArrayList<AppletOrder> list = new ArrayList<>();

        //60分钟未接单
        LocalDateTime oneHoursAgo = LocalDateTime.now().minusMinutes(60);
        List<AppletOrder> oneTimeoutOrders = lambdaQuery()
                .eq(AppletOrder::getStatus, 0)
                .eq(AppletOrder::getType, 0)
                .le(AppletOrder::getNewOrderTime, oneHoursAgo)
                .eq(AppletOrder::getNoticeSystemFlag, 0)
                .list();

        if (oneTimeoutOrders.size() > 0){
            //60分钟未接单修改订单状态
            lambdaUpdate()
                    .in(AppletOrder::getId, oneTimeoutOrders.stream().map(n -> n.getId()).collect(Collectors.toList()))
                    .set(AppletOrder::getUpdateTime, LocalDateTime.now())
                    .set(AppletOrder::getNoticeSystemFlag, 1)
                    .update();
        }

        //120分钟未接单
        LocalDateTime twoHoursAgo = LocalDateTime.now().minusHours(2);
        List<AppletOrder> twoTimeoutOrders = lambdaQuery()
                .eq(AppletOrder::getStatus, 0)
                .eq(AppletOrder::getType, 0)
                .le(AppletOrder::getNewOrderTime, twoHoursAgo)
                .eq(AppletOrder::getNoticeSystemFlag, 1)
                .list();


        if (twoTimeoutOrders.size() > 0) {
            //120分钟未接单修改订单状态
            lambdaUpdate()
                    .in(AppletOrder::getId, twoTimeoutOrders.stream().map(n -> n.getId()).collect(Collectors.toList()))
                    .set(AppletOrder::getUpdateTime, LocalDateTime.now())
                    .set(AppletOrder::getNoticeSystemFlag, 2)
                    .update();
        }

        log.info("[systemOrderTimeoutNotice] 开始检查系统订单超时未接单");
        LocalDateTime threeHoursAgo = LocalDateTime.now().minusHours(3);
        List<AppletOrder> timeoutOrders = lambdaQuery()
                .eq(AppletOrder::getStatus, 0)
                .eq(AppletOrder::getType, 0)
                .le(AppletOrder::getNewOrderTime, threeHoursAgo)
                .eq(AppletOrder::getNoticeSystemFlag, 2)
                .list();

        if(timeoutOrders.size() > 0){

            List<Long> idList = timeoutOrders.stream().map(n -> n.getId()).collect(Collectors.toList());

            AppletConfig appletConfig = appletConfigService.getByCode("admin_phone_list");

            String adminPhoneList = appletConfig.getParamValueText();

            if (StringUtils.isNotEmpty(adminPhoneList)){

                String orderId = "";

                for (AppletOrder aLong : timeoutOrders) {
                    orderId += aLong.getOrderId();
                }

                if (orderId.length() > 30){
                    orderId = orderId.substring(28) + "...";
                }

                for (String phone : adminPhoneList.split(",")) {
                    AliyunSmsUtils.sendLongTimeNoOrderAccepted(phone, orderId);
                }
            }

            //180分钟未接单修改订单状态
            lambdaUpdate()
                    .in(AppletOrder::getId, idList)
                    .set(AppletOrder::getUpdateTime, LocalDateTime.now())
                    .set(AppletOrder::getNoticeSystemFlag, -1)//通知过管理员了
                    .update();
        }

        log.info("[systemOrderTimeoutNotice] 检查完成，超时1小时订单数：{}，超时2小时订单数：{}超时3小时订单数：{}",
            oneTimeoutOrders.size(),
            twoTimeoutOrders.size(),
            timeoutOrders.size()
        );

        oneTimeoutOrders.forEach(list::add);
        twoTimeoutOrders.forEach(list::add);

        noticePersonalByOrderList(list);

        return timeoutOrders.size() + oneTimeoutOrders.size() + twoTimeoutOrders.size();
    }

    /**
     * 短信通知符合条件的伴宠师有新订单
     */
    @Override
    public void noticePersonalByOrderIds(List<Long> ids) {
        List<AppletOrder> list = lambdaQuery()
                .in(AppletOrder::getId, ids)
                .list();

        noticePersonalByOrderList(list);
    }

    public void noticePersonalByOrderList(List<AppletOrder> list) {
        // 需要通知的用户id
        ArrayList<Long> userIds = new ArrayList<>();
        // 需要通知的用户
        HashMap<Long, AppUsers> userMap = new HashMap<>();

        // 提取需要通知的用户
        for (AppletOrder appletOrder : list) {
            List<AppUsers> qualifiedTechnicians;
            if ("0".equals(appletOrder.getType())) { // 系统派单
                // 使用新的筛选逻辑

                qualifiedTechnicians = appUsersService
                        .filterQualifiedUsers(filterQualifiedUsersVo.builder()
                                .orderId(appletOrder.getOrderId())
                                .companionLevel(appletOrder.getCompanionLevel())
                                .latitude(appletOrder.getLatitude())
                                .longitude(appletOrder.getLongitude())
                                .build());

            } else if (StringUtils.isNotEmpty(appletOrder.getUserIdJson())) { // 个人订单
                List<Long> userIdList = Arrays.stream(appletOrder.getUserIdJson()
                        .split(",")).map(n -> Long.parseLong(n))
                        .filter(id -> !userIds.contains(id))
                        .collect(Collectors.toList());

                qualifiedTechnicians = appUsersService.lambdaQuery()
                        .in(AppUsers::getUserId, userIdList).list();
            } else {
                qualifiedTechnicians = new ArrayList<>();
            }

            for (AppUsers technician : qualifiedTechnicians) {
                userIds.add(technician.getUserId());
                userMap.put(technician.getUserId(), technician);
            }
        }

        // 发起通知
        userMap.forEach((id, user) -> {
            AliyunSmsUtils.sendBcshHasOrderSMS(user.getUserTelephone());
        });
    }

}
