//package com.cyl.tencent;
//
//import com.cyl.h5.pojo.vo.H5OrderVO;
//import com.cyl.h5.service.H5MemberService;
//import com.cyl.h5.service.H5OrderService;
//import com.cyl.manager.oms.domain.OmsOrderService;
//import com.cyl.manager.oms.domain.Order;
//import com.cyl.manager.oms.service.OmsOrderServiceService;
//import com.cyl.manager.oms.service.OrderService;
//import com.cyl.manager.staff.service.IDispatchOrderService;
//import com.cyl.manager.ums.domain.Member;
//import com.cyl.manager.ums.domain.MemberPointHistory;
//import com.cyl.manager.ums.mapper.MemberMapper;
//import com.cyl.manager.ums.service.MemberPointHistoryService;
//import com.cyl.manager.ums.service.MemberService;
//import com.ruoyi.common.config.properties.SmsProperties;
//import com.ruoyi.common.core.sms.AliyunSmsUtils;
//import com.ruoyi.common.utils.StringUtils;
//import com.wechat.pay.java.core.util.GsonUtil;
//import lombok.extern.slf4j.Slf4j;
//import lombok.val;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.stereotype.Component;
//
//import java.math.BigDecimal;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.time.LocalDate;
//import java.time.LocalDateTime;
//import java.time.ZoneId;
//import java.util.Date;
//import java.util.List;
//import java.util.concurrent.BlockingQueue;
//import java.util.concurrent.atomic.AtomicReference;
//
//
//@Slf4j
//@Component
//public class TaskConsumer implements QueueConsumer {
//
//
//    @Autowired
//    @Qualifier("taskQueue")
//    private BlockingQueue<OrderMessageModel> taskQueue;
//
//    @Autowired
//    private MemberPointHistoryService memberPointHistoryService;
//
//    @Autowired
//    private H5MemberService h5MemberService;
//
//    @Autowired
//    private MemberService memberService;
//
//    @Autowired
//    private OrderService orderService;
//
//    @Autowired
//    private OmsOrderServiceService omsOrderServiceService;
//
//    @Autowired
//    private MemberMapper memberMapper;
//
//    @Autowired
//    private SmsProperties smsProperties;
//
//    @Autowired
//    private H5OrderService h5OrderService;
//
//    @Autowired
//    private IDispatchOrderService dispatchedOrdersService;
//
//    @Autowired
//    private IMallOrderService mallOrderService;
//
//    int threadSize = 2;
//    private boolean run;
//    private TaskThread[] taskThreads;
//
//
//
//    private class TaskThread extends Thread {
//
//        @Override
//        public void run() {
//            while (run) {
//                try {
//                    OrderMessageModel model = taskQueue.take();
//                    log.info("消费者消息：" + model);
//                    //处理任务逻辑
//                    log.info("推送订单信息:" + GsonUtil.toJson(model.getOrder()));
//                    //处理积分，集点，等级
//                    pointHandler(model.getOrder());
//
//                    //派单订单逻辑处理方法--------lzx
//                    log.info("派单订单逻辑处理方法--------lzx");
//                    log.info("派单类型："+model.getOrder().getTeacherId());
//                    H5OrderVO h5OrderVO = h5OrderService.orderDetail(model.getOrder().getId());
//                    //如果为空则为系统派单
//                    if (model.getOrder().getTeacherId() == null) {
//                        //系统派单
//                        log.info("系统派单");
//
//                        mallOrderService.acceptDispatchAll(h5OrderVO);
//
//                    }else if (model.getOrder().getTeacherId() != null) {
//                        //指定派单
//                        log.info("指定派单");
//                        //获取当前时间
//                        LocalDateTime now = LocalDateTime.now();
//                    }
//
//
//
//
//
//
//                    //进行派单操作
//                     dispatchedOrdersService.dispatch(model.getOrder().getId());
//                    //TODO 等待订单逻辑完成
//                    smsHandler(model.getOrder());
//                } catch (Exception e) {
//                    log.error("task消费异常：{}", e);
//                }
//            }
//        }
//    }
//
//    private void smsHandler(Order order) {
//        try {
//            Member member = memberService.selectById(order.getMemberId());
//            String phone = memberService.getPhoneDecrypted(member.getPhoneEncrypted());
//
//            //TODO 查询订单的开始日期和结束日期
//            List<OmsOrderService> omsOrderServiceList = omsOrderServiceService.selectListByOrderId(order.getId());
//
//            AtomicReference<String> startDate = new AtomicReference<>();
//            AtomicReference<String> endDate = new AtomicReference<>();
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//
//            omsOrderServiceList.forEach(item -> {
//                String serviceDate = item.getServiceDate();
//                if (StringUtils.isNotEmpty(serviceDate)) {
//                    try {
//                        Date serviceDateDate = sdf.parse(serviceDate);
//
//                        if (StringUtils.isEmpty(startDate.get())) {
//                            startDate.set(serviceDate);
//                        } else {
//                            if (serviceDateDate.before(sdf.parse(startDate.get()))) {
//                                startDate.set(serviceDate);
//                            }
//                        }
//
//                        if (StringUtils.isEmpty(endDate.get())) {
//                            endDate.set(serviceDate);
//                        } else {
//                            if (serviceDateDate.after(sdf.parse(endDate.get()))) {
//                                endDate.set(serviceDate);
//                            }
//                        }
//                    } catch (ParseException e) {
//                        log.error("时间解析失败：" + serviceDate);
//                    }
//                }
//            });
//
//            if (StringUtils.isEmpty(endDate.get()) || StringUtils.isEmpty(startDate.get())) {
//                return;
//            }
//
//            AliyunSmsUtils util = new AliyunSmsUtils(smsProperties);
//            AliyunSmsUtils.sendOrderSuccessSMS(phone, startDate.get(), endDate.get());
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("【支付回调任务处理】发送短信失败：" + e.getMessage());
//        }
//    }
//
//    private void pointHandler(Order order) {
//        BigDecimal amount = order.getPayAmount();
//        Member member = memberService.selectById(order.getMemberId());
//        Integer level = member.getLevel();
//        BigDecimal coefficient = BigDecimal.ZERO;
//        if (level == 1) {
//            coefficient = BigDecimal.valueOf(1.1);
//        } else if ( level == 2) {
//            coefficient = BigDecimal.valueOf(1.1);
//        } else if ( level == 3) {
//            coefficient = BigDecimal.valueOf(1.3);
//        } else if ( level == 4) {
//            coefficient = BigDecimal.valueOf(1.5);
//        } else {
//            coefficient = BigDecimal.valueOf(1.1);
//        }
//        //处理积分
//        MemberPointHistory point =  getPointEntity(member,order,coefficient);
//        memberPointHistoryService.insertMemberPointHistory(point);
//        log.info("新增积分明细:{}", point);
//
//        //处理集点
//        MemberPointHistory gather =  getGatherEntity(order,member.getCentralPoint());
//        memberPointHistoryService.insertMemberPointHistory(gather);
//        log.info("新增集点明细:{}", gather);
//
//        //处理等级
//        //有效订单开始时间为当前时间往前推一年的第一天
//        // 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//        // 获取往前推一年的日期
//        LocalDate oneYearAgo = currentDate.minusYears(1);
//        // 获取往前推一年后的第一天（1月1日）
//        LocalDate firstDayOfYear = oneYearAgo.withDayOfYear(1);
//        // 将LocalDate转换为LocalDateTime，设置时间为00:00:00
//        LocalDateTime startOfDay = firstDayOfYear.atStartOfDay();
//
//        // 如果需要转换为Date类型
//        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
//        List<Order> orders = orderService.getOrdersByMemberId(order.getMemberId(),startDate,new Date());
//        //订单总金额
//        BigDecimal totalAmount = orders.stream()
//                .map(Order::getPayAmount) // 获取每个订单的 amount
//                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加
//        int[] levels =  h5MemberService.evaluateOrderAmount(totalAmount);
//        int memberLevel = levels[0];
//        member.setLevel(memberLevel);
//        member.setCentralPoint(BigDecimal.valueOf(orders.size()));
//        member.setIntegral(totalAmount.multiply(coefficient));
//        memberMapper.updateById(member);
//        log.info("更新member信息:{}", member);
//    }
//
//    private MemberPointHistory getGatherEntity(Order order, BigDecimal centralPoint) {
//        MemberPointHistory memberPointHistory = new MemberPointHistory();
//        memberPointHistory.setMemberId(order.getMemberId());
//        memberPointHistory.setPoint(BigDecimal.ONE);
//        memberPointHistory.setType("gather");
//        memberPointHistory.setTransactionId(order.getId());
//        memberPointHistory.setDescription("数据手工同步");
//        memberPointHistory.setAction("added");
//        memberPointHistory.setPointBefore(centralPoint);
//        centralPoint = centralPoint.add(BigDecimal.valueOf(1));
//        memberPointHistory.setPointAfter(centralPoint);
//        memberPointHistory.setCreateAt(order.getCreateTime());
//        return memberPointHistory;
//    }
//
//    private MemberPointHistory getPointEntity(Member member,Order order, BigDecimal coefficient) {
//        MemberPointHistory memberPointHistory = new MemberPointHistory();
//        memberPointHistory.setMemberId(order.getMemberId());
//        BigDecimal result = order.getPayAmount().multiply(coefficient);
//        memberPointHistory.setPoint(result);
//        memberPointHistory.setType("point");
//        memberPointHistory.setTransactionId(order.getId());
//        memberPointHistory.setDescription("订单生成");
//        memberPointHistory.setAction("added");
//        memberPointHistory.setPointBefore(member.getIntegral());
//        BigDecimal pointAfter = member.getIntegral().add(order.getPayAmount().multiply(coefficient));
//        memberPointHistory.setPointAfter(pointAfter);
//        memberPointHistory.setCreateAt(order.getCreateTime());
//        return memberPointHistory;
//    }
//
//    @Override
//    public void start() {
//        run = true;
//        taskThreads = new TaskThread[threadSize];
//        for (int i = 0; i < threadSize; i++) {
//            taskThreads [i] = new TaskThread();
//            taskThreads [i].start();
//        }
//    }
//
//    @Override
//    public void stop() {
//        run = false;
//        if (taskThreads != null) {
//            for (TaskThread thread : taskThreads ) {
//                thread.interrupt();
//            }
//        }
//    }
//}