package com.zbkj.front.controller;


import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.common.dto.*;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.exception.CrmebWalletException;
import com.zbkj.common.model.bcx.BcxPlatformFee;
import com.zbkj.common.model.huifu.*;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.service.CommonConfigService;
import com.zbkj.service.service.HuifuWalletService;
import com.zbkj.service.service.PayService;
import com.zbkj.service.service.bcx.BcxPlatformFeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 首页控制器
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/front/wallet")
@Api(tags = "企业钱包服务")
public class HuifuWalletController {


    @Autowired
    private HuifuWalletService huifuWalletService;
    @Autowired
    private PayService payService;
    @Resource
    private BcxPlatformFeeService bcxPlatformFeeService;
    @Autowired
    private CommonConfigService commonConfigService;

    @Autowired
    private RedissonClient redisson;

    private final static String TRANSFERKEY = "Transfer:";


    /**
     * 查询银行列表信息
     *
     * @param bankConfig
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "查询银行列表信息", httpMethod = "GET", notes = "查询银行列表信息", response = CommonResult.class)
    @PostMapping(value = "find-banks")
    public CommonResult<List<BankConfig>> findBank(@RequestBody BankConfig bankConfig) throws CrmebWalletException {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.findBank(bankConfig));
    }

    /**
     * 获取企业钱包服务开通情况
     * 【百课堂在调用，勿加权限校验】
     *
     * @param huifuWallet
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "获取企业钱包服务开通情况", httpMethod = "GET", notes = "获取企业钱包服务开通情况", response = CommonResult.class)
    @GetMapping(value = "get-huifu-wallet-service-open-info")
    public CommonResult<Map<String, String>> getHuifuWalletServiceOpenInfo(HuifuWallet huifuWallet) {
        huifuWallet.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuWalletServiceOpenInfo(huifuWallet));
    }

    /**
     * 获取企业钱包服务当前开通步骤(因富民银行开户流程调整作废)
     *
     * @param huifuWalletProcess
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "获取企业钱包服务当前开通步骤", httpMethod = "GET", notes = "获取企业钱包服务当前开通步骤", response = CommonResult.class)
    @GetMapping(value = "get-huifu-wallet-current-process")
    public CommonResult<HuifuWalletProcess> getHuifuWalletCurrentProcess(HuifuWalletProcess huifuWalletProcess) {
        huifuWalletProcess.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuWalletCurrentProcess(huifuWalletProcess));
    }

    /**
     * 保存开户资料
     *
     * @param dto
     * @author llc
     * @date 2019-06-21
     * @update by llc 2020-09-10 保存开户资料第一步、第二步整合成保存开户资料
     */
    @ApiOperation(value = "保存开户资料", httpMethod = "POST", notes = "保存开户资料", response = CommonResult.class)
    @PostMapping(value = "save-account-info")
    public CommonResult<String> saveAccountInfo(@RequestBody HuifuWalletAccountDto dto) {
        dto.setUniId(commonConfigService.getAccoutCode());
        String lockId = TRANSFERKEY+dto.getUniId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.saveAccountInfo(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("saveAccountInfo error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }


    /**
     * 保存开户资料第二步（作废）
     *
     * @param dto
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "保存开户资料第二步", httpMethod = "POST", notes = "保存开户资料第二步", response = CommonResult.class)
    @PostMapping(value = "save-account-info-step-two")
    public CommonResult<String> saveAccountInfoStepTwo(@RequestBody HuifuWalletBusiDto dto) {
        dto.setUniId(commonConfigService.getAccoutCode());
        String lockId = TRANSFERKEY+dto.getUniId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.saveAccountInfoStepTwo(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("saveAccountInfoStepTwo error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * 获取企业钱包账户
     *
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "获取企业钱包账户", httpMethod = "GET", notes = "获取企业钱包账户", response = CommonResult.class)
    @GetMapping(value = "get-huifu-wallet-account")
    public CommonResult<HuifuWalletAccountDto> getHuifuWalletAccount() throws CrmebWalletException {
        HuifuWalletAccount huifuWalletAccount = new HuifuWalletAccount();
        huifuWalletAccount.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuWalletAccount(huifuWalletAccount));
    }

    /**
     * 获取企业钱包账户金额
     *
     * @author llc
     * @date 2019-06-24
     */
    @ApiOperation(value = "获取企业钱包账户金额", httpMethod = "GET", notes = "获取企业钱包账户金额", response = CommonResult.class)
    @GetMapping(value = "get-huifu-wallet-account-amount")
    public CommonResult<Map<String, String>> getHuifuWalletAccountAmount() throws CrmebWalletException {
        HuifuWalletAccount huifuWalletAccount = new HuifuWalletAccount();
        huifuWalletAccount.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuWalletAccountAmount(huifuWalletAccount));
    }


    /**
     * 获取企业钱包账户交易明细
     *
     * @param dto
     * @author llc
     * @date 2019-06-21
     */
    @ApiOperation(value = "获取企业钱包账户交易明细", httpMethod = "GET", notes = "获取企业钱包账户交易明细", response = CommonResult.class)
    @PostMapping(value = "get-huifu-wallet-account-trade-detail")
    public CommonPage<HuifuWalletAccountDetail> getHuifuWalletAccountTradeDetail(@RequestBody HuifuWalletAccountDto dto) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        return CommonPage.restPage(huifuWalletService.thisHuifuWalletAccountTradeDetail(dto));
    }


    /**
     * 将钱包收支明细保存到本地-任务
     *
     * @author lp
     * @date 2019-12-09
     */
    @ApiOperation(value = "将钱包收支明细保存到本地", httpMethod = "POST", notes = "将钱包收支明细保存到本地", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-trade-detail-task")
    public CommonResult<String> huifuWalletAccountTradeDetailTask(HuifuWalletAccountDto dto) {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.huifuWalletAccountTradeDetailTask(dto.getStartDate(), dto.getEndDate()));
//        huifuWalletService.payTradeDetailTaskSch();
//        return CommonResult.success();
    }

    /**
     * 将钱包收支明细保存到本地-任务 余额支付
     *
     * @author lp
     * @date 2019-12-09
     */
    @ApiOperation(value = "将钱包收支明细保存到本地 余额支付", httpMethod = "POST", notes = "将钱包收支明细保存到本地 余额支付", response = CommonResult.class)
    @PostMapping(value = "yepay-detail-task")
    public CommonResult<String> yepayDetailTask() {
        commonConfigService.getAccoutCode();
        huifuWalletService.payTradeDetailTaskSch();
        return CommonResult.success();
    }


    /**
     * 获取企业钱包充值token
     *
     * @param dto
     * @author llc
     * @date 2019-06-25
     */
    @ApiOperation(value = "获取企业钱包充值token", httpMethod = "POST", notes = "获取企业钱包充值token", response = CommonResult.class)
    @PostMapping(value = "get-wallet-recharge-token")
    public CommonResult<String> getWalletRechargeToken(@RequestBody HuifuWalletAccountDto dto) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getWalletRechargeToken(dto));
    }

    /**
     * 企业钱包充值回调
     *
     * @param dto
     * @author llc
     * @date 2019-06-25
     */
    @ApiOperation("企业钱包充值回调")
    @PostMapping(value = "huifuWalletRechargeCallback")
    public String huifuWalletRechargeCallback(@RequestBody HuifuRequestDataDto dto) {
        return huifuWalletService.huifuWalletRechargeCallback(dto);
    }

    /**
     * 企业钱包提现回调
     *
     * @author llc
     * @date 2019-06-25
     */
    @ApiOperation("企业钱包提现回调")
    @PostMapping(value = "huifuWalletExtractCallback")
    public String huifuWalletExtractCallback(HttpServletRequest request) {
        String messageBody = (String)request.getAttribute("requestBodyMessage");
        return huifuWalletService.huifuWalletExtractCallback(messageBody);
    }

    /**
     * <b> C端聚合正扫回调 </b>
     * @author ZXF
     * @create 2023/08/25 0025 16:13
     * @version
     * @注意事项 </b>
     */
    @ApiOperation("C端聚合正扫回调")
    @PostMapping(value = "huifuJspayCallback")
    public String huifuJspayCallback(HttpServletRequest request) {
        String messageBody = (String)request.getAttribute("requestBodyMessage");
        return payService.huifuJspayCallback(messageBody);
    }

    /**
     * <b> C端聚合正扫退款回调 </b>
     * @author ZXF
     * @create 2023/08/25 0025 16:13
     * @version
     * @注意事项 </b>
     */
    @ApiOperation("C端聚合正扫退款回调")
    @PostMapping(value = "huifuJspayRefundCallback")
    public String huifuJspayRefundCallback(HttpServletRequest request) {
        String messageBody = (String)request.getAttribute("requestBodyMessage");
        return payService.huifuJspayRefundCallback(messageBody);
    }

    /**
     * <b> 根据业务编码或业务交易流水号查询交易信息 </b>
     * @author ZXF
     * @create 2023/03/23 0023 10:23
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "根据业务编码或业务交易流水号查询交易信息", httpMethod = "POST", notes = "根据业务编码或业务交易流水号查询交易信息", response = CommonResult.class)
    @PostMapping(value = "find-wallet-trade-info-by-business")
    public CommonResult<List<HuifuWalletTrade>> getHuifuWalletTradeBySeqAndCode(@RequestBody HuifuWalletTrade huifuWalletTrade) throws CrmebWalletException {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.getHuifuWalletTradeBySeqAndCode(huifuWalletTrade));
    }

    /**
     * 获取企业充值交易状态
     *
     * @param huifuWalletTrade
     * @author llc
     * @date 2019-06-28
     */
    @ApiOperation(value = "获取企业充值交易状态", httpMethod = "GET", notes = "获取企业充值交易状态", response = CommonResult.class)
    @GetMapping(value = "get-wallet-trade-info")
    public CommonResult<HuifuWalletTrade> getWalletTradeInfo( HuifuWalletTrade huifuWalletTrade) throws CrmebWalletException {
        huifuWalletTrade.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getWalletTradeInfo(huifuWalletTrade));
    }


    /**
     * 企业钱包账户提现
     *
     * @param dto
     * @author llc
     * @date 2019-06-25
     */
    @ApiOperation(value = "企业钱包账户提现", httpMethod = "POST", notes = "企业钱包账户提现", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-extract")
    public CommonResult<String> huifuWalletAccountExtract(@RequestBody HuifuWalletAccountDto dto) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        String lockId = TRANSFERKEY+dto.getUniId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.huifuWalletAccountExtract(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (InterruptedException e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed("操作失败，请稍后重试");
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }


    /**
     * <b> 企业账户金额冻结/解冻 </b>
     * @author ZXF
     * @create 2023/03/29 0029 17:20
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "企业消费转账接口", httpMethod = "POST", notes = "企业账户金额冻结/解冻", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-lock")
    public CommonResult<String> huifuWalletAccountLock(@RequestBody HuifuWalletTransferDto dto) {
        commonConfigService.getAccoutCode();
        if (StringUtil.isEmpty(dto.getTradeType())) {
            throw new CrmebException("交易类型不能为空");
        }
        if (dto.getOutId() == null) {
            throw new CrmebException("企业出账ID不能为空");
        }
        if (dto.getInId() == null) {
            throw new CrmebException("企业入账ID不能为空");
        }
        String comId = "05".equals(dto.getTradeType())?dto.getInId():dto.getOutId();
        String lockId = TRANSFERKEY+comId;
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.huifuWalletAccountLock(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * 企业消费转账接口
     * 【百课堂在调用，勿加权限校验】
     *
     * @author lp
     * @date 2019-08-20
     */
    @ApiOperation(value = "企业消费转账接口", httpMethod = "POST", notes = "企业消费转账接口", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-transfer")
    public CommonResult<String> huifuWalletAccountTransfer(@RequestBody HuifuWalletTransferDto dto) {
        commonConfigService.getAccoutCode();
        if (dto.getOutId() == null) {
            throw new CrmebException("企业出账ID不能为空");
        }
        if (dto.getInId() == null) {
            throw new CrmebException("企业入账ID不能为空");
        }
        if (StringUtil.isEmpty(dto.getTradeType())) {
            throw new CrmebException("交易类型不能为空");
        }

        String lockId = TRANSFERKEY+dto.getOutId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.huifuWalletAccountTransfer(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * 企业退款接口
     *
     * @author lp
     * @date 2019-08-20
     */
    @ApiOperation(value = "企业退款接口", httpMethod = "POST", notes = "企业退款接口", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-refund")
    public CommonResult<String> huifuWalletAccountRefund(@RequestBody HuifuWalletTransferDto dto) {
        commonConfigService.getAccoutCode();
        if (dto.getOutId() == null) {
            throw new CrmebException("企业出账ID不能为空");
        }
        if (dto.getInId() == null) {
            throw new CrmebException("企业入账ID不能为空");
        }
        if (StringUtil.isEmpty(dto.getTradeType())) {
            throw new CrmebException("交易类型不能为空");
        }

        String lockId = TRANSFERKEY+dto.getOutId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(3,10, TimeUnit.SECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.huifuWalletAccountRefund(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * 平台分销转账接口
     *
     * @author lp
     * @date 2019-08-20
     */
    @ApiOperation(value = "平台分销转账接口", httpMethod = "POST", notes = "平台分销转账接口", response = CommonResult.class)
    @PostMapping(value = "plat-account-retail-transfer")
    public CommonResult<String> platAccountRetailTransfer(@RequestBody HuifuWalletTransferDto dto) {
        commonConfigService.getAccoutCode();
        if (dto.getInId() == null) {
            throw new CrmebException("企业入账ID不能为空");
        }
        if (StringUtil.isEmpty(dto.getTradeType())) {
            throw new CrmebException("交易类型不能为空");
        }

        String lockId = TRANSFERKEY+dto.getOutId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(5,60, TimeUnit.MILLISECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.platAccountRetailTransfer(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }


    /**
     * 电子回单
     *
     * @param dto
     * @author lp
     * @date 2019-07-08
     */
    @ApiOperation(value = "电子回单", httpMethod = "POST", notes = "电子回单", response = CommonResult.class)
    @PostMapping(value = "huifu-account-trade-voucher")
    public CommonResult<String> getHuifuAccountTradeVoucher(@RequestBody HuifuWalletTradeDto dto, HttpServletResponse response) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuAccountTradeVoucher(dto));
    }


    private static void downloadBase64(HttpServletResponse response, String base64Code) throws IOException {
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + DateUtil.current(true) + ".pdf");
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(base64Code);
            try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
                byte[] buffer = new byte[1024];
                int byteRead = 0;
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                out.flush();
            }
        }
    }

    /**
     * 初始生成化对账单配置
     *
     * @author llc
     * @date 2019-09-16
     */
    @ApiOperation(value = "初始生成化对账单配置", httpMethod = "POST", notes = "初始生成化对账单配置", response = CommonResult.class)
    @PostMapping(value = "set-reconciliation-config")
    public CommonResult<String> setReconciliationConfig() throws CrmebWalletException {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.setReconciliationConfig());
    }

    /**
     * 交易结算对账文件重新生成
     *
     * @author llc
     * @date 2019-09-16
     */
    @ApiOperation(value = "交易结算对账文件重新生成", httpMethod = "POST", notes = "交易结算对账文件重新生成", response = CommonResult.class)
    @PostMapping(value = "reconciliation-replay/{tradeDate}")
    public CommonResult<String> reconciliationReplay(@PathVariable("tradeDate") String tradeDate) {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.reconciliationReplay(tradeDate));
    }

    /**
     * 企业钱包账户对账数据生成
     *
     * @author llc
     * @date 2019-09-16
     */
    @ApiOperation(value = "企业钱包账户对账数据生成", httpMethod = "POST", notes = "企业钱包账户对账数据生成", response = CommonResult.class)
    @PostMapping(value = "create-huifu-wallet-reconciliation")
    public CommonResult<String> createHuifuWalletReconciliation() {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.createHuifuWalletReconciliation());
    }

    /**
     * 获取企业钱包账户提现记录
     *
     * @author llc
     * @date 2019-09-16
     */
    @ApiOperation(value = "获取企业钱包账户提现记录", httpMethod = "POST", notes = "获取企业钱包账户提现记录", response = CommonResult.class)
    @PostMapping(value = "huifu-wallet-account-translog-task")
    public CommonResult<String> huifuWalletAccountTranslogTask() {
        commonConfigService.getAccoutCode();
        return CommonResult.success(huifuWalletService.huifuWalletAccountTranslogTask("",""));
//        return CommonResult.success(huifuWalletService.huifuWalletAccountTranslogTask("2023-08-13","2023-08-15"));
    }


    /**
     * 获取企业钱包账户对账数据
     *
     * @author llc
     * @date 2019-09-19
     */
    @ApiOperation(value = "获取企业钱包账户对账数据", httpMethod = "POST", notes = "获取企业钱包账户对账数据", response = CommonResult.class)
    @PostMapping(value = "get-huifu-wallet-reconciliation")
    public CommonResult<Map<String, Object>> getHuifuWalletReconciliation(@RequestBody HuifuWalletTradeDto dto) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        return CommonResult.success(huifuWalletService.getHuifuWalletReconciliation(dto));
    }

    /**
     * 导出企业钱包账户对账数据
     *
     * @author llc
     * @date 2019-09-20
     */
    @ApiOperation(value = "导出企业钱包账户对账数据", httpMethod = "POST")
    @PostMapping(value = "export-huifu-wallet-reconciliation")
    public void exprokHuifuWalletReconciliation(@RequestBody HuifuWalletTradeDto dto,HttpServletResponse response) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        huifuWalletService.exportHuifuWalletReconciliation(dto, response);
    }

    /**
     * <b> 导出企业钱包账户交易明细数据 </b>
     * @author ZXF
     * @create 2023/12/12 0012 14:02
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "导出企业钱包账户交易明细数据", httpMethod = "POST")
    @PostMapping(value = "export-huifu-wallet-account-trade-detail")
    public void exportHuifuWalletAccountTradeDetail(@RequestBody HuifuWalletAccountDto dto,HttpServletResponse response) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        huifuWalletService.exportHuifuWalletAccountTradeDetail(dto, response);
    }

    /**
     * <b> 获取企业钱包账户提现信息 </b>
     * @author ZXF
     * @create 2023/08/06 0006 13:21
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "获取企业钱包账户提现信息", httpMethod = "POST", notes = "获取企业钱包账户提现信息", response = CommonResult.class)
    @PostMapping(value = "get-huifu-wallet-translog")
    public CommonPage<HuifuWalletTranslog> getHuifuWalletSettlement(@RequestBody HuifuWalletTranslogDto dto) throws CrmebWalletException {
        dto.setUniId(commonConfigService.getAccoutCode());
        return CommonPage.restPage(huifuWalletService.thisHuifuWalletTranslog(dto));
    }
    
    /**
     * <b> 保存钱包银行卡信息变更 </b>
     *
     * @author ZXF
     * @create 2019/09/17 0017 15:45
     * @version
     * @注意事项 </b>
     */
//    @ApiOperation(value = "保存钱包银行卡信息变更", httpMethod = "POST", notes = "保存钱包银行卡信息变更", response = CommonResult.class)
//    @PostMapping(value = "save-bank-card-change-event")
//    public CommonResult<> saveBankCardChangeEvent(HuifuWalletChangeDto dto) {
//        Integer uid = commonConfigService.getAccoutCode();
//        if (uid == null) {
//            dto.setUniId(uid);
//        }
//        return CommonResult.success(huifuWalletChangeService.saveBankCardChangeEvent(dto));
//    }

    /**
     * <b> C端转账接口 - 聚合正扫 </b>
     * @author ZXF
     * @create 2023/08/25 0025 16:12
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "C端转账接口 - 聚合正扫", httpMethod = "POST", notes = "C端转账接口 - 聚合正扫", response = CommonResult.class)
    @PostMapping(value = "huifu-jspay-transfer")
    public CommonResult<String> huifuJspayTransfer(@RequestBody JsPayTransferDto dto) {
        dto.setUniId(commonConfigService.getAccoutCode()+"");
        if (StringUtil.isEmpty(dto.getBusinessPartnerSeq())) {
            throw new CrmebException("业务交易流水号不能为空");
        }
        BcxPlatformFee platFee = bcxPlatformFeeService.queryByOrderNo(dto.getBusinessPartnerSeq(), 0);
        dto.setSellFeePriority(platFee.getTransPriority());
        dto.setPlatAmount(platFee.getPlatFee() != null ? platFee.getPlatFee().toPlainString() : "0");
        Map<String,String> map = payService.getIdentifyNoByOrderNo(dto.getBusinessPartnerSeq());
        dto.setInId(map.get("inId"));
        dto.setAmount(map.get("amount"));
        if (StringUtil.isEmpty(map.get("inId"))) {
            throw new CrmebException("企业入账ID不存在");
        }
//        String inId = payService.getMerchantIdentifyNoByOrderNo(dto.getBusinessPartnerSeq());
//        dto.setInId(inId);
//        if (StringUtil.isEmpty(inId)) {
//            throw new CrmebException("企业入账ID不存在");
//        }
        //TODO C端支付当前固定走04冻结流程
        dto.setTradeType("04");
        if (StringUtil.isEmpty(dto.getTradeType())) {
            throw new CrmebException("交易类型不能为空");
        }

        String lockId = TRANSFERKEY+dto.getUniId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(5,60, TimeUnit.MILLISECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                //TODO 临时让订单通过支付
//                payService.setOrderPaySuccess(dto.getBusinessPartnerSeq());
                return CommonResult.success(huifuWalletService.huifuJspayTransfer(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * <b> C端退款接口 - 扫码交易退款 </b>
     * @author ZXF
     * @create 2023/08/25 0025 16:12
     * @version
     * @注意事项 </b>
     */
    @ApiOperation(value = "C端退款接口 - 扫码交易退款", httpMethod = "POST", notes = "C端退款接口 - 扫码交易退款", response = CommonResult.class)
    @PostMapping(value = "huifu-jspay-refund")
    public CommonResult<String> huifuJspayRefund(@RequestBody JsPayTransferDto dto) {
        dto.setUniId(commonConfigService.getAccoutCode()+"");

        String lockId = TRANSFERKEY+dto.getUniId();
        RLock lock = redisson.getLock(lockId);
        try {
            if(lock.tryLock(5,60, TimeUnit.MILLISECONDS)){
                log.debug(lockId+":getLock: " + Thread.currentThread().getId());
                return CommonResult.success(huifuWalletService.huifuJspayRefund(dto));
            }else{
                return CommonResult.failed("资源繁忙，请稍后重试");
            }
        } catch (Exception e) {
            log.error("doCatchRecommendUser error", e);
            return CommonResult.failed(e.getMessage());
        }finally {
            if (lock.isHeldByCurrentThread()) {
                log.debug(lockId+":unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}



