package com.gree.mall.manager.schedule;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.StringUtils;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.OrderInfoSourceEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
import com.gree.mall.manager.enums.PayStatusEnum;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.order.OrderLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * 发货相关任务
 */
@Slf4j
@ConditionalOnProperty(name = "schedule.enable", havingValue = "true", matchIfMissing = true)
@Component
public class AutoDeliverSchedule {

    @Autowired
    WechatLogic wechatLogic;
    @Autowired
    OrderLogic orderLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;
    @Autowired
    WebsitSalesPayOrderService websitSalesPayOrderService;
    @Autowired
    PgIncreOrderService pgIncreOrderService;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    LeaseOrderService leaseOrderService;
    @Autowired
    LeaseOrderPayRecordService leaseOrderPayRecordService;
    @Autowired
    UserService userService;
    @Autowired
    WechatAutoDeliverService wechatAutoDeliverService;

    /**
     * 定时同步商城订单 到微信发货
     * @throws Exception
     */
    @Scheduled(fixedDelay = 10 * 1000)
    public void task0() throws Exception {
        List<OrderInfo> list = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getIsDeliver, false)
                .in(OrderInfo::getOrderStatus, OrderStatusEnum.YFH.toString(),OrderStatusEnum.OVER.toString())
                .le(OrderInfo::getPayTime, DateUtil.offsetMinute(new Date(), -5)).list();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        log.info("【定时同步商城订单到微信发货】数量:{}",list.size());
        for(OrderInfo bean : list){
            //小程序需要对接发货
            if(StringUtils.equals(bean.getSource(), OrderInfoSourceEnum.A.getRemark())) {
                User user = userService.getById(bean.getUserId());
                if(user == null){
                    continue;
                }
                wechatLogic.deliver(bean.getCompanyWechatId(), bean.getTransactionId(), null, user.getMiniOpenId());
            }
            bean.setIsDeliver(true);
            bean.updateById();
        }
    }


    /**
     * 定时同步辅材销售单 到微信发货
     * @throws Exception
     */
//    @Scheduled(fixedDelay = 10 * 1000)
//    public void task() throws Exception {
//        List<WebsitSalesPayOrder> list = websitSalesPayOrderService.lambdaQuery()
//                .eq(WebsitSalesPayOrder::getIsDeliver, false)
//                .in(WebsitSalesPayOrder::getOrderSource, SalesPayOrderSourceEnum.M_SALES.getKey(),SalesPayOrderSourceEnum.P_SALES.getKey())
//                .le(WebsitSalesPayOrder::getPayTime, DateUtil.offsetMinute(new Date(), -5))
//                .list();
//        if(CollectionUtils.isEmpty(list)){
//            return;
//        }
//        log.info("【定时辅材销售单到微信发货】数量:{}",list.size());
//        for(WebsitSalesPayOrder bean : list){
//            //小程序需要对接发货
//            if(StringUtils.equals(bean.getSource(), OrderInfoSourceEnum.A.getRemark())) {
//                wechatLogic.deliver(bean.getCompanyWechatId(), bean.getTransactionId(), null, bean.getOpenid());
//            }
//            bean.setIsDeliver(true);
//            bean.updateById();
//        }
//    }


    /**
     * 定时延保订单 到微信发货
     * @throws Exception
     */
    @Scheduled(fixedDelay = 10 * 1000)
    public void task2() throws Exception {

        List<PgIncreOrder> list = pgIncreOrderService.lambdaQuery().eq(PgIncreOrder::getIsDeliver, false)
                .eq(PgIncreOrder::getPayStatus, PayStatusEnum.PAID.getKey())
                .le(PgIncreOrder::getPayTime, DateUtil.offsetMinute(new Date(), -5)).list();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        log.info("【定时延保订单到微信发货】数量:{}",list.size());
        for(PgIncreOrder bean : list){
            //小程序需要对接发货
            if(StringUtils.equals(bean.getSource(), OrderInfoSourceEnum.A.getRemark())) {
                wechatLogic.deliver(bean.getCompanyWechatId(), bean.getTranscationId(), null, bean.getWorkerOpenId());
            }
            bean.setIsDeliver(true);
            bean.updateById();
        }
    }

    /**
     * 定时租赁订单 到微信发货
     * @throws Exception
     */
    @Scheduled(fixedDelay = 10 * 1000)
    public void task4() throws Exception {

        List<LeaseOrderPayRecord> list = leaseOrderPayRecordService.lambdaQuery()
                .eq(LeaseOrderPayRecord::getIsDeliver, false)
                .eq(LeaseOrderPayRecord::getPayStatus, true)
                .ne(LeaseOrderPayRecord::getTransactionId,"")
                .le(LeaseOrderPayRecord::getPayTime, DateUtil.offsetMinute(new Date(), -5)).list();

        if(CollectionUtils.isEmpty(list)){
            return;
        }
        log.info("【定时租赁订单到微信发货】数量:{}",list.size());
        for(LeaseOrderPayRecord bean : list){
            //小程序需要对接发货
            if(StringUtils.equals(bean.getSource(), OrderInfoSourceEnum.A.getRemark())) {
                wechatLogic.deliver(bean.getCompanyWechatId(), bean.getTransactionId(), null, bean.getOpenid());
            }
            bean.setIsDeliver(true);
            bean.updateById();
        }
    }



    /**
     * 纯虚拟商品的待发货订单，直接生成工单
     * @throws Exception
     */
    @Scheduled(fixedDelay = 10 * 1000)
    public void task3() throws Exception {
        List<OrderInfo> list = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                .eq(OrderInfo::getIsAllVr, true).list();
        for(OrderInfo orderInfo : list){
            Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + orderInfo.getOrderId());
            if(!obtain.tryLock(10, TimeUnit.SECONDS)){
                continue;
            }
            try {
                orderLogic.deliverGoods(orderInfo.getOrderId(),"","","",true,false);
            }finally {
                obtain.unlock();
            }
        }
    }



    /**
     * 通用对接微信自动发货
     * @throws Exception
     */
    @Scheduled(fixedDelay = 10 * 1000)
    public void task0000() throws Exception {

        List<WechatAutoDeliver> list = wechatAutoDeliverService.lambdaQuery()
                .eq(WechatAutoDeliver::getIsDeliver, false)
                .ne(WechatAutoDeliver::getTransactionId,"")
                .le(WechatAutoDeliver::getCreateTime, DateUtil.offsetMinute(new Date(), -5)).list();

        if(CollectionUtils.isEmpty(list)){
            return;
        }
        log.info("【定时通用发货到微信发货】数量:{}",list.size());
        for(WechatAutoDeliver bean : list){
            //小程序需要对接发货
            wechatLogic.deliver(bean.getCompanyWechatId(), bean.getTransactionId(), null, bean.getOpenId());

            bean.setIsDeliver(true);
            bean.updateById();
        }
    }




}
