package com.game.business.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.game.business.domain.AppGame;
import com.game.business.domain.AppGameItem;
import com.game.business.domain.AppGameItemMultiple;
import com.game.business.domain.AppGameLottery;
import com.game.business.dto.AppUserDTO;
import com.game.business.service.IAppGameItemMultipleService;
import com.game.business.service.IAppGameItemService;
import com.game.business.service.IAppGameLotteryService;
import com.game.business.service.IAppGameService;
import com.game.business.task.AppGameBettingTask;
import com.game.business.task.AppGameLotteryTask;
import com.game.business.util.Common;
import com.game.business.vo.AppGameLotteryVO;
import com.game.business.vo.AppUserAgentVO;
import com.game.common.annotation.Anonymous;
import com.game.common.annotation.Log;
import com.game.common.core.controller.BaseController;
import com.game.common.core.domain.HttpRet;
import com.game.common.core.domain.HttpRetPageArr;
import com.game.common.core.domain.R;
import com.game.common.core.page.TableDataInfo;
import com.game.common.enums.BusinessType;
import com.game.common.utils.DateUtils;
import com.game.common.utils.SecurityUtils;
import com.game.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/business/lottery")
@Api(value = "AppGameLotteryController", description = "游戏开奖接口", tags = {"游戏开奖记录"})
public class AppGameLotteryController extends BaseController{

    @Autowired
    private IAppGameLotteryService appGameLotteryService;

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private IAppGameItemService appGameItemService;

    @Autowired
    private AppGameLotteryTask appGameLotteryTask;

