package com.game.business.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.game.business.domain.*;
import com.game.business.dto.AppGameItemDTO;
import com.game.business.service.IAppGameClassifyService;
import com.game.business.service.IAppGameService;
import com.game.business.vo.AppGameBettingVO;
import com.game.business.vo.AppGameItemVO;
import com.game.common.core.domain.HttpRetArr;
import com.game.common.core.domain.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.game.common.annotation.Log;
import com.game.common.core.controller.BaseController;
import com.game.common.core.domain.AjaxResult;
import com.game.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.game.business.service.IAppGameItemService;
import com.game.common.utils.poi.ExcelUtil;
import com.game.common.core.page.TableDataInfo;

/**
 * 游戏选项Controller
 * 
 * @author game
 * @date 2024-06-29
 */
@RestController
@RequestMapping("/business/game_item")
@Api(value = "AppGameItemController", description = "游戏选项接口", tags = {"游戏选项"})
public class AppGameItemController extends BaseController
{
    @Autowired
    private IAppGameItemService appGameItemService;

    @Autowired
    private IAppGameClassifyService appGameClassifyService;

    @Autowired
    private IAppGameService appGameService;

    /**
     * 查询游戏选项列表
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询游戏选项列表", notes = "获取游戏选项列表")
    public TableDataInfo<AppGameItem> list(AppGameItem appGameItem)
    {

        startPage();
        List<AppGameItem> list = appGameItemService.selectAppGameItemList(appGameItem);
        return getDataTable(list);
    }

    /**
     * 查询游戏选项列表
     */
//    @PreAuthorize("@ss.hasPermi('business:game_item:list')")
    @GetMapping("/allList")
    @ApiOperation(value = "查询游戏选项列表", notes = "获取游戏选项列表")
    public R<List<AppGameItem>> allList(AppGameItem appGameItem)
    {
        List<AppGameItem> list = appGameItemService.selectAppGameItemList(appGameItem);
        return R.ok(list);
    }

    /**
     * 查询游戏选项列表
     */
    @GetMapping("/listAll")
    @ApiOperation(value = "查询游戏所有选项", notes = "查询游戏所有选项")
    public HttpRetArr<AppGameItemVO> listAll(AppGameItem appGameItem)
    {
        List<AppGameItemVO> resultList = new ArrayList<>();
        List<AppGameItem> list = appGameItemService.selectAppGameItemList(appGameItem);

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

            int lotterySum = list.stream().mapToInt(AppGameItem::getLotteryCount).sum();
            BigDecimal lotteryCountSum = new BigDecimal(lotterySum);

            for (int i = 0; i < list.size(); i++) {
                AppGameItem gameItem = list.get(i);
                AppGameItemVO appGameItemVO = new AppGameItemVO();
                BeanUtils.copyProperties(gameItem, appGameItemVO);
                if(gameItem.getLotteryCount() == null || gameItem.getLotteryCount() == 0){
                    appGameItemVO.setLotteryRate("0.00");
                }else{
                    BigDecimal lotteryCount = new BigDecimal(gameItem.getLotteryCount());
                    BigDecimal lotteryRate = lotteryCount.divide(lotteryCountSum,4, BigDecimal.ROUND_HALF_UP);
                    appGameItemVO.setLotteryRate(lotteryRate.multiply(new BigDecimal(100)).setScale(2,  BigDecimal.ROUND_HALF_UP).toString());
                }

                resultList.add(appGameItemVO);
            }
        }

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

    /**
     * 导出游戏选项列表
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:export')")
    @Log(title = "游戏选项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出游戏选项列表", notes = "导出游戏选项列表")
    public void export(HttpServletResponse response, AppGameItem appGameItem)
    {
        List<AppGameItem> list = appGameItemService.selectAppGameItemList(appGameItem);
        ExcelUtil<AppGameItem> util = new ExcelUtil<AppGameItem>(AppGameItem.class);
        util.exportExcel(response, list, "游戏选项数据");
    }

    /**
     * 获取游戏选项详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取游戏选项详细信息", notes = "获取游戏选项详细信息")
    public R<AppGameItem> getInfo(@PathVariable("id") Long id)
    {
        return R.ok(appGameItemService.selectAppGameItemById(id));
    }

    /**
     * 新增游戏选项
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:add')")
    @Log(title = "游戏选项", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增游戏选项", notes = "新增游戏选项")
    @PostMapping
    public R add(@RequestBody AppGameItem appGameItem)
    {
        return R.ok(appGameItemService.insertAppGameItem(appGameItem));
    }

    /**
     * 修改游戏选项
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:edit')")
    @Log(title = "游戏选项", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改游戏选项", notes = "修改游戏选项")
    @PutMapping
    public R edit(@RequestBody AppGameItem appGameItem)
    {
        return R.ok(appGameItemService.updateAppGameItem(appGameItem));
    }

    /**
     * 删除游戏选项
     */
    @PreAuthorize("@ss.hasPermi('business:game_item:remove')")
    @Log(title = "游戏选项", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除游戏选项", notes = "删除游戏选项")
	@DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids)
    {
        return R.ok(appGameItemService.deleteAppGameItemByIds(ids));
    }



