package com.game.business.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.game.business.domain.AppChargeChannel;
import com.game.business.domain.AppUsersCharge;
import com.game.business.domain.FinTranRecord;
import com.game.business.dto.RestPwdDto;
import com.game.business.dto.UserChargeDto;
import com.game.business.dto.UserWithdrawDto;
import com.game.business.service.IAppChargeChannelService;
import com.game.business.service.IAppUsersChargeService;
import com.game.business.service.IFinTranRecordService;
import com.game.business.task.AppUserCountTask;
import com.game.business.util.Md5Utils;
import com.game.common.constant.AppSceneType;
import com.game.common.constant.finance.FinTranAddedInfo;
import com.game.common.constant.finance.FinTranType1;
import com.game.common.constant.finance.FinTranType3;
import com.game.common.constant.finance.TranCurrencyType;
import com.game.common.core.domain.HttpRet;
import com.game.common.core.domain.R;
import com.game.common.core.redis.RedisCache;
import com.game.common.utils.SecurityUtils;
import lombok.extern.log4j.Log4j2;
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.validation.annotation.Validated;
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 com.game.common.annotation.DataSource;
import com.game.common.enums.DataSourceType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.game.business.domain.AppUser;
import com.game.business.service.IAppUserService;
import com.game.common.utils.poi.ExcelUtil;
import com.game.common.core.page.TableDataInfo;

/**
 * app用户Controller
 * 
 * @author game
 * @date 2024-06-18
 */
@RestController
@RequestMapping("/business/user")
@Api(value = "AppUserController", description = "app用户接口", tags = {"app用户"})
@Log4j2
public class AppUserController extends BaseController
{
    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppUsersChargeService appUsersChargeService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAppChargeChannelService appChargeChannelService;

    @Autowired
    private IFinTranRecordService finTranRecordService;

    @Autowired
    private AppUserCountTask appUserCountTask;

