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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@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;

    @Override
    public Result queryTaskCenter(Integer page, Integer limit, Long userId) {
        //任务
        IPage<TaskCenter> taskPage = baseMapper.selectPage(new Page<>(page, limit), new QueryWrapper<TaskCenter>().eq("shows", 1).orderByDesc("sort"));
        boolean todaySign = true;
        //月 签到记录
        QueryWrapper<UserSignRecord> signWrapper = new QueryWrapper<>();
        signWrapper.eq("user_id", userId);
        signWrapper.lt("sign_day", DateUtil.format(new Date(), "yyyy-MM") + "-00");
        signWrapper.orderByAsc("create_time");
        List<UserSignRecord> signRecordList = signRecordService.list(signWrapper);
        for (TaskCenter s : taskPage.getRecords()) {
            //签到任务
            if (s.getType() == 2) {
                if (s.getNumber().equals(1)) {
                    Integer dayOrderNum = ordersService.countOrderNum(userId, DateUtil.today() + " 00:00:00");
                    if (dayOrderNum < 3 || recordService.countTaskNum(userId, s.getId(), DateUtil.today() + " 00:00:00") > 0) {
                        s.setDisabled(false);
                        todaySign = false;
                    }
                } else {
                    if (todaySign) {
                        if ((signRecordList.size() < (s.getNumber().intValue() - 1)) || recordService.countTaskNum(userId, s.getId(), DateUtil.beginOfMonth(new Date()).toString()) > 0) {
                            s.setDisabled(false);
                        }
                    } else {
                        if ((signRecordList.size() < s.getNumber().intValue()) || recordService.countTaskNum(userId, s.getId(), DateUtil.beginOfMonth(new Date()).toString()) > 0) {
                            s.setDisabled(false);
                        }
                    }

                }
            }
        }
        return Result.success().put("data", taskPage);
    }

    @Override
    @Transactional
    public Result taskReceive(Long userId, Long id) {
        TaskCenter taskCenter = baseMapper.selectById(id);
        //月 签到记录
        QueryWrapper<UserSignRecord> signWrapper = new QueryWrapper<>();
        signWrapper.eq("user_id", userId);
        signWrapper.lt("sign_day", DateUtil.format(new Date(), "yyyy-MM") + "-00");
        signWrapper.orderByAsc("create_time");
        List<UserSignRecord> signRecordList = signRecordService.list(signWrapper);

        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) {
                    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 (dayOrderNum > 2) {
                    if (signRecordList.size() < (taskCenter.getNumber().intValue() - 1)) {
                        return Result.error("领取失败，未达成领取条件");
                    }
                    if (recordService.countTaskNum(userId, taskCenter.getId(), DateUtil.today() + " 00:00:00") > 0) {
                        return Result.error("不可重复领取");
                    }
                } else {
                    if (signRecordList.size() < taskCenter.getNumber().intValue()) {
                        return Result.error("领取失败，未达成领取条件");
                    }
                    if (recordService.countTaskNum(userId, taskCenter.getId(), DateUtil.today() + " 00:00:00") > 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();
                    userMoneyDetails1.setClassify(8);
                    userMoneyDetails1.setUserId(userId);
                    userMoneyDetails1.setCreateTime(DateUtil.now());
                    userMoneyDetails1.setTitle("任务中心");
                    userMoneyDetails1.setState(2);
                    userMoneyDetails1.setType(1);
                    userMoneyDetails1.setMoney(new BigDecimal(reward.getNumber()));
                    userMoneyDetails1.setContent(taskCenter.getTitle() + "任务完成,金豆奖励" + reward.getNumber());
                    userMoneyService.updateMoney(1, userId, reward.getNumber());
                    userMoneyDetailsService.save(userMoneyDetails1);
                    targetId = userMoneyDetails1.getId();
                    break;
                case 2:
                    UserMoneyDetails userMoneyDetails2 = new UserMoneyDetails();
                    userMoneyDetails2.setClassify(8);
                    userMoneyDetails2.setUserId(userId);
                    userMoneyDetails2.setCreateTime(DateUtil.now());
                    userMoneyDetails2.setTitle("任务中心");
                    userMoneyDetails2.setState(2);
                    userMoneyDetails2.setType(1);
                    userMoneyDetails2.setMoney(new BigDecimal(reward.getNumber()));
                    userMoneyDetails2.setContent(taskCenter.getTitle() + "任务完成,现金奖励" + reward.getNumber());
                    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);
            records.add(record);
        }
        recordService.saveBatch(records);
        return Result.success();
    }

    @Override
    public int countTaskDisc(Long userId) {
        //TaskCenter的number为大转盘次数
        List<TaskCenter> taskCenters = baseMapper.queryTaskDiscCenter(userId);
        //大转盘任务 校验 次数
        return 0;
    }
}

