package com.game.business.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.game.business.domain.AppUserAgent;
import com.game.business.service.IAppUserAgentService;
import com.game.common.core.domain.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.domain.AppGameCommission;
import com.game.business.service.IAppGameCommissionService;
import com.game.common.utils.poi.ExcelUtil;
import com.game.common.core.page.TableDataInfo;

/**
 * 游戏佣金配置Controller
 * 
 * @author game
 * @date 2024-06-23
 */
@RestController
@RequestMapping("/business/commission")
@Api(value = "AppGameCommissionController", description = "游戏佣金配置接口", tags = {"游戏佣金配置"})
public class AppGameCommissionController extends BaseController
{
    @Autowired
    private IAppGameCommissionService appGameCommissionService;

    @Autowired
    private IAppUserAgentService appUserAgentService;

    /**
     * 查询游戏佣金配置列表
     */
    @PreAuthorize("@ss.hasPermi('business:commission:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询游戏佣金配置列表", notes = "获取游戏佣金配置列表")
    public TableDataInfo<AppGameCommission> list(AppGameCommission appGameCommission)
    {
        startPage();
        List<AppGameCommission> list = appGameCommissionService.selectAppGameCommissionList(appGameCommission);
        return getDataTable(list);
    }

    /**
     * 导出游戏佣金配置列表
     */
    @PreAuthorize("@ss.hasPermi('business:commission:export')")
    @Log(title = "游戏佣金配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出游戏佣金配置列表", notes = "导出游戏佣金配置列表")
    public void export(HttpServletResponse response, AppGameCommission appGameCommission)
    {
        List<AppGameCommission> list = appGameCommissionService.selectAppGameCommissionList(appGameCommission);
        ExcelUtil<AppGameCommission> util = new ExcelUtil<AppGameCommission>(AppGameCommission.class);
        util.exportExcel(response, list, "游戏佣金配置数据");
    }

    /**
     * 获取游戏佣金配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:commission:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取游戏佣金配置详细信息", notes = "获取游戏佣金配置详细信息")
    public R<AppGameCommission> getInfo(@PathVariable("id") Long id)
    {
        return R.ok(appGameCommissionService.selectAppGameCommissionById(id));
    }

    /**
     * 新增游戏佣金配置
     */
    @PreAuthorize("@ss.hasPermi('business:commission:add')")
    @Log(title = "游戏佣金配置", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增游戏佣金配置", notes = "新增游戏佣金配置")
    @PostMapping
    public R add(@RequestBody AppGameCommission appGameCommission)
    {
        return R.ok(appGameCommissionService.insertAppGameCommission(appGameCommission));
    }

    /**
     * 修改游戏佣金配置
     */
    @PreAuthorize("@ss.hasPermi('business:commission:edit')")
    @Log(title = "游戏佣金配置", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改游戏佣金配置", notes = "修改游戏佣金配置")
    @PutMapping
    public R edit(@RequestBody AppGameCommission appGameCommission)
    {
        return R.ok(appGameCommissionService.updateAppGameCommission(appGameCommission));
    }

    /**
     * 删除游戏佣金配置
     */
    @PreAuthorize("@ss.hasPermi('business:commission:remove')")
    @Log(title = "游戏佣金配置", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除游戏佣金配置", notes = "删除游戏佣金配置")
	@DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids)
    {
        return R.ok(appGameCommissionService.deleteAppGameCommissionByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('business:user:updateSetting')")
    @Log(title = "更新用户游戏佣金待遇", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateSetting")
    @ApiOperation(value = "更新用户游戏佣金待遇", notes = "更新用户游戏佣金待遇")
    @Transactional(rollbackFor = Exception.class)
    public R<String> updateSetting(@RequestBody AppGameCommission appGameCommission){
        AppGameCommission gameCommission = appGameCommissionService.selectAppGameCommissionById(appGameCommission.getId());
        AppUserAgent appUserAgent = appUserAgentService.selectInfo(appGameCommission.getUserId());
        if(null == appUserAgent){
            return R.fail("修改失败，用户代理信息不存在");
        }
        if(appUserAgent.getPid().doubleValue() == 0){
            return R.fail("顶级账号禁止修改");
        }
        if(null == appGameCommission.getGameRate()){
            return R.fail("费率不能为空");
        }
        if(appGameCommission.getGameRate() < 0){
            return R.fail("费率不能为负数");
        }
        //查询上级
        AppGameCommission superQuery = new AppGameCommission();
        superQuery.setUserId(appUserAgent.getPid());
        superQuery.setGameId(appGameCommission.getGameId());
        List<AppGameCommission> superGameCommissions = appGameCommissionService.selectAppGameCommissionList(superQuery);
        if(null != superGameCommissions && superGameCommissions.size()>0){
            AppGameCommission superGameCommission = superGameCommissions.get(0);
            if(superGameCommission.getGameRate() < appGameCommission.getGameRate()){
                return R.fail("修改失败，超过最大可修改值：" + superGameCommission.getGameRate());
            }
        }
        //查询下级
        /*AppGameCommission downQuery = new AppGameCommission();
        downQuery.setPid(appGameCommission.getUserId());
        downQuery.setGameId(appGameCommission.getGameId());
        List<AppGameCommission> downGameCommissions = appGameCommissionService.selectAppGameCommissionList(downQuery);
        if(null != downGameCommissions && downGameCommissions.size() > 0){
            double rate = downGameCommissions.stream().mapToDouble(e->e.getGameRate()).max().getAsDouble();
            if(appGameCommission.getGameRate() < rate){
                return R.fail("修改失败，超过最小可修改值：" + rate);
            }
        }*/
        AppGameCommission updateCommission = new AppGameCommission();
        if(null != gameCommission){
            updateCommission.setId(appGameCommission.getId());
            updateCommission.setGameId(appGameCommission.getGameId());
            updateCommission.setGameRate(appGameCommission.getGameRate());
            appGameCommissionService.updateAppGameCommission(updateCommission);
        }else{
            updateCommission.setGameId(appGameCommission.getGameId());
            updateCommission.setGameRate(appGameCommission.getGameRate());
            updateCommission.setGameName(appGameCommission.getGameName());
            updateCommission.setUserId(appGameCommission.getUserId());
            updateCommission.setPid(appUserAgent.getPid());
            appGameCommissionService.insertAppGameCommission(updateCommission);
        }
        upRate(appUserAgent.getUserId(),appGameCommission.getGameRate(),appGameCommission.getGameId());
        return R.ok("修改成功");
    }

    private void upRate(Long userId,Double rate,Long gameId){
        double newRate = rate - 0.1;
        if(newRate < 0){
            newRate = 0.0;
        }
        //查询下级大于等于当前分红比例的用户
        LambdaQueryWrapper<AppGameCommission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppGameCommission::getPid,userId);
        queryWrapper.eq(AppGameCommission::getGameId,gameId);
        queryWrapper.gt(AppGameCommission::getGameRate,newRate);//查询费率大于当前值的用户
        List<AppGameCommission> downAgents = appGameCommissionService.list(queryWrapper);
        if(null != downAgents && downAgents.size() > 0){
            for(AppGameCommission downAgent : downAgents){
                AppGameCommission updateAgent = new AppGameCommission();
                updateAgent.setId(downAgent.getId());
                updateAgent.setGameRate(newRate);
                appGameCommissionService.updateAppGameCommission(updateAgent);
                upRate(downAgent.getUserId(),newRate,gameId);
            }
        }
    }
}