    /**
     * 同步游戏选项
     */
    @ApiOperation(value = "同步游戏选项", notes = "同步游戏选项")
    @PostMapping("/synItem")
    public R synItem(@RequestBody AppGameItemDTO appGameItemDTO)
    {
        if(StringUtils.isBlank(appGameItemDTO.getClassId())){
            return R.fail("平台ID为空");
        }

        AppGameClassify appGameClassify = appGameClassifyService.getByCode(appGameItemDTO.getClassId());

        if(appGameClassify == null){
            return R.fail("平台ID不正确");
        }

        if(StringUtils.isBlank(appGameItemDTO.getGameId())){
            return R.fail("平台不存在");
        }

        AppGame appGame = appGameService.selectAppGameByClassIdAndCode(appGameClassify.getId(), appGameItemDTO.getGameId());

        if(appGame == null){
            return R.fail("游戏不存在");
        }

        if(StringUtils.isBlank(appGameItemDTO.getConfig())){
            return R.fail("游戏赔率配置为空");
        }

        AppGameItem appGameItem = new AppGameItem();
        appGameItem.setGameId(appGame.getId());
        List<AppGameItem> itemList = appGameItemService.selectAppGameItemList(appGameItem);
        if(itemList == null || itemList.isEmpty()){
            return R.fail("游戏未配置选项设置");
        }

        String[] configArry = appGameItemDTO.getConfig().split(",");

        if(itemList.size() != configArry.length){
            return R.fail("游戏赔率配置长度与选项长度不一致");
        }

        // 升序排序
        Collections.sort(itemList, Comparator.comparing(AppGameItem::getItemLocation));

        for (int i = 0; i < itemList.size(); i++) {
            AppGameItem gameItem = itemList.get(i);
            gameItem.setItemMultiple(Double.valueOf(configArry[i]));
            appGameItemService.updateAppGameItem(gameItem);
        }
        return R.ok("同步成功");
    }

    /**
     * 获取游戏选项
     */
    @ApiOperation(value = "获取游戏选项", notes = "获取游戏选项")
    @GetMapping("/getSynItem")
    public R getSynItem(AppGameItemDTO appGameItemDTO)
    {
        if(StringUtils.isBlank(appGameItemDTO.getClassId())){
            return R.fail("平台ID为空");
        }

        AppGameClassify appGameClassify = appGameClassifyService.getByCode(appGameItemDTO.getClassId());

        if(appGameClassify == null){
            return R.fail("平台ID不正确");
        }

        if(StringUtils.isBlank(appGameItemDTO.getGameId())){
            return R.fail("平台不存在");
        }

        AppGame appGame = appGameService.selectAppGameByClassIdAndCode(appGameClassify.getId(), appGameItemDTO.getGameId());

        if(appGame == null){
            return R.fail("游戏不存在");
        }

        AppGameItem appGameItem = new AppGameItem();
        appGameItem.setGameId(appGame.getId());
        List<AppGameItem> itemList = appGameItemService.selectAppGameItemList(appGameItem);
        if(itemList == null || itemList.isEmpty()){
            return R.fail("游戏未配置选项设置");
        }

        // 升序排序
        Collections.sort(itemList, Comparator.comparing(AppGameItem::getItemLocation));
        String config = "";
        for (int i = 0; i < itemList.size(); i++) {
            AppGameItem gameItem = itemList.get(i);
            if(StringUtils.isBlank(config)){
                config = gameItem.getItemMultiple() + "";
            }else{
                config = config + "," + gameItem.getItemMultiple() + "";
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("config", config);
        return R.ok(jsonObject);
    }
}
