package com.sqx.modules.job.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.modules.app.entity.InviteAchievement;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.InviteAchievementService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.complet.entity.CompletAward;
import com.sqx.modules.complet.service.CompletAwardService;
import com.sqx.modules.course.service.CourseService;
import com.sqx.modules.invite.dao.InviteDao;
import com.sqx.modules.invite.entity.Invite;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.wuyou.BaseResp;
import com.sqx.modules.pay.wuyou.WuyouPay;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Component
public class TempOrdersTask {

    @Resource
    private OrdersDao ordersDao;
    @Resource
    private PayDetailsDao payDetailsDao;
    @Resource
    private OrdersService ordersService;
    @Resource
    private UserMoneyDetailsService userMoneyDetailsService;
    @Resource
    private UserService userService;
    @Resource
    private InviteService inviteService;
    @Resource
    private CommonInfoService commonRepository;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private InviteDao inviteDao;
    @Resource
    private CompletAwardService completAwardService;
    @Resource
    private WuyouPay wuyouPay;
    @Value("${spring.profiles.active}")
    private String profiles;
    private final InviteAchievementService inviteAchievementService;
    private final CourseService courseService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public TempOrdersTask(InviteAchievementService inviteAchievementService, CourseService courseService) {
        this.inviteAchievementService = inviteAchievementService;
        this.courseService = courseService;
    }


