package com.sqx.modules.taskCenter.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.RedisKeys;
import com.sqx.common.utils.RedisUtils;
import com.sqx.common.utils.Result;
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.discSpinning.service.DiscSpinningRecordService;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.taskCenter.dao.TaskCenterDao;
import com.sqx.modules.taskCenter.entity.TaskCenter;
import com.sqx.modules.taskCenter.entity.TaskCenterRecord;
import com.sqx.modules.taskCenter.entity.TaskCenterReward;
import com.sqx.modules.taskCenter.service.TaskCenterRecordService;
import com.sqx.modules.taskCenter.service.TaskCenterRewardService;
import com.sqx.modules.taskCenter.service.TaskCenterService;
import com.sqx.modules.userSign.entity.UserSignRecord;
import com.sqx.modules.userSign.service.UserSignRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class TaskCenterServiceImpl extends ServiceImpl<TaskCenterDao, TaskCenter> implements TaskCenterService {

    @Autowired
    private UserSignRecordService signRecordService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private TaskCenterRewardService taskCenterRewardService;
    @Autowired
    private TaskCenterRecordService recordService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private DiscSpinningRecordService discSpinningRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;
    private final InviteAchievementService inviteAchievementService;

    public TaskCenterServiceImpl(InviteAchievementService inviteAchievementService) {
        this.inviteAchievementService = inviteAchievementService;
    }


    @Override
    public Result queryTaskCenter(Long userId) {
        //任务
        List<TaskCenter> taskPage = baseMapper.selectList(new QueryWrapper<TaskCenter>().eq("shows", 1).orderByAsc("sort", "type"));
        List<TaskCenter> resultTask = new ArrayList<>();
        for (TaskCenter s : taskPage) {
            Map<Integer, Integer> rewardMap = taskCenterRewardService.getRewardMap(s.getId());
            boolean todaySign = true;
            Integer signCount = null;
            if (CollectionUtil.isEmpty(rewardMap)) {
                continue;
            }
            switch (s.getType()) {
                //签到任务
                case 2:
                    //日任务
                    if (s.getNumber().equals(1)) {
//                        Integer dayOrderNum = ordersService.countOrderNum(userId, DateUtil.today() + " 00:00:00");
                        InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(userId);
                        Integer dayOrderNum = 0;
                        if (inviteAchievement != null) {
                            dayOrderNum = inviteAchievement.getCount();
                        }
                        if (dayOrderNum < 3) {
                            s.setDiscNumber(dayOrderNum);
                            s.setNumber(3);
                            todaySign = false;
                        } else if (recordService.countTaskNum(userId, s.getId(), DateUtil.today() + " 00:00:00") > 0) {
                            s.setButtonTitle("已领取");
                            s.setNumber(null);
                        } else {
                            s.setDiscNumber(0);
                            s.setNumber(null);
                            s.setJumpType(0);
                        }
                    } else {
                        //周任务
                        if (s.getNumber() > 1 && s.getNumber() < 8) {
                            if (rewardMap.containsKey(9)) {
                                boolean isBreak = false;
                                //抽奖次数
                                Map<Long, Integer> taskWCount = signRecordService.getTaskWCount(userId, rewardMap.get(9));
                                if (CollectionUtil.isNotEmpty(taskWCount)) {
                                    for (Integer value : taskWCount.values()) {
                                        if (value > 0) {
                                            isBreak = true;
                                            break;
                                        }
                                    }
                                    if (isBreak) {
                                        s.setDiscNumber(null);
                                        s.setNumber(null);
                                        break;
                                    }
                                }
                            }
                            Integer wSignCount = signRecordService.getWSignCount(userId);
                            if (wSignCount == null || wSignCount + (todaySign ? 1 : 0) < s.getNumber()) {
                                s.setDiscNumber(wSignCount == null ? 0 : wSignCount);
                                s.setDisabled(false);
                            } else {
                                s.setButtonTitle("已领取");
                                s.setDisabled(false);
                                s.setNumber(null);
                            }
                        }
                        //月任务
                        else if (s.getNumber() > 7 && s.getNumber() < 32) {
                            if (signCount == null) {
                                signCount = signRecordService.getUserSignCount(userId);
                            }
                            if (signCount + (todaySign ? 1 : 0) < s.getNumber()) {
                                s.setDiscNumber(signCount);
                                s.setDisabled(false);
                            } else {
                                if (rewardMap.containsKey(9)) {
                                    Integer spinningCount = discSpinningRecordService.countSourceRecord(s.getId());
                                    if (spinningCount == null || rewardMap.get(9) - spinningCount > 0) {
                                        s.setDiscNumber(null);
                                        s.setNumber(null);
                                        break;
                                    } else {
                                        s.setButtonTitle("已领取");
                                        s.setDisabled(false);
                                        s.setDiscNumber(null);
                                        s.setNumber(null);
                                    }
                                } else {
                                    if (recordService.countTaskNum(userId, s.getId(), DateUtil.beginOfMonth(new Date()) + " 00:00:00") > 0) {
                                        s.setButtonTitle("已领取");
                                        s.setDisabled(false);
                                        s.setNumber(null);
                                        s.setDiscNumber(null);
                                    } else {
                                        s.setDiscNumber(null);
                                        s.setNumber(null);
                                    }
                                }
                            }
                        }
                    }
                    break;
                //一次性任务
                case 3:
                    if (s.getId().equals(1L)) {
//                        Integer sumOrderNum = ordersService.countOrderNum(userId, null);
                        InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(userId);
                        Integer sumOrderNum = 0;
                        if (inviteAchievement != null) {
                            sumOrderNum = inviteAchievement.getCount();
                        }
                        if (sumOrderNum != null && sumOrderNum < s.getNumber()) {
                            s.setDiscNumber(sumOrderNum);
                            s.setNumber(s.getNumber());
                        } else if (recordService.countTaskNum(userId, s.getId(), null) > 0) {
                            continue;
                        } else {
                            s.setDiscNumber(0);
                            s.setNumber(null);
                            s.setJumpType(0);
                        }
                    } else if (s.getDetail().contains("绑定支付宝")) {
                        UserEntity userInfo = userService.queryByUserId(userId);
                        if (StringUtils.isNotBlank(userInfo.getZhiFuBao()) && StringUtils.isNotBlank(userInfo.getZhiFuBaoName())) {
                            continue;
                        }
                    }
                    break;
            }
            resultTask.add(s);
        }
        return Result.success().put("data", resultTask);
    }

    @Override
    @Transactional
    public Result taskReceive(Long userId, Long id) {
        TaskCenter taskCenter = baseMapper.selectById(id);

        if (taskCenter.getType().equals(2)) {
            Integer dayOrderNum = ordersService.countOrderNum(userId, DateUtil.today() + " 00:00:00");
            if (taskCenter.getNumber().equals(1)) {
                UserSignRecord yesterday = signRecordService.getOne(new QueryWrapper<UserSignRecord>().eq("user_id", userId).eq("sign_day",
                        DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd")));
                UserSignRecord signRecord = new UserSignRecord();
                if (yesterday != null && yesterday.getDay() != null && yesterday.getDay() != 7) {
                    signRecord.setDay(yesterday.getDay() + 1);
                } else {
                    signRecord.setDay(1);
                }
                signRecord.setUserId(userId);
                signRecord.setSignDay(DateUtil.today());
                signRecord.setCreateTime(new Date());
                if (dayOrderNum < 3) {
                    return Result.error("领取失败，未达成领取条件");
                }
                if (recordService.countTaskNum(userId, taskCenter.getId(), DateUtil.today() + " 00:00:00") > 0) {
                    return Result.error("不可重复领取");
                }
                signRecordService.save(signRecord);
            }
        } else if (taskCenter.getType().equals(3) && taskCenter.getId().equals(1L)) {
            InviteAchievement inviteAchievement = inviteAchievementService.getByUserId(userId);
            Integer sumOrderNum = 0;
            if (inviteAchievement != null) {
                sumOrderNum = inviteAchievement.getCount();
            }
//            Integer sumOrderNum = ordersService.countOrderNum(userId, null);
            if (sumOrderNum != null && sumOrderNum < taskCenter.getNumber()) {
                return Result.error("领取失败，未达成领取条件");
            } else if (recordService.countTaskNum(userId, taskCenter.getId(), null) > 0) {
                return Result.error("不可重复领取");
            }
        }
        List<TaskCenterRecord> records = new ArrayList<>();
        Long targetId = null;
        QueryWrapper<TaskCenterReward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", id);
        List<TaskCenterReward> list = taskCenterRewardService.list(queryWrapper);
        for (TaskCenterReward reward : list) {
            switch (reward.getType()) {
                case 1:
                    UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails(
                            userId, null, null, "[任务中心]", 7, 1, 2,
                            new BigDecimal(reward.getNumber()), taskCenter.getTitle() + "任务完成,金币奖励" + reward.getNumber(), 2, reward.getTaskId());

                    userMoneyService.updateMoney(1, userId, reward.getNumber());
                    userMoneyDetailsService.save(userMoneyDetails1);
                    targetId = userMoneyDetails1.getId();
                    break;
                case 2:
                    UserMoneyDetails userMoneyDetails2 = new UserMoneyDetails(
                            userId, null, null, "[任务中心]", 7, 1, 2,
                            new BigDecimal(reward.getNumber()), taskCenter.getTitle() + "任务完成,现金奖励" + reward.getNumber(), 1, reward.getTaskId());

                    userMoneyService.updateAmount(1, userId, reward.getNumber());
                    userMoneyDetailsService.save(userMoneyDetails2);
                    targetId = userMoneyDetails2.getId();
                    break;
                default:
                    break;
            }
            TaskCenterRecord record = new TaskCenterRecord();
            record.setUserId(userId);
            record.setTaskId(id);
            record.setType(reward.getType());
            record.setNumber(reward.getNumber());
            record.setName(taskCenter.getTitle() + ":" + record.getName());
            record.setTargetId(targetId);
            record.setCreateTime(DateUtil.now());
            record.setUpdateTime(DateUtil.now());
            records.add(record);
        }
        recordService.saveBatch(records);
        return Result.success();
    }

    @Override
    public int countTaskDisc(Long userId, String type) {
        int countTaskDisc = 0;
        Integer signCount = null;
        if (StringUtils.isBlank(type) || "1".equals(type)) {
            return 0;
        }
        QueryWrapper<TaskCenter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 2);
        if ("2".equals(type)) {
            queryWrapper.gt("number", 1);
            queryWrapper.lt("number", 8);
        } else if ("3".equals(type)) {
            queryWrapper.gt("number", 7);
            queryWrapper.lt("number", 32);
        }
        List<TaskCenter> taskCenters = baseMapper.selectList(queryWrapper);
        for (TaskCenter taskCenter : taskCenters) {
            Map<Integer, Integer> rewardMap = taskCenterRewardService.getRewardMap(taskCenter.getId());
            if (CollectionUtil.isEmpty(rewardMap)) {
                continue;
            }
            Map<Integer, Integer> taskWRedisMap = new HashMap<>();
            if ("2".equals(type)) {
                //抽奖次数
                Map<Long, Integer> taskWCount = signRecordService.getTaskWCount(userId, rewardMap.get(9));
                if (CollectionUtil.isNotEmpty(taskWCount)) {
                    for (Map.Entry<Long, Integer> entry : taskWCount.entrySet()) {
                        Long key = entry.getKey();
                        Integer value = entry.getValue();
                        if (value > 0) {
                            countTaskDisc = countTaskDisc + value;
                            taskWRedisMap.put(key.intValue(), value);
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(taskWRedisMap)) {
                    redisUtils.set(RedisKeys.getDateKey("spinning:amount:taskW") + userId, taskWRedisMap, DateUtils.todayAfterSecond());
                }
            } else if ("3".equals(type)) {
                if (signCount == null) {
                    signCount = signRecordService.getUserSignCount(userId);
                }
                if (signCount >= taskCenter.getNumber()) {
                    if (rewardMap.containsKey(9)) {
                        Integer spinningCount = discSpinningRecordService.countSourceRecord(taskCenter.getId());
                        countTaskDisc = rewardMap.get(9) + (spinningCount == null ? 0 : spinningCount);
                        if (countTaskDisc > 0) {
                            taskWRedisMap.put(taskCenter.getId().intValue(), countTaskDisc);
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(taskWRedisMap)) {
                    redisUtils.set(RedisKeys.getDateKey("spinning:amount:taskM") + userId, taskWRedisMap, DateUtils.todayAfterSecond());
                }
            }
        }
        return countTaskDisc;
    }
}

