package com.sqx.modules.taskCenter.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.annotation.Debounce;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Objects;

@Slf4j
@RestController
@Api(value = "任务中心", tags = {"任务中心"})
@RequestMapping
public class TaskCenterController {
    /**
     * 服务对象
     */
    @Autowired
    private TaskCenterService taskCenterService;

    @Autowired
    private TaskCenterRecordService recordService;
    @Autowired
    private TaskCenterRewardService taskRewardService;

    @PostMapping("/taskCenter/insertTaskCenter")
    @ApiOperation("添加任务中心")
    public Result insertTaskCenter(@RequestBody TaskCenter taskCenter) {
        taskCenter.setCreateTime(DateUtil.now());
        taskCenterService.save(taskCenter);
        return Result.success();
    }

    @GetMapping("/taskCenter/{id}")
    @ApiOperation("通过Id查询详情")
    public Result selectOne(@PathVariable Integer id) {
        return Result.success().put("data", taskCenterService.getById(id));
    }

    @PostMapping("/taskCenter/updateTaskCenter")
    @ApiOperation("修改任务中心")
    public Result updateTaskCenter(@RequestBody TaskCenter taskCenter) {
        taskCenter.setUpdateTime(DateUtil.now());
        taskCenterService.updateById(taskCenter);
        return Result.success();
    }

    @PostMapping("/taskCenter/deleteTaskCenter")
    @ApiOperation("删除任务中心")
    public Result deleteTaskCenter(Long id) {
        taskCenterService.removeById(id);
        return Result.success();
    }

    @GetMapping("/taskCenter/selectTaskCenter")
    @ApiOperation("查询任务中心")
    public Result selectTaskCenter(Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        return Result.success().put("data", PageUtils.page(new PageInfo<>(taskCenterService.list(new QueryWrapper<TaskCenter>().orderByAsc("sort", "type"))),true));
    }


    @Login
    @GetMapping("/app/taskCenter/selectTaskCenter")
    @ApiOperation("App查询任务中心")
    public Result selectAppTaskCenter(@ApiIgnore @RequestAttribute("userId") Long userId) {
        return taskCenterService.queryTaskCenter(userId);
    }

    @Login
    @GetMapping("/app/taskCenter/taskReceive")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataTypeClass = Long.class),
    })
    @ApiOperation("App 任务中心 领取")
    @Debounce(interval = 1000, value = "#userId")
    public Result taskReceive(@ApiIgnore @RequestAttribute("userId") Long userId, Long id) {
        return taskCenterService.taskReceive(userId, id);
    }

    @Login
    @PostMapping("/app/taskCenter/receiveGoods")
    @ApiOperation("App 实物领取")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", dataTypeClass = Long.class, paramType = "body"),
            @ApiImplicitParam(name = "sourceId", value = "实物(物品Id)", dataTypeClass = Long.class, paramType = "body")
    })
    @Debounce(interval = 1000, value = "#userId")
    public Result receiveGoods(@ApiIgnore @RequestAttribute("userId") Long userId,@ApiIgnore TaskCenterRecord record) {
        TaskCenter task = taskCenterService.getById(record.getTaskId());
        if (Objects.isNull(task)) {
            return Result.error("任务不存在。");
        }
        if (recordService.countTaskNum(userId, record.getTaskId(), DateUtil.beginOfMonth(new Date()) + " 00:00:00") > 0) {
            return Result.error("该奖励仅可领取一次。");
        }
        TaskCenterReward reward = taskRewardService.getOne(new QueryWrapper<TaskCenterReward>()
                .eq("task_id", record.getTaskId())
                .eq("type", 3)
                .eq("id", record.getSourceId()));
        if (Objects.isNull(reward)) {
            return Result.error("该奖励不存在。");
        }
        if (reward.getSurplusNumber() == null || reward.getSurplusNumber() < 1) {
            return Result.error("暂无库存，请领取其它奖励。");
        }
        record.setNumber(1);
        record.setName(reward.getName());
        record.setUserId(userId);
        record.setType(3);
        record.setCreateTime(DateUtil.now());
        record.setUpdateTime(DateUtil.now());
        recordService.save(record);
        return Result.success();
    }

}