    @Scheduled(cron = "0 0/10 * * * ? ")
    public void order() {
        if (!"pay".equals(profiles)) {
            return;
        }
        logger.info("订单表数据处理开始");
//        List<Orders> orders = ordersDao.selectList(Wrappers.<Orders>lambdaQuery()
//                .eq(Orders::getStatus, 0)
//                .lt(Orders::getCreateTime, DateUtil.offsetMinute(DateUtil.date(), -15)));
        List<PayDetails> payDetailsList = payDetailsDao.selectList(new LambdaQueryWrapper<PayDetails>()
                .eq(PayDetails::getState, 0)
                .lt(PayDetails::getCreateTime, DateUtil.offsetMinute(DateUtil.date(), -15)));
        if (CollUtil.isEmpty(payDetailsList)) {
            return;
        }

        logger.info("待处理数据{}条", payDetailsList.size());

        for (PayDetails details : payDetailsList) {
            try {
                ThreadUtil.sleep(100);
                Orders orders = ordersDao.selectOne(new LambdaQueryWrapper<Orders>()
                        .eq(Orders::getOrdersNo, details.getOrderId()));

                BaseResp baseResp = wuyouPay.queryOrder(details.getTradeNo(), details.getMoney().toString(), "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/131.0.0.0");
                logger.info("baseResp：{} ", JSONUtil.toJsonStr(baseResp));
                if (baseResp.getCode() == null || baseResp.getCode() != 200) {
                    logger.info("code错误跳过");
                    continue;
                }
                if ("SUCCESS".equals(baseResp.getPayStatus()) || "SUCCESS".equals(baseResp.getPayStatus2())) {
                    logger.info("payDetails：{} ", JSONUtil.toJsonStr(details));
                    logger.info("order：{} ", JSONUtil.toJsonStr(orders));
                    updateOrderStatus(details, orders);
                } else {
                    logger.info("订单未支付，修改状态: {}", details.getTradeNo());
                    if (orders != null) {
                        orders.setStatus(3);
                        ordersDao.updateById(orders);
                    }
                    details.setState(2);
                    payDetailsDao.updateById(details);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("订单数据处理异常：", e);
            }

        }
        logger.info("订单表数据处理完毕");
    }


    public void updateOrderStatus(PayDetails payDetails, Orders order) {
        if (payDetails.getState() == 1) {
            return;
        }

        payDetailsDao.updateState(payDetails.getId(), 1, DateUtil.now(), payDetails.getTradeNo(), payDetails.getThirdOrderNo());

        order.setPayWay(9);
        order.setStatus(1);
        order.setPayTime(DateUtils.format(new Date()));

        ordersService.updateById(order);
        ordersService.insertOrders(order);

        UserEntity user = userService.selectUserById(order.getUserId());
        UserEntity byUser = userService.queryByInvitationCode(user.getInviterCode());
        if (byUser != null) {
            InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(user.getUserId());
            if (inviteAchievement == null) {
                inviteAchievement = new InviteAchievement();
                inviteAchievement.setState(0);
                inviteAchievement.setCount(1);
                inviteAchievement.setCreateTime(DateUtil.date());
                inviteAchievement.setUserId(user.getUserId());
                inviteAchievement.setSourceUserId(byUser.getUserId());
                inviteAchievementService.save(inviteAchievement);
            } else {
                inviteAchievementService.incrCount(inviteAchievement.getId(), 1);
            }
        }
        ThreadUtil.execAsync(() -> {
            ThreadUtil.sleep(1000);
            activities(user, byUser);
        });

        ThreadUtil.execAsync(() -> {
            inviteService.updateInvite(byUser, DateUtil.now(), user.getUserId(), order.getPayMoney());
        });

        //增加剧集支付次数
        ThreadUtil.execAsync(() -> {
            courseService.incrWeekPayCount(order.getCourseId());
        });
        //Map<String, Object> map = inviteService.updateInvite(byUser, DateUtil.now(), user.getUserId(), order.getPayMoney());
//        Object oneUserId = map.get("oneUserId");
//        if (oneUserId != null) {
//            order.setOneUserId(Long.parseLong(String.valueOf(oneUserId)));
//            order.setOneMoney(new BigDecimal(String.valueOf(map.get("oneMoney"))));
//        }
//        Object twoUserId = map.get("twoUserId");
//        if (twoUserId != null) {
//            order.setTwoUserId(Long.parseLong(String.valueOf(twoUserId)));
//            order.setTwoMoney(new BigDecimal(String.valueOf(map.get("twoMoney"))));
//        }
//        Object sysUserId = map.get("sysUserId");
//        if (sysUserId != null) {
//            order.setSysUserId(Long.parseLong(String.valueOf(sysUserId)));
//            order.setQdMoney(new BigDecimal(String.valueOf(map.get("qdMoney"))));
//        }
    }

    @Transactional
    public void activities(UserEntity user, UserEntity sourceUser) {
        //分享达标
        if (sourceUser == null || sourceUser.getUserId() == 1) {
            return;
        }
        InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(user.getUserId());
        // 首次达标
        int signCount = Integer.parseInt(commonRepository.findOne(913).getValue());
        logger.info("{}签到次数: {}", user.getUserName(), inviteAchievement.getCount());
        if (inviteAchievement.getState() == 0 && inviteAchievement.getCount() >= signCount) {
            //满3笔
            String amount = commonRepository.findOne(912).getValue();
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setClassify(6);
            userMoneyDetails.setMoney(new BigDecimal(amount));
            userMoneyDetails.setUserId(sourceUser.getUserId());
            userMoneyDetails.setByUserId(user.getUserId());
            userMoneyDetails.setCreateTime(DateUtil.now());
            userMoneyDetails.setContent("分享达标奖励" + amount + "元");
            userMoneyDetails.setTitle("分享达标奖励");
            userMoneyDetails.setState(2);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoneyType(1);
            userMoneyDetailsService.save(userMoneyDetails);
            //上级 存入余额 钱
            userMoneyService.updateAmount(1, sourceUser.getUserId(), Double.parseDouble(amount));

            inviteAchievement.setState(1);
            inviteAchievementService.updateById(inviteAchievement);

            //代理
            if (StringUtils.isNotBlank(user.getQdCode()) && !"666666".equals(user.getQdCode())) {
                SysUserEntity sysUser = sysUserService.selectSysUserByQdCode(user.getQdCode());
                if (sysUser != null) {
                    String qdAward = commonRepository.findOne(915).getValue();
                    UserMoneyDetails userMoneyDetails4 = new UserMoneyDetails(
                            null, sysUser.getUserId(), null, "[分享达标额外奖励]", 6, 1, 2,
                            new BigDecimal(qdAward), "推广人员首次达标，额外奖励现金红包" + qdAward, 2);

                    userMoneyService.updateSysAmount(1, sysUser.getUserId(), Double.parseDouble(qdAward));
                    userMoneyDetailsService.save(userMoneyDetails4);
                }
            }
        }

        int count = inviteAchievementService.count(
                new LambdaQueryWrapper<InviteAchievement>()
                        .eq(InviteAchievement::getSourceUserId, sourceUser.getUserId())
                        .eq(InviteAchievement::getState, 1));
        logger.info("邀请人员: {}", count);
        //count 邀请的已达标人数
        completAwardService.list(new QueryWrapper<CompletAward>().eq("invite_count", count).eq("status", 1)).forEach(completAward -> {
            QueryWrapper<UserMoneyDetails> moneyDetailsQuery = new QueryWrapper<>();
            moneyDetailsQuery.eq("classify", 6);
            moneyDetailsQuery.eq("user_id", sourceUser.getUserId());
            moneyDetailsQuery.eq("source_id", completAward.getId());
            //达标人数
            int awardCount = userMoneyDetailsService.count(moneyDetailsQuery);
            if (awardCount < 1) {
                switch (completAward.getType()) {
                    case 1:

                        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails(
                                sourceUser.getUserId(), null, null, "[分享达标额外奖励]", 6, 1, 2, completAward.getAwardNumber(),
                                "邀请人员已有" + completAward.getInviteCount() + "人完成达标任务，额外奖励金币" + completAward.getAwardNumber(), 2, completAward.getId());

                        userMoneyService.updateMoney(1, sourceUser.getUserId(), completAward.getAwardNumber().doubleValue());
                        userMoneyDetailsService.save(userMoneyDetails1);
                        break;
                    case 2:
                        UserMoneyDetails userMoneyDetails2 = new UserMoneyDetails(
                                sourceUser.getUserId(), null, null, "[分享达标额外奖励]", 6, 1, 2, completAward.getAwardNumber(),
                                "邀请人员已有" + completAward.getInviteCount() + "人完成达标任务，额外奖励现金红包" + completAward.getAwardNumber(), 1, completAward.getId());

                        userMoneyService.updateAmount(1, sourceUser.getUserId(), completAward.getAwardNumber().doubleValue());
                        userMoneyDetailsService.save(userMoneyDetails2);
                        break;
                }
            }
        });

    }
}
