package com.fzm.mall.server.admin.task.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fzm.mall.server.admin.chain.FzmChain;
import com.fzm.mall.server.admin.finance_center.model.UserAsset;
import com.fzm.mall.server.admin.finance_center.model.UserAssetRecord;
import com.fzm.mall.server.admin.finance_center.service.IUserAssetRecordService;
import com.fzm.mall.server.admin.finance_center.service.IUserAssetService;
import com.fzm.mall.server.admin.goods_center.model.GoodsComment;
import com.fzm.mall.server.admin.goods_center.model.Spu;
import com.fzm.mall.server.admin.goods_center.service.IGoodsCommentService;
import com.fzm.mall.server.admin.goods_center.service.ISpuService;
import com.fzm.mall.server.admin.home_page.model.Merchant;
import com.fzm.mall.server.admin.home_page.service.IMerchantService;
import com.fzm.mall.server.admin.mq.MsgProducer;
import com.fzm.mall.server.admin.mq.enums.QueueTypeEnum;
import com.fzm.mall.server.admin.order.model.*;
import com.fzm.mall.server.admin.order.service.*;
import com.fzm.mall.server.admin.user_center.model.User;
import com.fzm.mall.server.admin.user_center.service.IUserService;
import com.fzm.mall.server.admin.util.OrderUtil;
import com.fzm.mall.server.admin.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author wangp
 * @date 2021/6/18 10:43
 * @description 订单定时任务
 * @since JDK 1.8
 */
@Component
@Slf4j
@Transactional
public class OrderTask {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private ISpuService spuService;
    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IGoodsCommentService goodsCommentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private FzmChain fzmChain;
    @Autowired
    private IUserAssetRecordService userAssetRecordService;
    @Autowired
    private IUserAssetService userAssetService;
    @Autowired
    private IPayService payService;
    @Autowired
    private MsgProducer producer;

    //TODO apiToken,接口调用限制,预售拍卖定时任务,|权限，转账WITHDRAW TRUE

    //超时自动发货
    /*@Scheduled(cron = "2 0 0 * * ?")
    public void autoDelivery() {
        LambdaQueryWrapper<Order> orderQW = new LambdaQueryWrapper<>();
        orderQW.in(Order::getOrderState, 1, 8, 9);
        orderQW.eq(Order::getIsDraw, 1);
        List<Order> orderList = orderService.list(orderQW);

        for (Order order : orderList) {
            LambdaQueryWrapper<OrderDetail> orderDetailQW = new LambdaQueryWrapper<>();
            orderDetailQW.eq(OrderDetail::getOid, order.getOid());
            orderDetailQW.gt(OrderDetail::getTNumber, 0);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailQW);

            if (orderDetailList.size() == 0) {
                LambdaUpdateWrapper<Order> orderUW = new LambdaUpdateWrapper<>();
                orderUW.set(Order::getIsDraw, 2);
                orderUW.eq(Order::getOid, order.getOid());
                orderService.update(orderUW);
            } else {
                for (OrderDetail orderDetail : orderDetailList) {
                    Spu spu = spuService.getByGoodsId(orderDetail.getGoodsId());
                    long lastDay = orderDetail.getCreateTime() + spu.getDelayDays() * 24 * 60 * 60 * 1000;
                    //超时自动提货
                    if (System.currentTimeMillis() > lastDay) {
                        Delivery delivery = new Delivery();
                        delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                        delivery.setUid(order.getUid());
                        delivery.setMerchantId(order.getMerchantId());
                        delivery.setGoodsId(orderDetail.getGoodsId());
                        delivery.setSkuId(orderDetail.getSkuId());
                        delivery.setName(spu.getName());
                        delivery.setCoin(orderDetail.getCoin());
                        delivery.setNumber(orderDetail.getTNumber());
                        delivery.setUname(order.getUname());
                        delivery.setPhone(order.getPhone());
                        delivery.setAddress(order.getAddress());
                        delivery.setNote("超时自动提货");
                        delivery.setDeliveryState(0);
                        delivery.setIsDelete(0);
                        delivery.setBuyerState(0);
                        delivery.setSellerState(0);
                        deliveryService.save(delivery);
                    }

                    //可提货数量清零
                    orderDetail.setTNumber(0);
                    orderDetailService.updateById(orderDetail);
                }
            }
        }
    }*/

    //超时自动收货
    /*@Scheduled(cron = "3 0 0 * * ?")
    public void autoReceiving() {
        LambdaQueryWrapper<Delivery> deliveryQW = new LambdaQueryWrapper<>();
        deliveryQW.eq(Delivery::getDeliveryState, 1);
        deliveryQW.eq(Delivery::getIsDelete, 0);
        List<Delivery> deliveryList = deliveryService.list(deliveryQW);

        Config config = configService.getById(1);
        for (Delivery delivery : deliveryList) {
            long time = delivery.getDeliveryTime() + config.getGoodsReceivedLimit() * 24 * 60 * 60 * 1000;
            if (System.currentTimeMillis() > time) {
                delivery.setDeliveryState(2);
                delivery.setFinishTime(System.currentTimeMillis());
                deliveryService.updateById(delivery);
            }
        }
    }*/

