package com.sqx;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.InviteAchievement;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.InviteAchievementService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.job.task.TempOrdersTask;
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.service.PayDetailsService;
import com.sqx.modules.sys.service.SysUserService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ActiveProfiles;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@ActiveProfiles("pay")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Tets {
    private static final Logger log = LoggerFactory.getLogger(Tets.class);
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    UserService userService;
    @Autowired
    TempOrdersTask tempOrdersTask;
    @Autowired
    InviteAchievementService inviteAchievementService;
    @Autowired
    PayDetailsService payDetailsService;
    @Autowired
    PayDetailsDao payDetailsDao;
    @Autowired
    UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    UserMoneyDao userMoneyDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OrdersService ordersService;

    //@Test
    public void test4() {
        UserEntity userEntity = userDao.selectById(1072962203591784209L);
        UserEntity userEntity2 = userDao.selectById(1072640875319932689L);
        tempOrdersTask.activities(userEntity, userEntity2);
    }

    //@Test
    public void test3() {
        List<UserMoneyDetails> userMoneyDetails = userMoneyDetailsDao.selectList(new LambdaQueryWrapper<UserMoneyDetails>().in(UserMoneyDetails::getClassify, 6, 1).isNotNull(UserMoneyDetails::getUserId).groupBy(UserMoneyDetails::getUserId).select(UserMoneyDetails::getUserId));
        Set<Long> useridList = userMoneyDetails.stream().map(UserMoneyDetails::getUserId).collect(Collectors.toSet());
        List<UserMoney> userMoneyDetailsList = userMoneyDao.selectList(new LambdaQueryWrapper<UserMoney>().in(UserMoney::getUserId, useridList));
        userMoneyDetailsList.parallelStream().forEach(userMoney -> {
            BigDecimal coin = userMoneyDao.sumMoney(userMoney.getUserId());
            BigDecimal money = userMoneyDao.sumMoney2(userMoney.getUserId());
            log.info("用户: {}, 金币: {}, 金额: {}", userMoney.getUserId(), coin, money);
            userMoney.setInviteIncomeCoin(coin);
            userMoney.setInviteIncomeMoney(money);
            userMoneyDao.update(userMoney, new LambdaQueryWrapper<UserMoney>().eq(UserMoney::getUserId, userMoney.getUserId())
                    .eq(UserMoney::getId, userMoney.getId()));
        });

    }

    //@Test
    public void test2() {
        inviteAchievementService.remove(new LambdaQueryWrapper<>());
        //Wrappers.<UserEntity>lambdaQuery().apply("create_time >= str_to_date({0}, '%Y-%m-%d %H:%i:%s')",  "2025-01-01 00:00:00");
        List<UserEntity> userinfoList = userService.list(Wrappers.emptyWrapper());
        System.out.println(userinfoList.size());
        userinfoList.parallelStream().forEach((userEntity -> {
            if (StrUtil.isBlank(userEntity.getInviterCode())) return;

            UserEntity byUser = userService.queryByInvitationCode(userEntity.getInviterCode());

            if (byUser == null) return;

            Integer count = payDetailsDao.selectCount(new LambdaQueryWrapper<PayDetails>()
                    .eq(PayDetails::getState, 1)
                    .eq(PayDetails::getUserId, userEntity.getUserId())
                    .eq(PayDetails::getClassify, 9));

            Integer count1 = userMoneyDetailsDao.selectCount(new LambdaQueryWrapper<UserMoneyDetails>()
                    .eq(UserMoneyDetails::getClassify, 6)
                    .eq(UserMoneyDetails::getByUserId, userEntity.getUserId())
                    .eq(UserMoneyDetails::getUserId, byUser.getUserId())
                    .eq(UserMoneyDetails::getTitle, "分享达标奖励"));

            InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(userEntity.getUserId());
            if (inviteAchievement == null) {
                inviteAchievement = new InviteAchievement();
                inviteAchievement.setState(count1 > 0 ? 1 : 0);
                inviteAchievement.setCount(count);
                inviteAchievement.setCreateTime(DateUtil.date());
                inviteAchievement.setTargetUserId(userEntity.getUserId());
                inviteAchievement.setUserId(byUser.getUserId());
                inviteAchievementService.save(inviteAchievement);
            } else {
                inviteAchievement.setState(count1 > 0 ? 1 : 0);
                inviteAchievement.setCount(count);
                inviteAchievement.setCreateTime(DateUtil.date());
                inviteAchievement.setTargetUserId(userEntity.getUserId());
                inviteAchievement.setUserId(byUser.getUserId());
                inviteAchievementService.update(inviteAchievement, new LambdaQueryWrapper<InviteAchievement>()
                        .eq(InviteAchievement::getUserId, inviteAchievement.getUserId())
                        .eq(InviteAchievement::getId, inviteAchievement.getId()));
            }
        }));

    }

    //@Test
    public void test() {
//       }
//        WuyouController proxy = applicationContext.getBean(WuyouController.class);
//        UserEntity userEntity = userService.selectUserById(26972L);
//        UserEntity byUser = userService.queryByInvitationCode(userEntity.getInviterCode());
//
//        proxy.activities(userEntity, byUser);
//        System.out.println(proxy);
//        BaseResp baseResp = JSONObject.parseObject("{\"msg\":\"查询成功\",\"code\":200,\"payStatus\":\"NOTPAY\",\"status\":99999}", BaseResp.class);
//        tempOrdersTask.order();
//        List<PayDetails> payDetailsList = payDetailsDao.selectList(new LambdaQueryWrapper<PayDetails>()
//                .eq(PayDetails::getState, 0)
//                .lt(PayDetails::getCreateTime, DateUtil.offsetMinute(DateUtil.date(), -15)));

    }

    public static com.aliyun.dytnsapi20200217.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 请参考 https://api.aliyun.com/product/Dytnsapi
        config.endpoint = "dytnsapi.aliyuncs.com";
        return new com.aliyun.dytnsapi20200217.Client(config);
    }


    public static void main(String[] args) {
        assert false : "asdasfqwerq3rqwr";
    }

    //@Test
    public void test999() {
        int total = ordersService.count(Wrappers.<Orders>lambdaQuery().apply("sys_user_id is null"));
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + total);
        LambdaQueryWrapper<Orders> wrapper = Wrappers.<Orders>lambdaQuery().apply("sys_user_id is null").last("limit 1");
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 5000; i++) {
            list.add(i);
        }
        list.parallelStream().forEach(param -> {
            while (true) {
                Orders orders = ordersService.getOne(wrapper);
                if (orders == null) {
                    break;
                }
                ordersService.fillSysUserId(orders);
                //System.out.println(StrUtil.format("-------------------------------sysUserId:{} ", orders.getSysUserId()));
                ordersService.update(null, Wrappers.<Orders>lambdaUpdate().set(Orders::getSysUserId, orders.getSysUserId()).eq(Orders::getOrdersId, orders.getOrdersId()));
            }
        });
    }

    @Test
    public void test888() {
        LambdaQueryWrapper<UserEntity> wrapper = Wrappers.<UserEntity>lambdaQuery().apply("create_time >= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", "2025-01-01 00:00:00");
        List<UserEntity> userinfoList = userService.list(wrapper);
        userinfoList.parallelStream().forEach((userEntity -> {
            List<Orders> list = ordersService.list(Wrappers.<Orders>lambdaQuery().eq(Orders::getUserId, userEntity.getUserId()).isNull(Orders::getSysUserId));
            if (CollUtil.isNotEmpty(list)) {
                List<List<Orders>> split = CollUtil.split(list, 500);
                for (List<Orders> splitList : split) {
                    splitList.parallelStream().forEach(orders -> {
                        ordersService.fillSysUserId(orders);
                        System.out.println(StrUtil.format("-------------------------------sysUserId:{},sysUserName:{} ", orders.getSysUserId(), orders.getUserName()));
                        ordersService.update(null, Wrappers.<Orders>lambdaUpdate().set(Orders::getSysUserId, orders.getSysUserId()).eq(Orders::getOrdersId, orders.getOrdersId()));
                    });
                }
            }
        }));
        System.out.println("-------------------------------结束------------------------------------");
    }

    private List<Dict> buildPageList(int total) {
        int size = 300;
        int totalPage = PageUtil.totalPage(total, size);
        List<Dict> pageList = new ArrayList<>();
        for (int page = 1; page <= totalPage; page++) {
            Dict dict = new Dict();
            dict.set("page", (page - 1) * size);
            dict.set("size", size);
            pageList.add(dict);
        }
        return pageList;
    }

}
