package com.zanxiang.game.back.serve.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zanxiang.erp.security.annotation.PreAuthorize;
import com.zanxiang.game.back.serve.pojo.dto.*;
import com.zanxiang.game.back.serve.pojo.enums.BackUnitEnum;
import com.zanxiang.game.back.serve.pojo.vo.*;
import com.zanxiang.game.back.serve.service.*;
import com.zanxiang.module.util.exception.BaseException;
import com.zanxiang.module.util.pojo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/policy")
@Api("回传策略")
public class BackPolicyController {
    @Autowired
    private IGameBackPolicyService gameBackPolicyService;

    @ApiOperation(value = "创建回传策略")
    @PreAuthorize(permissionKey = "gameBack:policy:allOfUser")
    @GetMapping("/allOfUser")
    public ResultVO<List<GameBackPolicyVO>> allOfUser() {
        return ResultVO.ok(gameBackPolicyService.allOfUser());
    }

    @PreAuthorize(permissionKey = "gameBack:policy:list")
    @PostMapping("/list")
    @ApiOperation(value = "回传策略列表")
    public ResultVO<IPage<GameBackPolicyVO>> policyList(@Validated @RequestBody GameBackPolicyListDTO dto) {
        return ResultVO.ok(gameBackPolicyService.policyList(dto));
    }

    @PreAuthorize(permissionKey = "gameBack:policy:create")
    @PostMapping("/add")
    @ApiOperation(value = "创建回传策略")
    public ResultVO<Boolean> createPolicy(@Validated @RequestBody GameBackPolicyDTO dto) {
        checkDTO(dto);
        return ResultVO.ok(gameBackPolicyService.createPolicy(dto));
    }

    @PreAuthorize(permissionKey = "gameBack:policy:update")
    @PostMapping("/modify/{policyId}")
    @ApiOperation(value = "修改回传策略")
    public ResultVO<Boolean> updatePolicy(@PathVariable("policyId") Long policyId, @Validated @RequestBody GameBackPolicyDTO dto) {
        checkDTO(dto);
        return ResultVO.ok(gameBackPolicyService.updatePolicy(policyId, dto));
    }

    @PreAuthorize(permissionKey = "gameBack:policy:delete")
    @DeleteMapping("/del/{ids}")
    @ApiOperation(value = "删除回传策略")
    public ResultVO<Boolean> deletePolicy(@PathVariable("ids") List<Long> ids) {
        throw new BaseException("暂不支持删除回传策略！");
        // return ResultVO.ok(gameBackPolicyService.deletePolicy(ids));
    }

    private void checkDTO(GameBackPolicyDTO dto) {
        BackUnitEnum backUnit = BackUnitEnum.getByValue(dto.getBackUnit());
        if (backUnit == null) {
            throw new BaseException("错误的回传单位：" + dto.getBackUnit());
        }
        if (dto.getFirstMinMoney().compareTo(dto.getFirstMaxMoney()) >= 0) {
            throw new BaseException("首充的大额金额必须大于小额金额");
        }
        if (dto.getRechargeMinMoney().compareTo(dto.getRechargeMaxMoney()) >= 0) {
            throw new BaseException("此单的大额金额必须大于小额金额");
        }
        if (dto.getRegPayIntervalTime() != null && dto.getRegPayIntervalTime() <= 0) {
            throw new BaseException("注册充值回传的最大间隔时间不能小于 1");
        }
        if (dto.getMarkUpOrder() == null) {
            dto.setMarkUpOrder(false);
        }
        if (dto.getMarkUpOrder()) {
            if (dto.getRegPayIntervalTime() == null) {
                throw new BaseException("开启补单后必需填充值注册回传最大间隔时间");
            }
            if (dto.getMarkUpOrderMinMoney().compareTo(dto.getMarkUpOrderMaxMoney()) >= 0) {
                throw new BaseException("首充的大额金额必须大于小额金额");
            }
        }
        if (backUnit == BackUnitEnum.LARGE_AMOUNT) {
            if (dto.getLargeAmount() == null || dto.getLargeAmount().compareTo(BigDecimal.ZERO) <= 0) {
                throw new BaseException("大额判定金额错误！！！");
            }
        }
        checkDownLevel(dto.getFirstDownLevel());
        checkDownLevel(dto.getRechargeDownLevel());
        checkDownLevel(dto.getMarkUpDownLevel());
        if (dto.getFirstBackCountOfUser() != null && dto.getFirstBackCountOfUser() < 1) {
            throw new BaseException("单用户最大回传次数不能小于 1");
        }
        if (dto.getRechargeBackCountOfUser() != null && dto.getRechargeBackCountOfUser() < 1) {
            throw new BaseException("单用户最大回传次数不能小于 1");
        }
        if (dto.getMarkUpBackCountOfUser() != null && dto.getMarkUpBackCountOfUser() < 1) {
            throw new BaseException("单用户最大回传次数不能小于 1");
        }
    }

    private void checkDownLevel(List<GameBackPolicyVO.PolicyDownLevel> downLevelList) {
        if (CollectionUtils.isEmpty(downLevelList)) {
            return;
        }
        downLevelList.sort((val1, val2) -> val1.getMinMoney().compareTo(val2.getMinMoney()));
        BigDecimal compareMoney = null;
        for (GameBackPolicyVO.PolicyDownLevel downLevel : downLevelList) {
            if (downLevel.getMinMoney() == null
                    || downLevel.getMaxMoney() == null
                    || downLevel.getBackMoney() == null) {
                throw new BaseException("降档策略校验失败：金额不能为空");
            }
            if (downLevel.getMinMoney().compareTo(BigDecimal.ZERO) <= 0
                    || downLevel.getMaxMoney().compareTo(BigDecimal.ZERO) <= 0
                    || downLevel.getBackMoney().compareTo(BigDecimal.ZERO) <= 0) {
                throw new BaseException("降档策略校验失败：金额必须大于 0");
            }
            if (downLevel.getMinMoney().compareTo(downLevel.getMaxMoney()) > 0) {
                throw new BaseException("降档策略校验失败：最小金额（" + downLevel.getMinMoney() + "）> 最大金额（" + downLevel.getMaxMoney() + "）");
            }
            if (compareMoney == null) {
                compareMoney = downLevel.getMaxMoney();
            } else {
                if (compareMoney.compareTo(downLevel.getMinMoney()) >= 0) {
                    throw new BaseException("降档策略校验失败：金额区间内不能有交集！！！");
                }
            }
        }
    }
}