    /**
     * 查询app用户列表
     */
    @PreAuthorize("@ss.hasPermi('business:user:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询app用户列表", notes = "获取app用户列表")
    public TableDataInfo list(AppUser appUser)
    {
        startPage();
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        return getDataTable(list);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('business:user:restPwd')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PostMapping("/restPwd")
    @ApiOperation(value = "重置密码", notes = "重置密码")
    public R<String> restPwd(HttpServletResponse response,@RequestBody @Validated RestPwdDto restPwdDto)
    {
        AppUser appUser = appUserService.selectAppUserByUserid(restPwdDto.getUserId());
        if(null == appUser){
            return R.fail("重置失败，用户不存在");
        }
        AppUser updateUser = new AppUser();
        updateUser.setUserid(appUser.getUserid());
        updateUser.setSalt(appUser.getSalt());
        if(StringUtils.isBlank(updateUser.getSalt())){
            updateUser.setSalt(RandomUtil.randomString(6));
        }
        updateUser.setPassword(Md5Utils.md5(Md5Utils.md5(restPwdDto.getPassword()) + updateUser.getSalt()));
        appUserService.updateAppUser(updateUser);
        //清除用户缓存
        redisCache.deleteObject("U:UserInfo:".concat(String.valueOf(appUser.getUserid())));
        return R.ok("重置成功");
    }

    /**
     * 充值
     */
    @PreAuthorize("@ss.hasPermi('business:user:charge')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PostMapping("/charge")
    @ApiOperation(value = "充值", notes = "充值")
    public R<String> charge(HttpServletResponse response,@RequestBody @Validated UserChargeDto userChargeDto)
    {
        AppUser appUser = appUserService.selectAppUserByUserid(userChargeDto.getUserId());
        if(null == appUser){
            return R.fail("充值失败，用户不存在");
        }
        String remark = "后台充值";

        if(null == userChargeDto.getChannelId() || -1 == userChargeDto.getChannelId().longValue()){
            remark = "后台充值";
        }else{
            AppChargeChannel channel = appChargeChannelService.selectAppChargeChannelById(userChargeDto.getChannelId());
            if(null == channel){
                return R.fail("充值渠道错误");
            }
            userChargeDto.setRate(channel.getRate());
            remark = "后台充值补单，渠道：".concat(channel.getName());
        }
        Long groupId = IdUtil.getSnowflakeNextId();
        /*if(StringUtils.isNotBlank(userChargeDto.getRemark())){
            String r = userChargeDto.getRemark().replace("后台充值","");
            remark = remark.concat(",").concat(r);
        }*/
        //流水 余额
        FinTranAddedInfo addedInfo = FinTranAddedInfo.createTranInfo(appUser.getUserid(), 0, 0, AppSceneType.Scene_None, "");
        FinTranRecord tran = null;
        if(userChargeDto.getType() == 0){
            tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.CHARGE_IN_Back, userChargeDto.getAmount()<0?FinTranType1.U_Outcome_Coin:FinTranType1.U_Income_Coin, appUser);
            tran.setCoinChange(userChargeDto.getAmount());
            tran.setCurrencyType(TranCurrencyType.Coin.getType());
        }else{
            tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.CHARGE_IN_Back, userChargeDto.getAmount()<0?FinTranType1.U_Outcome_Balance:FinTranType1.U_Income_Coin_Balance, appUser);
            tran.setDiamondCoinChange(userChargeDto.getAmount());
            tran.setCurrencyType(TranCurrencyType.Balance.getType());
        }
        tran.setTranGroupId(groupId);
        tran.setRemarks(remark);

        try {
            appUserService.updateUserAmount(tran);
            BigDecimal rate = BigDecimal.ZERO;
            if(null != userChargeDto.getRate() && userChargeDto.getRate() > 0 && userChargeDto.getAmount() > 0){
                if(userChargeDto.getRate() > 1){
                    return R.fail("超过最大手续费扣除");
                }
                //扣除手续费
                FinTranRecord rateTran = new FinTranRecord();
                rateTran.setId(null);
                BeanUtils.copyProperties(tran,rateTran);
                if(TranCurrencyType.Balance.getType() == rateTran.getCurrencyType()){
                    rate = BigDecimal.valueOf(rateTran.getDiamondCoinChange() * userChargeDto.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    rateTran.setDiamondCoinChange(rate.doubleValue() * -1);
                }else if(TranCurrencyType.Coin.getType() == rateTran.getCurrencyType()){
                    rate = BigDecimal.valueOf(rateTran.getCoinChange() * userChargeDto.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    rateTran.setCoinChange(rate.doubleValue() * -1);
                }
                /*rateTran.setTranType3(FinTranType3.CHARGE_OUT_RATE.getType());
                rateTran.setTranType2(FinTranType3.CHARGE_OUT_RATE.getTranType2().getType());
                rateTran.setTranType1(userChargeDto.getType() == 1?FinTranType1.U_Outcome_Balance.getType():FinTranType1.U_Outcome_Coin.getType());
                rateTran.setRemarks("充值手续费");

                appUserService.updateUserAmount(rateTran);*/
            }
            double give = 0;
//            if(null != userChargeDto.getGiveAmount() && userChargeDto.getGiveAmount() > 0){
                //今日已赠送金额
                double todayGiveMoney = appUsersChargeService.isChargeToday(userChargeDto.getUserId());
                double giveRate = todayGiveMoney>0?0.02:0.1; //当然首充10% 否则2%
                if(todayGiveMoney < 2000) { //当日2000封顶
                    give = BigDecimal.valueOf(userChargeDto.getAmount().doubleValue()
                            * giveRate).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if((give + todayGiveMoney) > 2000){
                        give = give - (give + todayGiveMoney - 2000); //赠送金额超过2000则扣减多出的余额
                    }
                    //赠送
                    FinTranRecord giveTran = new FinTranRecord();
                    BeanUtils.copyProperties(tran, giveTran);
                    if (TranCurrencyType.Balance.getType() == giveTran.getCurrencyType()) {
                        giveTran.setDiamondCoinChange(give);
                    } else if (TranCurrencyType.Coin.getType() == giveTran.getCurrencyType()) {
                        giveTran.setCoinChange(give);
                    }
                    giveTran.setTranType3(FinTranType3.CHARGE_IN_SEND.getType());
                    giveTran.setTranType2(FinTranType3.CHARGE_IN_SEND.getTranType2().getType());
                    giveTran.setTranType1(userChargeDto.getType() == 1 ? FinTranType1.U_Income_Coin_Balance.getType() : FinTranType1.U_Income_Coin.getType());
                    giveTran.setRemarks("充值赠送");
                    giveTran.setId(null);
                    appUserService.updateUserAmount(giveTran);
                }
//            }
            AppUser afterUser = appUserService.selectAppUserByUserid(userChargeDto.getUserId());
            //充值记录
            AppUsersCharge appUsersCharge = new AppUsersCharge();
//            appUsersCharge.id = charge.id;
            appUsersCharge.setTouid(appUser.getUserid());
            appUsersCharge.setUid(appUser.getUserid());

            appUsersCharge.setCoin(BigDecimal.valueOf(userChargeDto.getAmount()));
            appUsersCharge.setCoinType(Long.parseLong(String.valueOf(userChargeDto.getType())));
            appUsersCharge.setOrderno(String.valueOf(groupId));
            // 充值成功
            appUsersCharge.setStatus(1L);
            // 人工充值
            appUsersCharge.setType(4L);
            // 人工
            appUsersCharge.setAmbient(1L);
            // 操作人
            appUsersCharge.setOptUser(String.valueOf(SecurityUtils.getUserId()));
            // 操作类型 1：充值金币 2：扣减金币
            appUsersCharge.setOptType(userChargeDto.getAmount()<0?2L:1L);
            //赠送金额
            appUsersCharge.setCoinGive(BigDecimal.valueOf(give));
            appUsersCharge.setAddtime(new Date());
            appUsersCharge.setPlatformService(rate.doubleValue());
            appUsersCharge.setPlatformServiceRate(userChargeDto.getRate());
            appUsersCharge.setAfterCoin(userChargeDto.getType()==0?BigDecimal.valueOf(afterUser.getCoin()):BigDecimal.valueOf(afterUser.getDiamondCoin()));
            appUsersChargeService.insertAppUsersCharge(appUsersCharge);
        } catch (Exception e) {
            log.info("{}充值失败：{}",userChargeDto.getUserId(),e.getMessage());
            return  R.fail("充值失败");
        }
        return R.ok("充值成功");
    }

    /**
     * 补足提现流水
     */
    @PreAuthorize("@ss.hasPermi('business:user:charge')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PostMapping("/withdraw")
    @ApiOperation(value = "补足提现流水", notes = "补足提现流水")
    public R<String> withdraw(HttpServletResponse response,@RequestBody @Validated UserWithdrawDto withdrawDto)
    {
        AppUser appUser = appUserService.selectAppUserByUserid(withdrawDto.getUserId());
        if(null == appUser){
            return R.fail("补足流水失败，用户不存在");
        }
        try{
            //流水 余额
            FinTranAddedInfo addedInfo = FinTranAddedInfo.createTranInfo(appUser.getUserid(), 0, 0, AppSceneType.Scene_None, "");
            FinTranRecord tran = null;
            tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.CHARGE_IN_Back, FinTranType1.U_Income_Coin_Balance, appUser);
            tran.setDiamondCoinChange(withdrawDto.getAmount());
            tran.setAfterDiamondCoin(appUser.getDiamondCoin());
            tran.setCurrencyType(TranCurrencyType.Balance.getType());
            tran.setTranGroupId(IdUtil.getSnowflakeNextId());
            tran.setRemarks("补充提现流水");
            finTranRecordService.insertFinTranRecord(tran);
            appUserCountTask.calculationWithdraw(tran.getUid());
        } catch (Exception e) {
            log.info("{}补足流水失败：{}",withdrawDto.getUserId(),e.getMessage());
            return  R.fail("补足流水失败");
        }
        return R.ok("补足流水成功");
    }

    /**
     * 导出app用户列表
     */
    @PreAuthorize("@ss.hasPermi('business:user:export')")
    @Log(title = "app用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出app用户列表", notes = "导出app用户列表")
    public void export(HttpServletResponse response, AppUser appUser)
    {
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        ExcelUtil<AppUser> util = new ExcelUtil<AppUser>(AppUser.class);
        util.exportExcel(response, list, "app用户数据");
    }

    /**
     * 获取app用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:user:query')")
    @GetMapping(value = "/{userid}")
    @ApiOperation(value = "获取app用户详细信息", notes = "获取app用户详细信息")
    public AjaxResult getInfo(@PathVariable("userid") Long userid)
    {
        return success(appUserService.selectAppUserByUserid(userid));
    }

    /**
     * 新增app用户
     */
    @PreAuthorize("@ss.hasPermi('business:user:add')")
    @Log(title = "app用户", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增app用户", notes = "新增app用户")
    @PostMapping
    public AjaxResult add(@RequestBody AppUser appUser)
    {
        return toAjax(appUserService.insertAppUser(appUser));
    }

    /**
     * 修改app用户
     */
    @PreAuthorize("@ss.hasPermi('business:user:edit')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改app用户", notes = "修改app用户")
    @PutMapping
    public AjaxResult edit(@RequestBody AppUser appUser)
    {
        return toAjax(appUserService.updateAppUser(appUser));
    }

    /**
     * 删除app用户
     */
    @PreAuthorize("@ss.hasPermi('business:user:remove')")
    @Log(title = "app用户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除app用户", notes = "删除app用户")
	@DeleteMapping("/{userids}")
    public AjaxResult remove(@PathVariable Long[] userids)
    {
        return toAjax(appUserService.deleteAppUserByUserids(userids));
    }
}
