package com.game.business.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.game.business.domain.*;
import com.game.business.dto.RestPwdDto;
import com.game.business.dto.UserChargeDto;
import com.game.business.dto.UserWithdrawDto;
import com.game.business.service.*;
import com.game.business.task.AppUserCountTask;
import com.game.business.util.Md5Utils;
import com.game.business.util.im.HttpClientUtils;
import com.game.business.util.im.TencentCloudImUtil;
import com.game.business.vo.AppRechargeConfigVo;
import com.game.common.annotation.RepeatSubmit;
import com.game.common.constant.AppSceneType;
import com.game.common.constant.finance.*;
import com.game.common.core.domain.HttpRet;
import com.game.common.core.domain.HttpRetArr;
import com.game.common.core.domain.R;
import com.game.common.core.redis.RedisCache;
import com.game.common.exception.ServiceException;
import com.game.common.utils.SecurityUtils;
import com.game.system.service.ISysConfigService;
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.transaction.annotation.Transactional;
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.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 ILiveLiveService liveLiveService;

    @Autowired
    private AppUserCountTask appUserCountTask;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IAppUserGameRecordCountService appUserGameRecordCountService;

    /**
     * 查询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);
        if(null != list && list.size() > 0){
            list.forEach(e->{
                if(e.getRole().intValue() == 1){
                    e.setLiveLive(liveLiveService.selectLiveLiveByUserId(e.getUserid()));
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 查询用户直播间返佣
     */
    @PreAuthorize("@ss.hasPermi('business:user:list')")
    @GetMapping("/liveCommission")
    @ApiOperation(value = "查询用户直播间返佣", notes = "查询用户直播间返佣")
    public TableDataInfo liveCommission(Long userId)
    {
        startPage();
        List<AppUserGameRecordCount> list = appUserGameRecordCountService.liveCommission(userId);
        return getDataTable(list);
    }

    /**
     * 查询用户收到的礼物
     */
    @PreAuthorize("@ss.hasPermi('business:user:list')")
    @GetMapping("/getGift")
    @ApiOperation(value = "查询用户收到的礼物", notes = "查询用户收到的礼物")
    public TableDataInfo getGift(Long userId)
    {
        startPage();
        FinTranRecord finTranRecord = new FinTranRecord();
        finTranRecord.setTranType1(FinTranType1.U_Income_Coin.getType());
        finTranRecord.setTranType2(FinTranType2.REWARD_Income.getType());
        finTranRecord.setTranType3(FinTranType3.RECOMMEND_ADD_AMOUNT.getType());
        finTranRecord.setToUid(userId);
        List<FinTranRecord> list = finTranRecordService.selectFinTranRecordList(finTranRecord);
        return getDataTable(list);
    }

    /**
     * 查询用户收到的礼物
     */
    @GetMapping("/getGiftApp")
    @ApiOperation(value = "APP-查询用户收到的礼物", notes = "APP-查询用户收到的礼物")
    public HttpRetArr getGiftApp(Long userId)
    {
        startPage();
        FinTranRecord finTranRecord = new FinTranRecord();
        finTranRecord.setTranType1(FinTranType1.U_Income_Coin.getType());
        finTranRecord.setTranType2(FinTranType2.REWARD_Income.getType());
        finTranRecord.setTranType3(FinTranType3.RECOMMEND_ADD_AMOUNT.getType());
        finTranRecord.setToUid(userId);
        List<FinTranRecord> list = finTranRecordService.selectFinTranRecordList(finTranRecord);
        return HttpRetArr.success("查询成功",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:restPwd')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PostMapping("/restPayPwd")
    @ApiOperation(value = "重置密码", notes = "重置密码")
    public R<String> restPayPwd(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.setFundPassword(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 = "充值")
    @RepeatSubmit(message = "频繁操作")
    @DSTransactional
    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 {
            /*if(null != userChargeDto.getChannelId() && userChargeDto.getChannelId() > 0){
                AppChargeChannel channel = appChargeChannelService.selectAppChargeChannelById(userChargeDto.getChannelId());
                userChargeDto.setRate(channel.getRate());
            }*/
            appUserService.updateUserAmount(tran,false);
            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(4,BigDecimal.ROUND_HALF_UP);
                    rateTran.setDiamondCoinChange(rate.doubleValue() * -1);
                }else if(TranCurrencyType.Coin.getType() == rateTran.getCurrencyType()){
                    rate = BigDecimal.valueOf(rateTran.getCoinChange() * userChargeDto.getRate()).setScale(4,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;
            //查询赠送配置
            AppRechargeConfigVo configVo = appUsersChargeService.getRechargeConfig();
            if(userChargeDto.getType() == 1
                    && userChargeDto.getAmount() > 0
                    && null != userChargeDto.getRate()
                    && userChargeDto.getRate() > 0
            ) { //金币充值不赠送
//            if(null != userChargeDto.getGiveAmount() && userChargeDto.getGiveAmount() > 0){
                //今日已赠送金额
                double todayGiveMoney = appUsersChargeService.isChargeToday(userChargeDto.getUserId(),userChargeDto.getType());
                double giveRate = todayGiveMoney>0?configVo.getSend()/100:configVo.getFirstSend()/100; //当然首充10% 否则2%
                if(todayGiveMoney < configVo.getMaxSend() && giveRate > 0) { //当日2000封顶
                    give = BigDecimal.valueOf(userChargeDto.getAmount().doubleValue()
                            * giveRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if((give + todayGiveMoney) > configVo.getMaxSend()){
                        give = give - (give + todayGiveMoney - configVo.getMaxSend()); //赠送金额超过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,false);
                }
            }
            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.setChannelId(userChargeDto.getChannelId());
            //赠送金额
            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);

            JSONObject paramJson = new JSONObject();
            paramJson.put("type", "UserSystemNotify");
            paramJson.put("subType", "UserRefreshBalance");
            paramJson.put("content", JSONObject.parseObject("{'msg':'刷新余额'}"));
            TencentCloudImUtil.imPushBatchSendMsg(Arrays.asList(String.valueOf(appUsersCharge.getUid())), paramJson.toString());

        } catch (Exception e) {
            log.info("{}充值失败：{}",userChargeDto.getUserId(),e);
            throw new ServiceException("充值失败");
        }
        return R.ok("充值成功");
    }

    /**
     * 补足提现流水
     */
    @PreAuthorize("@ss.hasPermi('business:user:charge')")
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PostMapping("/withdraw")
    @ApiOperation(value = "补足提现流水", notes = "补足提现流水")
    @RepeatSubmit(message = "频繁操作")
    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.CONSUM_GAME_ANCHOR_WITHDRAW, withdrawDto.getAmount()<0?FinTranType1.U_Income_Coin_Balance:FinTranType1.U_Outcome_Balance, appUser);
            tran.setDiamondCoinChange(withdrawDto.getAmount()*-1);
            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("补足流水成功");
    }

    /**
     * 开关播
     */
    @PreAuthorize("@ss.hasPermi('business:user:charge')")
    @Log(title = "开关播", businessType = BusinessType.UPDATE)
    @PostMapping("/openLive")
    @ApiOperation(value = "开关播", notes = "开关播")
    public R<String> openLive(HttpServletResponse response, @RequestBody LiveLive liveLive)
    {
        String url = sysConfigService.selectConfigByKey("sys_live_apiurl").concat("/api/live/httpOpenCloseLive");
        Map<String, String> map = new HashMap<>();
        map.put("roomId", String.valueOf(liveLive.getId()));
        map.put("liveType", "1");
        map.put("isLive", String.valueOf(liveLive.getIslive()));
        map.put("description", liveLive.getTitle());

        String res = HttpClientUtils.ajaxPost(url,map);
        if(StringUtils.isBlank(res) || !JSONObject.parseObject(res).getString("code").equals("1")){
            log.info("失败===============》》".concat(res));
            return R.fail(liveLive.getIslive().intValue()==1?"关播":"虚拟开播"+"失败");
        }
        String sign = TencentCloudImUtil.genUserSig(String.valueOf(liveLive.getUserId()), null);
        String liveUrl = "rtmp://intl-rtmp.rtc.qq.com/push/"+liveLive.getId()+"?sdkappid="+TencentCloudImUtil.getSdkAppId()+"&userid="+liveLive.getUserId()+"&usersig="+sign;
        return R.ok(liveLive.getIslive().intValue()==1?"关播":"虚拟开播"+"成功",liveUrl);
    }

    /**
     * 导出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));
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("roomId", "10000359");
        map.put("liveType", "1");
        map.put("isLive", "0");
        map.put("description", "1");

        String res = HttpClientUtils.ajaxPost("http://127.0.0.1:1801/api/live/httpOpenCloseLive",map);
        System.out.println(res);
    }
}
