package com.playlet.web.service.app.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.playlet.common.exception.ServiceException;
import com.playlet.common.utils.DateUtils;
import com.playlet.common.utils.StringUtils;
import com.playlet.system.domain.*;
import com.playlet.system.service.IPlayletItemService;
import com.playlet.system.service.IPlayletRevenueRecordService;
import com.playlet.system.service.IPlayletTaskService;
import com.playlet.system.service.IPlayletUserTaskService;
import com.playlet.web.service.app.PlayletTaskAppService;
import com.playlet.web.service.app.PlayletUserTaskAppService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * @Date: 2024-03-22 00:02
 * @Author: 但星霖
 * @Version: v1.0
 * @Description: 任务app Service接口实现
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PlayletTaskAppServiceImpl implements PlayletTaskAppService {

    private final IPlayletTaskService playletTaskService;
    private final IPlayletUserTaskService iPlayletUserTaskService;
    private final PlayletUserTaskAppService playletUserTaskAppService;
    private final IPlayletRevenueRecordService revenueRecordService;
    private final IPlayletItemService playletItemService;

    @Override
    public PageInfo<PlayletTask> getTaskPage(PlayletTask playletTask, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PlayletTask> revenueRecordList = playletTaskService.selectPlayletTaskList(playletTask);
        revenueRecordList.forEach(model->{
            PlayletItem playletItem = playletItemService.getById(model.getItemId());
            if(playletItem != null){
                model.setPlayletItem(playletItem);
            }
            // 如果用户id不存在,则需要判断是否加入过该任务
            if(StringUtils.isNotEmpty(playletTask.getUserId())){
                long count = iPlayletUserTaskService.lambdaQuery()
                        .eq(PlayletUserTask::getUserId, playletTask.getUserId())
                        .eq(PlayletUserTask::getTaskId, model.getId())
                        .count();
                if(count > 0){
                    model.setIsJoin(true);
                }
            }
        });
        return PageInfo.of(revenueRecordList);
    }

    @Override
    public PageInfo<PlayletTask> getTaskPageByUser(PlayletTask playletTask, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PlayletTask> revenueRecordList = playletTaskService.selectPlayletTaskListByUser(playletTask);
        revenueRecordList.forEach(model->{
            PlayletItem playletItem = playletItemService.getById(model.getItemId());
            if(playletItem != null){
                model.setPlayletItem(playletItem);
            }
        });
        return PageInfo.of(revenueRecordList);
    }

    @Override
    public Boolean userDesignateTask(PlayletUserTask playletUserTask) {
        // 检查任务数据。
        PlayletTask task = playletTaskService.selectPlayletTaskById(playletUserTask.getTaskId());
        // 任务数据数据
        if (ObjectUtils.isNull(task)) {
            throw new ServiceException("参与任务失败，未找到匹配任务数据。");
        }
        // 任务状态
        if (task.getState() != 1) {
            throw new ServiceException("参与任务失败，任务还未开始或者已结束。");
        }
        // 是否在任务时间线内
        if (DateUtil.compare(new Date(), task.getStartTime()) >=0 &&  DateUtil.compare(new Date(), task.getEndTime())<=0) {
            long count = iPlayletUserTaskService.lambdaQuery().eq(PlayletUserTask::getUserId, playletUserTask.getUserId())
                        .eq(PlayletUserTask::getTaskId, playletUserTask.getTaskId())
                        .count();
            if(count > 0){
                throw new ServiceException("请勿重复领取任务!");
            }
            PlayletUserTask model = PlayletUserTask.dataSupplement(task);
            model.setUserId(playletUserTask.getUserId());
            // 用户数据绑定。
            playletUserTaskAppService.insertPlayletUserTask(model);
            return Boolean.TRUE;
        } else {
            throw new ServiceException("参与任务失败，任务未开始或者已结束。");
        }
    }

    /**
     * 查询任务
     *
     * @param id 任务主键
     * @return 任务
     */
    @Override
    public PlayletTask selectPlayletTaskById(Long id) {
        PlayletTask task = playletTaskService.selectPlayletTaskById(id);
        if (ObjectUtils.isNotNull(task)) {
            // 奖金划分数据查询
            List<PlayletRevenueRecord> revenueRecordList = revenueRecordService.searchByTaskId(task.getId());
            if (CollectionUtils.isNotEmpty(revenueRecordList)) {
                Long totalMoney = revenueRecordList.stream().mapToLong(PlayletRevenueRecord::getPracticalEarnings).sum();
            }
        }
        return task;
    }

    /**
     * 查询任务列表
     *
     * @param playletTask 任务
     * @return 任务
     */
    @Override
    public List<PlayletTask> selectPlayletTaskList(PlayletTask playletTask) {
        return playletTaskService.selectPlayletTaskList(playletTask);
    }

    /**
     * 新增任务
     *
     * @param playletTask 任务
     * @return 结果
     */
    @Override
    public int insertPlayletTask(PlayletTask playletTask) {
        playletTask.setCreateTime(DateUtils.getNowDate());
        return playletTaskService.insertPlayletTask(playletTask);
    }

    /**
     * 修改任务
     *
     * @param playletTask 任务
     * @return 结果
     */
    @Override
    public int updatePlayletTask(PlayletTask playletTask) {
        playletTask.setUpdateTime(DateUtils.getNowDate());
        return playletTaskService.updatePlayletTask(playletTask);
    }

    /**
     * 批量删除任务
     *
     * @param ids 需要删除的任务主键
     * @return 结果
     */
    @Override
    public int deletePlayletTaskByIds(String ids) {
        return playletTaskService.deletePlayletTaskByIds(ids);
    }

    /**
     * 删除任务信息
     *
     * @param id 任务主键
     * @return 结果
     */
    @Override
    public int deletePlayletTaskById(Long id) {
        return playletTaskService.deletePlayletTaskById(id);
    }

    @Override
    public String promotionTask(PlayletUserTask playletUserTask) {
        PlayletUserTask model = iPlayletUserTaskService.getById(playletUserTask.getId());
        if(model == null){
            throw new ServiceException("改任务不存在!");
        }
        // 检查任务数据。
        PlayletTask task = playletTaskService.selectPlayletTaskById(model.getTaskId());
        // 任务数据数据
        if (ObjectUtils.isNull(task)) {
            throw new ServiceException("参与任务失败，未找到匹配任务数据。");
        }
        model.setUserTaskState(1);
        // 将任务更新成推广中
        iPlayletUserTaskService.updateById(model);
        return "https://jumpv.qinronmedia.com/web/call?key=e9848b589167b459e98178e2e5ebfdbc";
    }

    @Override
    public PageInfo<PlayletUserTask> getPromotionTaskPage(PlayletUserTask playletUserTask, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PlayletUserTask> list = iPlayletUserTaskService.lambdaQuery()
                .eq(PlayletUserTask::getUserId, playletUserTask.getUserId())
                .ne(PlayletUserTask::getUserTaskState, 0)
                .list();
        list.forEach(model->{
            model.setPlayletTask(playletTaskService.getById(model.getTaskId()));
        });
        return PageInfo.of(list);
    }
}