    @Autowired
    private IAppGameItemMultipleService appGameItemMultipleService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "游戏开奖记录", notes = "游戏开奖记录")
    public HttpRetPageArr<AppGameLotteryVO> getListByGameId(@RequestParam(name = "gameId") Long gameId, @RequestParam(name= "gameDate", required = false) String gameDate
            , @RequestParam(name= "strDate", required = false) String strDate)
    {
        startPage();

        if(StringUtils.isBlank(strDate)){
            strDate = DateUtils.getDate();
        }

        LambdaQueryWrapper<AppGameLottery> queryLotteryWrapper = Wrappers.lambdaQuery();;
        queryLotteryWrapper.eq(AppGameLottery::getGameId, gameId);
        if(StringUtils.isNotBlank(gameDate)) {
            queryLotteryWrapper.like(AppGameLottery::getGameDate, gameDate);
        }
        if(StringUtils.isNotBlank(strDate)){
            queryLotteryWrapper.between(AppGameLottery::getGameRecordDate, strDate + " 00:00:00", strDate + " 23:59:59");
        }
        queryLotteryWrapper.eq(AppGameLottery::getIsLottery, 1);
        queryLotteryWrapper.orderByDesc(AppGameLottery::getGameRecordDate).orderByDesc(AppGameLottery::getGameDate);
        List<AppGameLottery> list = appGameLotteryService.list(queryLotteryWrapper);
        List<AppGameLotteryVO> resultList = new ArrayList<>();

        if(list != null && !list.isEmpty()) {

            AppGame appGame = appGameService.selectAppGameById(gameId);
            if(appGame == null){
                return HttpRetPageArr.fail("查询失败，游戏不存在");
            }

            AppGameItem appGameItem = new AppGameItem();
            appGameItem.setGameId(gameId);
            List<AppGameItem> itemList = appGameItemService.selectAppGameItemList(appGameItem);
            Map<String, List<AppGameItem>> codeItmeMap = itemList.stream().collect(Collectors.groupingBy(AppGameItem::getItemLocation));

            Map<String, List<AppGameItemMultiple>> gameDateMap = null;

            if(appGame.getCode().equals(Common.GAME_ONE_CODE)){
                List<AppGameItemMultiple> appGameItemMultipleList = appGameItemMultipleService.getAppGameItemMultipleList(appGame.getId());
                if(appGameItemMultipleList != null && !appGameItemMultipleList.isEmpty()) {
                    gameDateMap = appGameItemMultipleList.stream().collect(Collectors.groupingBy(AppGameItemMultiple::getGameDate));
                }
            }

            for (int i = 0; i <list.size(); i++) {
                AppGameLottery appGameLottery  = list.get(i);
                AppGameLotteryVO appGameLotteryVO = new AppGameLotteryVO();
                BeanUtils.copyProperties(appGameLottery, appGameLotteryVO);

                if(StringUtils.isNotBlank(appGameLotteryVO.getGameLotterySucc())){

                    String itemName = "";
                    String itemMultiple = "";
                    List<String> multipleList = new ArrayList<>();

                    if(appGame.getCode().equals(Common.GAME_ONE_CODE)){
                        if(gameDateMap != null && gameDateMap.containsKey(appGameLottery.getGameDate())){
                            AppGameItemMultiple appGameItemMultiple = gameDateMap.get(appGameLottery.getGameDate()).get(0);
                            multipleList = Arrays.asList(appGameItemMultiple.getItemMultiple().split(","));
                        }
                    }

                    String [] itmeArr = appGameLotteryVO.getGameLotterySucc().split(",");

                    for (int j = 0; j < itmeArr.length; j++) {
                        String item = itmeArr[j];
                        if(codeItmeMap.containsKey(item)){
                            if(StringUtils.isNotBlank(itemName)){
                                itemName += "," + codeItmeMap.get(item).get(0).getItemName();
                                if(!multipleList.isEmpty()){
                                    itemMultiple += "," + Double.parseDouble(multipleList.get(Integer.parseInt(item)));
                                }else{
                                    itemMultiple += "," + codeItmeMap.get(item).get(0).getItemMultiple();
                                }
                            }else{
                                itemName += codeItmeMap.get(item).get(0).getItemName();

                                if(!multipleList.isEmpty()){
                                    itemMultiple +=  Double.parseDouble(multipleList.get(Integer.parseInt(item)));
                                }else{
                                    itemMultiple += codeItmeMap.get(item).get(0).getItemMultiple();
                                }
                            }
                        }
                    }
                    appGameLotteryVO.setItemName(itemName);
                    appGameLotteryVO.setItemMultiple(itemMultiple);
                }
                resultList.add(appGameLotteryVO);
            }
        }

//        List<AppGameLotteryDTO> resultList = new ArrayList<>();
//
//        if(list != null && !list.isEmpty()){
//            List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
//            Map<Long, List<AppGame>> idGameMap = gameList.stream().collect(Collectors.groupingBy(AppGame::getId));
//
//            for (AppGameLottery appGameLottery : list) {
//                AppGameLotteryDTO dto = new AppGameLotteryDTO();
//                if(idGameMap.containsKey(appGameLottery.getGameId())){
//                    AppGame appGame = idGameMap.get(appGameLottery.getGameId()).get(0);
//                    dto.setGamePath(appGame.getGamePath());
//                    dto.setGameName(appGame.getName());
//                    dto.setLogoUrl(appGame.getLogoUrl());
//                }
//                dto.setGameId(appGameLottery.getGameId());
//                dto.setGameDate(appGameLottery.getGameDate());
//                dto.setClassId(appGameLottery.getClassId());
//                dto.setGameLotterySucc(appGameLottery.getGameLotterySucc());
//                dto.setGameRecordDate(appGameLottery.getGameRecordDate());
//                resultList.add(dto);
//            }
//        }

        return HttpRetPageArr.success("查询成功",getDataTable(resultList));
    }

    @PostMapping("/addLottery")
    @ApiOperation(value = "手动开奖", notes = "手动开奖")
    @Log(title = "手动开奖", businessType = BusinessType.UPDATE)
    public HttpRet<Boolean> addLottery(@RequestBody AppGameLottery appGameLottery) throws Exception {

        Long userId = SecurityUtils.getUserId();

        if(userId == null){
            return HttpRet.fail("权限不足，请联系管理员");
        }

        if(userId != 10013 && SecurityUtils.getLoginUser().isBusUser()){ //app用户只有10013能发
            return HttpRet.fail("权限不足，请联系管理员");
        }

        if(StringUtils.isNotBlank(appGameLottery.getGameDate())){
            appGameLottery.setGameDate(appGameLottery.getGameDate().trim());
        }

        AppGameLottery dbAppGameLottery = appGameLotteryService.selectLottery(appGameLottery.getClassId(), appGameLottery.getGameId(), appGameLottery.getGameDate());
        if(dbAppGameLottery != null && dbAppGameLottery.getIsLottery() == 1){
            return HttpRet.fail("该游戏，当前期已自动开奖过了，不能手动开奖");
        }

        appGameLottery.setIsLottery(1);
        String time = DateUtil.format(new Date(),"yyyy-").concat(appGameLottery.getGameDate());
        appGameLottery.setGameRecordDate(DateUtil.parse(time,"yyyy-MM-dd HH:mm"));
        boolean flg = false;
        if(dbAppGameLottery == null){
            flg = appGameLotteryService.save(appGameLottery);
        }else{
            AppGameLottery updateAppGameLottery = new AppGameLottery();
            updateAppGameLottery.setId(dbAppGameLottery.getId());
            updateAppGameLottery.setIsLottery(1);
            updateAppGameLottery.setGameRecordDate(new Date());
            updateAppGameLottery.setGameLotterySucc(appGameLottery.getGameLotterySucc());
            flg =appGameLotteryService.updateById(updateAppGameLottery);
        }
        if(flg){
            appGameLotteryTask.updateLottery(appGameLottery);
        }
        return HttpRet.success("手动开奖成功",true);
    }

    /**
     * 查询游戏开奖记录列表
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询游戏开奖记录列表", notes = "获取游戏开奖记录列表")
    public TableDataInfo<AppGameLottery> list(AppGameLottery appGameLottery)
    {
        startPage();
        List<AppGameLottery> list = appGameLotteryService.selectAppGameLotteryList(appGameLottery);
        return getDataTable(list);
    }

    /**
     * 导出游戏开奖记录列表
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:export')")
    @Log(title = "游戏开奖记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出游戏开奖记录列表", notes = "导出游戏开奖记录列表")
    public void export(HttpServletResponse response, AppGameLottery appGameLottery)
    {
        List<AppGameLottery> list = appGameLotteryService.selectAppGameLotteryList(appGameLottery);
        ExcelUtil<AppGameLottery> util = new ExcelUtil<AppGameLottery>(AppGameLottery.class);
        util.exportExcel(response, list, "游戏开奖记录数据");
    }

    /**
     * 获取游戏开奖记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取游戏开奖记录详细信息", notes = "获取游戏开奖记录详细信息")
    public R<AppGameLottery> getInfo(@PathVariable("id") Long id)
    {
        return R.ok(appGameLotteryService.selectAppGameLotteryById(id));
    }

    /**
     * 新增游戏开奖记录
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:add')")
    @Log(title = "游戏开奖记录", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增游戏开奖记录", notes = "新增游戏开奖记录")
    @PostMapping
    public R add(@RequestBody AppGameLottery appGameLottery)
    {
        return R.ok(appGameLotteryService.insertAppGameLottery(appGameLottery));
    }

    /**
     * 修改游戏开奖记录
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:edit')")
    @Log(title = "游戏开奖记录", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改游戏开奖记录", notes = "修改游戏开奖记录")
    @PutMapping
    public R edit(@RequestBody AppGameLottery appGameLottery)
    {
        return R.ok(appGameLotteryService.updateAppGameLottery(appGameLottery));
    }

    /**
     * 删除游戏开奖记录
     */
    @PreAuthorize("@ss.hasPermi('business:lottery:remove')")
    @Log(title = "游戏开奖记录", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除游戏开奖记录", notes = "删除游戏开奖记录")
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids)
    {
        return R.ok(appGameLotteryService.deleteAppGameLotteryByIds(ids));
    }

}
