package com.game.business.controller;

import java.beans.Encoder;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.game.business.domain.*;
import com.game.business.service.IAppChargeChannelService;
import com.game.business.service.IAppUserService;
import com.game.business.service.IAppUsersCashAccountService;
import com.game.business.task.AppUserCountTask;
import com.game.business.util.EncodeUtils;
import com.game.business.util.other.PayOrderUtils;
import com.game.common.annotation.Anonymous;
import com.game.common.annotation.RepeatSubmit;
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.R;
import com.game.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
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 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.service.IAppUsersCashrecordService;
import com.game.common.utils.poi.ExcelUtil;
import com.game.common.core.page.TableDataInfo;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 提现记录Controller
 * 
 * @author game
 * @date 2024-06-18
 */
@RestController
@RequestMapping("/business/cashrecord")
@Api(value = "AppUsersCashrecordController", description = "提现记录接口", tags = {"提现记录"})
public class AppUsersCashrecordController extends BaseController
{
    @Autowired
    private IAppUsersCashrecordService appUsersCashrecordService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private AppUserCountTask appUserCountTask;

    @Autowired
    private IAppUsersCashAccountService appUsersCashAccountService;

    @Autowired
    private IAppChargeChannelService appChargeChannelService;

    /**
     * 查询提现记录列表
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询提现记录列表", notes = "获取提现记录列表")
    public TableDataInfo list(AppUsersCashrecord appUsersCashrecord)
    {
        startPage();
        List<AppUsersCashrecord> list = appUsersCashrecordService.selectAppUsersCashrecordList(appUsersCashrecord);
        return getDataTable(list);
    }

    /**
     * 导出提现记录列表
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:export')")
    @Log(title = "提现记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出提现记录列表", notes = "导出提现记录列表")
    public void export(HttpServletResponse response, AppUsersCashrecord appUsersCashrecord)
    {
        List<AppUsersCashrecord> list = appUsersCashrecordService.selectAppUsersCashrecordList(appUsersCashrecord);
        ExcelUtil<AppUsersCashrecord> util = new ExcelUtil<AppUsersCashrecord>(AppUsersCashrecord.class);
        util.exportExcel(response, list, "提现记录数据");
    }

    /**
     * 获取提现记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取提现记录详细信息", notes = "获取提现记录详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(appUsersCashrecordService.selectAppUsersCashrecordById(id));
    }

    /**
     * 新增提现记录
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:add')")
    @Log(title = "提现记录", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增提现记录", notes = "新增提现记录")
    @PostMapping
    public AjaxResult add(@RequestBody AppUsersCashrecord appUsersCashrecord)
    {
        return toAjax(appUsersCashrecordService.insertAppUsersCashrecord(appUsersCashrecord));
    }

    /**
     * 修改提现记录
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:edit')")
    @Log(title = "提现记录", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改提现记录", notes = "修改提现记录")
    @PutMapping
    @DSTransactional()
    @RepeatSubmit(interval = 1000,message = "频繁操作")
    public R<String> edit(@RequestBody AppUsersCashrecord appUsersCashrecord) throws Exception {
        AppUsersCashrecord cashrecord = appUsersCashrecordService.selectAppUsersCashrecordById(appUsersCashrecord.getId());
        if(null == cashrecord){
            return R.fail("审核失败，记录不存在");
        }
        if(cashrecord.getStatus().intValue() != 0 && (appUsersCashrecord.getCallOther() != 0 && cashrecord.getCashOutStatus() != 2)){
            return R.fail("审核失败，当前状态不可审核");
        }
        AppUser appUser = appUserService.selectAppUserByUserid(cashrecord.getUid());
        if(null == appUser){
            return R.fail("审核失败，用户不存在");
        }
        if(null == appUsersCashrecord.getCashChannelId()){
            return R.fail("请选择提现渠道");
        }
        AppChargeChannel appChargeChannel = appChargeChannelService.selectAppChargeChannelById(appUsersCashrecord.getCashChannelId());
        if(null == appChargeChannel){
            return R.fail("审核失败，提现渠道不存在");
        }
        AppUsersCashrecord update = new AppUsersCashrecord();
        update.setId(cashrecord.getId());
        update.setStatus(appUsersCashrecord.getStatus());
        update.setReason(appUsersCashrecord.getReason());
        //计算手续费
        double servicePerc = null==appChargeChannel?0:appChargeChannel.getWithdrawRate();
        BigDecimal service = NumberUtil.div(NumberUtil.mul(cashrecord.getMoney(), servicePerc), 1, 2);
        update.setService(service);
        update.setPlatformService(service);
        /*if(appUsersCashrecord.getCallOther() == 0 && 1== appUsersCashrecord.getStatus().intValue() &&
                (null == appUsersCashrecord.getCashChannelId() || appUsersCashrecord.getCashChannelId() < 1)){
            return R.fail("审核失败，未找到对应渠道，请驳回或者人工审核");
        }*/
        if(1 == appUsersCashrecord.getStatus().intValue()
         && appUsersCashrecord.getCallOther() == 0){
            //审核通过
            /*String key = "";
            switch (cashrecord.getType().intValue()){
                case 1: //支付宝
                    key = "alipay";
                    break;
                case 2: //微信
                    key = "weixin";
                    break;
                case 3: //银行卡
                    key = "bank";
                    break;
                case 4:
                    key = "okpay";
                    break;
                case 5:
                    key = "cbpay";
                    break;
            }
            if(StringUtils.isBlank(key)){
                return R.fail("审核失败，用户提现账号渠道异常");
            }*/
            if(StringUtils.isBlank(appChargeChannel.getChannelKey())){
                return R.fail("审核失败，提现渠道未配置四方产品id");
            }
            update.setCashChannelId(appChargeChannel.getId());
//            if(StringUtils.isNotBlank(appChargeChannel.getChannelKey())){
                String extra = "";
                if(Arrays.asList("8092","8095").contains(appChargeChannel.getChannelKey())){
                    //钱包提现
                    extra = cashrecord.getAccount();
                }else{
                    AppUsersCashAccount appUsersCashAccount = appUsersCashAccountService.selectAppUsersCashAccountById(cashrecord.getCashAccountId());
                    if(null != appUsersCashAccount) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("cardNumber", cashrecord.getAccount());
                        jsonObject.put("bankName", URLEncoder.encode(cashrecord.getAccountBank(),"UTF-8"));
                        jsonObject.put("branchName", URLEncoder.encode(appUsersCashAccount.getBranch(),"UTF-8"));
                        jsonObject.put("ownerName", URLEncoder.encode(appUsersCashAccount.getName(),"UTF-8"));
                        extra = jsonObject.toString();
                    }else{
                        logger.info("调起第三方失败，用户提现账号不存在");
                        throw new Exception("审核失败，用户提现账号不存在");
                    }
                }
//                Double amount = (appUsersCashrecord.getMoney().doubleValue() - appUsersCashrecord.getService().doubleValue()) * 100;
                Double amount = (appUsersCashrecord.getMoney().doubleValue()) * 100;
                String orderno = IdUtil.getSnowflakeNextIdStr();
                logger.info("流水{}，订单{} 发起提现",cashrecord.getOrderno(),orderno);
                Map<String, Object> map = PayOrderUtils.getPayUrl(orderno,appChargeChannel.getChannelKey(),amount.intValue(),extra);
//                String url = "";
                AppUsersCashrecord cashRecord = new AppUsersCashrecord();
                cashRecord.setId(appUsersCashrecord.getId());
                cashRecord.setTradeNo(orderno);
                if("1".equals(String.valueOf(map.get("code")))){
//                    url = map.get("data").toString();

                    cashRecord.setCashOutStatus(3L); //转出中
                    appUsersCashrecordService.updateAppUsersCashrecord(cashRecord);
                }else{
                    appUsersCashrecordService.updateAppUsersCashrecord(cashRecord);
                    throw new ServiceException("发起提现失败: " + map.get("msg"));
                }
            /*}else{
                return R.fail("审核失败，未找到对应渠道，请驳回或者人工审核");
            }*/
        }
        if(appUsersCashrecord.getCallOther() == 1 && 1 == appUsersCashrecord.getStatus().intValue()){
            update.setCashOutStatus(0L);
        }
        if(2 == appUsersCashrecord.getStatus().intValue()){

            //审核驳回 回退用户金额
            //流水 余额
            FinTranAddedInfo addedInfo = FinTranAddedInfo.createTranInfo(appUser.getUserid(), 0, 0, AppSceneType.Scene_None, "");
            FinTranRecord tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.CASH_DIAMOND_INCOME_BACK, FinTranType1.U_Income_Coin_Balance, appUser);
            tran.setDiamondCoinChange(cashrecord.getVotes().doubleValue());
            tran.setAfterDiamondCoin(appUser.getDiamondCoin());
            tran.setCurrencyType(TranCurrencyType.Balance.getType());
            tran.setTranGroupId(IdUtil.getSnowflakeNextId());
            tran.setRemarks("提现审核失败：回退金额");
            appUserService.updateUserAmount(tran,true,false);
            update.setCashOutStatus(0L);
        }
        int rest = appUsersCashrecordService.updateAppUsersCashrecord(update);
        logger.info("{},提现审核:{}",appUser.getUserid(),appUsersCashrecord.getStatus());
        //更新用户可提现余额
        appUserCountTask.updateWithdrawAble(appUser.getUserid());
        if(rest < 1){
            return R.fail("审核失败");
        }

        return R.ok("审核成功");
    }

    /**
     * 删除提现记录
     */
    @PreAuthorize("@ss.hasPermi('business:cashrecord:remove')")
    @Log(title = "提现记录", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除提现记录", notes = "删除提现记录")
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appUsersCashrecordService.deleteAppUsersCashrecordByIds(ids));
    }

    @ApiOperation(value = "第三方支付回调", notes = "第三方支付回调  1校验成功")
    @RequestMapping(value = "/otherCallback")
    @Anonymous
    public String otherPayCallBack(@ApiIgnore HttpServletRequest request) {
        Map<String, Object> map =  PayOrderUtils.getOrderStatus(request);
        logger.info("订单回调：{}",JSONObject.toJSONString(map));
        if(null != map && null != map.get("data") && null != map.get("tradeNo")){
            //支付回调成功
            String orderNo = map.get("data").toString();
            String tradeNo = map.get("tradeNo").toString();
            //验证回调订单
            Map<String, Object> checkMap = PayOrderUtils.checkOrder(orderNo,tradeNo);
            AppUsersCashrecord appUsersCashrecord = appUsersCashrecordService.getByOrderNo(orderNo);
            if(null == appUsersCashrecord){
                return "failed";
            }

            AppUsersCashrecord update = new AppUsersCashrecord();
            update.setId(appUsersCashrecord.getId());
            update.setCashOutStatus(1L);
            update.setCashOutOrderId(tradeNo);
            if(!"1".equals(String.valueOf(checkMap.get("code")))){
                //转出失败
                //流水 余额
                AppUser appUser = appUserService.selectAppUserByUserid(appUsersCashrecord.getUid());
                if(null == appUser){
                    return "failed";
                }
                /*try {
                    if(null != appUsersCashrecord.getCashOutStatus() && appUsersCashrecord.getCashOutStatus().intValue() == 3) {
                        FinTranAddedInfo addedInfo = FinTranAddedInfo.createTranInfo(appUser.getUserid(), 0, 0, AppSceneType.Scene_None, "");
                        FinTranRecord tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.CASH_DIAMOND_INCOME_BACK, FinTranType1.U_Income_Coin_Balance, appUser);
                        tran.setDiamondCoinChange(appUsersCashrecord.getVotes().doubleValue());
                        tran.setAfterDiamondCoin(appUser.getDiamondCoin());
                        tran.setCurrencyType(TranCurrencyType.Balance.getType());
                        tran.setTranGroupId(IdUtil.getSnowflakeNextId());
                        tran.setRemarks("转出失败：回退金额");
                        appUserService.updateUserAmount(tran,true,false);
                    }else{
                        logger.info("订单{}，当前状态非转出中，停止更新失败逻辑",orderNo);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }*/
                //更新状态
                update.setCashOutStatus(2L);
            }
            appUsersCashrecordService.updateAppUsersCashrecord(update);
            //更新用户可提现余额
            appUserCountTask.updateWithdrawAble(appUsersCashrecord.getUid());

            return "success";
        }else{
            return "failed";
        }
    }

    public static void main(String[] args) {
        System.out.println(IdUtil.getSnowflakeNextIdStr().length());
        System.out.println(IdUtil.fastUUID());
    }
}