    //提货单自动结束交易
    /*@Scheduled(cron = "4 0 0 * * ?")
    public void autoDeliveryCloseLimit() {
        LambdaQueryWrapper<Delivery> deliveryQW = new LambdaQueryWrapper<>();
        deliveryQW.eq(Delivery::getDeliveryState, 2);
        deliveryQW.eq(Delivery::getIsDelete, 0);
        List<Delivery> deliveryList = deliveryService.list(deliveryQW);

        Config config = configService.getById(1);
        for (Delivery delivery : deliveryList) {
            long time = delivery.getFinishTime() + config.getDeliveryCloseLimit() * 24 * 60 * 60 * 1000;
            if (System.currentTimeMillis() > time) {
                delivery.setDeliveryState(6);
                deliveryService.updateById(delivery);

                //获取用户币地址
                String fromAddress = "";
                User user = userService.queryByUid(delivery.getUid());
                if (user != null) {
                    fromAddress = user.getAddress();
                }
                //获取品牌方销毁地址
                Merchant merchant = merchantService.getByMerchantId(delivery.getMerchantId());
                String toAddress = "";
                if (merchant != null) {
                    toAddress = merchant.getTokenRecoverAddr();
                }
                Map<String, String> map = fzmChain.tranToken(fromAddress, null, toAddress, new BigDecimal(delivery.getNumber()), delivery.getCoin());
                if (map.get("status").equals("FAIL")) {
                    log.error("销毁商品币失败，提货单号：" + delivery.getOrderDeliveryId());
                }

                LambdaQueryWrapper<UserAsset> qw = new LambdaQueryWrapper<>();
                qw.eq(UserAsset::getCoin, delivery.getCoin());
                qw.eq(UserAsset::getType, 7);
                UserAsset userAsset = userAssetService.getOne(qw);
                userAsset.setAmount(userAsset.getAmount().subtract(new BigDecimal(delivery.getNumber())));
                userAssetService.updateById(userAsset);

                UserAssetRecord record = new UserAssetRecord();
                record.setUid(delivery.getUid());
                record.setCoin(delivery.getCoin());
                record.setAmount(BigDecimal.valueOf(delivery.getNumber()));
                record.setType(7);//提货
                record.setStatus(2);//成功
                record.setAssetType(7);
                record.setTradeType(2);
                record.setFlowId(UUIDUtil.getUUID());
                record.setNote(delivery.getOrderDeliveryId());
                boolean saveReco = userAssetRecordService.save(record);
                if (saveReco) {
                    log.error("资金记录保存失败");
                }


            }
        }
    }*/

    //订单自动结束交易
    @Scheduled(cron = "5 0 0 * * ?")
    public void autoDealCloseLimit() {
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.in(Order::getOrderState, 1, 8, 9);
        qw.eq(Order::getIsDelete, 0);
        List<Order> orderList = orderService.list(qw);

        Config config = configService.list().get(0);
        for (Order order : orderList) {
            long time = order.getUpdateTime() + config.getDealCloseLimit() * 24 * 60 * 60 * 1000;
            if (System.currentTimeMillis() > time) {
                order.setOrderState(Order.ORDER_STATE_FINISH_AUTO_CLOSE);
                orderService.updateById(order);
            }
        }
    }

    //自动好评
    /*@Scheduled(cron = "6 0 0 * * ?")
    public void autoPraise() {
        LambdaQueryWrapper<Delivery> deliveryQW = new LambdaQueryWrapper<>();
        deliveryQW.eq(Delivery::getDeliveryState, 6);
        deliveryQW.eq(Delivery::getBuyerState, 0);
        deliveryQW.eq(Delivery::getIsDelete, 0);
        List<Delivery> deliveryList = deliveryService.list(deliveryQW);

        Config config = configService.getById(1);
        for (Delivery delivery : deliveryList) {
            long time = delivery.getFinishTime() + config.getHighOpinionLimit() * 24 * 60 * 60 * 1000;
            if (System.currentTimeMillis() > time) {
                GoodsComment comment = new GoodsComment();
                comment.setSkuId(delivery.getSkuId());
                comment.setCommentId(UUIDUtil.getUUID());
                comment.setMerchantId(delivery.getMerchantId());
                comment.setGoodsId(delivery.getGoodsId());
                comment.setOid(delivery.getOrderDeliveryId());
                comment.setUid(delivery.getUid());
                comment.setEvaluate(0);
                comment.setContent("默认好评");
                goodsCommentService.save(comment);
            }
        }
    }*/

    //超时关闭订单
    @Scheduled(cron = "0 * * * * ?")
    public void closeOrder() {
        LambdaQueryWrapper<Pay> payQW = new LambdaQueryWrapper<>();
        payQW.in(Pay::getState, 3, 6);
//        payQW.eq(Pay::getType, 1);
        List<Pay> payList = payService.list(payQW);

        Config config = configService.list().get(0);
        for (Pay pay : payList) {
            long time = pay.getCreateTime() + config.getOrderCloseLimit() * 60 * 1000;
            if (System.currentTimeMillis() > time) {
                log.info("超时关闭订单,关闭订单支付子编号:" + pay.getPayId());
                //发送消息队列
                producer.send(pay.getPayId(), QueueTypeEnum.ORDER_CLOSE);
            }
        }
    }

}
