package com.neusoft.smart.pos.card.controller;

import com.neusoft.smart.pos.card.constants.CardCapitalChangeType;
import com.neusoft.smart.pos.card.constants.CardErrorCode;
import com.neusoft.smart.pos.card.constants.CardTradeConstants;
import com.neusoft.smart.pos.card.dto.UpdateCardRequest;
import com.neusoft.smart.pos.card.persistent.domain.*;
import com.neusoft.smart.pos.card.persistent.repository.CardCapitalChangeRepository;
import com.neusoft.smart.pos.card.persistent.repository.ICardRelationRepository;
import com.neusoft.smart.pos.card.service.CardService;
import com.neusoft.smart.pos.card.service.CardTradeService;
import com.neusoft.smart.pos.card.utils.SignUtils;
import com.neusoft.smart.pos.dto.card.request.*;
import com.neusoft.smart.pos.dto.card.response.CardTradeCreateResponse;
import com.neusoft.smart.pos.dto.card.response.CardTradeQueryResponse;
import com.neusoft.smart.pos.dto.card.response.CardTradeRefundResponse;
import com.neusoft.smart.pos.dto.card.response.GetRechargeListResponse;
import com.neusoft.smart.pos.exchangeStrategy.constants.ExchangeStrategyConstants;
import com.neusoft.smart.pos.exchangeStrategy.persistent.domain.ExchangeStrategy;
import com.neusoft.smart.pos.exchangeStrategy.persistent.domain.ExchangeStrategyTypeDict;
import com.neusoft.smart.pos.exchangeStrategy.persistent.repository.IExchangeStrategy;
import com.neusoft.smart.pos.exchangeStrategy.service.ExchangeStrategyTypeDictService;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.SpringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "卡支付接口", description = "卡支付接口")
@RestController
@RequestMapping(path = "/cardtrade")
public class CardTradeController {

	@Resource
	private CardTradeService cardTradeService;

    @Resource
    private CardService cardService;

    @Resource
    private ExchangeStrategyTypeDictService exchangeStrategyTypeDictService;

    @Resource
    private CardCapitalChangeRepository cardCapitalChangeRepository;

    @Transactional
    @PostMapping("/recharge/{snCode}")
    @ApiOperation(value = "卡充值接口", notes = "卡充值接口")
    public ResponseData<Long> recharge(@PathVariable String snCode, @RequestBody RechargeRequest rechargeRequest) {
        Card card = cardService.getSingleCard(rechargeRequest.getCardNum(),rechargeRequest.getCardAnotherId(),rechargeRequest.getCardOtherId(), snCode, null, null);
        if(card == null) {
            throw new BusinessCommonException(CardErrorCode.RECHARGE_PATAM_LACKED);
        }
        cardService.validateCard(card, snCode);
        Long balance = card.getCardBalance();
        Long rechargeAmount = convertAmount(card,rechargeRequest.getRechargeAmount());
        CardOrder cardOrder = cardTradeService.createRechargeOrder(rechargeRequest, card.getCardId());

        //更新卡数据
        int res = this.updateCard(card.getCardNum(), balance, card.getCardPoint(), balance+rechargeAmount,card.getCardPoint(), rechargeAmount);
        if(res <= 0) {
            throw new BusinessCommonException(CardErrorCode.RECHARGE_FAILED_CARD_DATA_INPUT_ERROR);
        }

        //存变更数据
        Long afterBalance = balance+rechargeAmount;
        this.createCardCapitalChange(card.getCardId(),card.getCardNum(),cardOrder.getCardTradeNum(),
                rechargeAmount, balance, afterBalance, //正数 意味着加钱
                null, null, null,
                "充值:"+rechargeRequest.getRechargeMode(), CardCapitalChangeType.RECHARGE.getCode(), rechargeRequest.getRechargeTime());

        return new ResponseData<>(afterBalance);
    }

    
    @Transactional
    @PostMapping("/transfer/{snCode}")
    @ApiOperation(value = "转账接口", notes = "转账接口")
    public ResponseData<?> transfer(@PathVariable String snCode, @RequestBody TransferRequest transferRequest) {
        Card sourceCard = cardService.getSingleCard(transferRequest.getSourceCardNum(), transferRequest.getSourceCardAnotherId(), transferRequest.getSourceCardOtherId(), snCode, null, null);
        Card targetCard = cardService.getSingleCard(transferRequest.getTargetCardNum(), transferRequest.getTargetCardAnotherId(), transferRequest.getTargetCardOtherId(), snCode, null, null);
        if(sourceCard == null || targetCard == null) {
            throw new BusinessCommonException(CardErrorCode.TRANSFER_PATAM_LACKED);
        }

        cardService.validateCard(sourceCard, snCode);
        CardOrder cardOrder = cardTradeService.createTransferOrder(transferRequest, sourceCard.getCardId(), targetCard.getCardId());

        // 资金流出方
        Long sourceBalance = sourceCard.getCardBalance();
        if(sourceBalance < transferRequest.getTransferAmount()) {
            throw new BusinessCommonException(CardErrorCode.CARD_INSUFFICIENT_BALANCE); // 当有异常抛出时，事务回滚，订单创建回滚
        }
        //更新卡数据
        int res = this.updateCard(sourceCard.getCardNum(),sourceBalance, sourceCard.getCardPoint(), sourceBalance-transferRequest.getTransferAmount(), sourceCard.getCardPoint(), null);
        if(res <= 0) {
            throw new BusinessCommonException(CardErrorCode.TRANSFER_FAILED_CARD_DATA_INPUT_ERROR);
        }
        //存变更数据
        Long sourceAfterBalance = sourceBalance-transferRequest.getTransferAmount();
        this.createCardCapitalChange(sourceCard.getCardId(),sourceCard.getCardNum(),cardOrder.getCardTradeNum(),
                -transferRequest.getTransferAmount(), sourceBalance, sourceAfterBalance,//负数 意味着减钱
                null, null, null,
                "转账", CardCapitalChangeType.TRANSFER.getCode(), transferRequest.getTransferTime());

        //资金流入方
        Long targetBalance = targetCard.getCardBalance();
        //更新卡数据
        res = this.updateCard(targetCard.getCardNum(),targetBalance, targetCard.getCardPoint(), targetBalance+transferRequest.getTransferAmount(), targetCard.getCardPoint(), null);
        if(res <= 0) {
            throw new BusinessCommonException(CardErrorCode.TRANSFER_FAILED_CARD_DATA_INPUT_ERROR);
        }
        //存变更数据
        Long targetAfterBalance = targetBalance+transferRequest.getTransferAmount();
        this.createCardCapitalChange(targetCard.getCardId(),targetCard.getCardNum(),cardOrder.getCardTradeNum(),
                transferRequest.getTransferAmount(), targetBalance, targetAfterBalance,//正数 意味着加钱
                null, null, null,
                "转账", CardCapitalChangeType.TRANSFER.getCode(), transferRequest.getTransferTime());
        return new ResponseData<>();
    }

	@Transactional
	@PostMapping("/createOrder/{snCode}")
	@ApiOperation(value = "订单生成接口", notes = "订单生成接口")
	public ResponseData<CardTradeCreateResponse> createOrder(@PathVariable String snCode, @RequestBody CardTradeCreateRequest cardTradeCreateRequest) {
        Card sourceCard = cardService.getSingleCard(cardTradeCreateRequest.getSourceCardNum(),cardTradeCreateRequest.getSourceCardAnotherId(),cardTradeCreateRequest.getSourceCardOtherId(), snCode, null, null);
        Card targetCard = null;
        if(cardTradeCreateRequest.getTargetCardNum() != null && cardTradeCreateRequest.getTargetCardAnotherId() != null && cardTradeCreateRequest.getTargetCardOtherId() != null) {
            targetCard = cardService.getSingleCard(cardTradeCreateRequest.getTargetCardNum(), cardTradeCreateRequest.getTargetCardAnotherId(), cardTradeCreateRequest.getTargetCardOtherId(), snCode, null, null);
        }
        if(sourceCard == null) {
            throw new BusinessCommonException(CardErrorCode.TRADE_PATAM_LACKED);
        }
        cardService.validateCard(sourceCard, snCode);

        CardOrder cardOrder = cardTradeService.createPayOrder(cardTradeCreateRequest,
                sourceCard.getCardId(),
                targetCard==null?null:targetCard.getCardId());

        // 买家
        Integer sourcePoint = sourceCard.getCardPoint();
        Long sourceBalance = sourceCard.getCardBalance();
        if(cardOrder.getPayType().equals(CardTradeConstants.CARD_PAY_TYPE_YE.getCode())) { //余额支付
            if (sourceBalance.compareTo(cardTradeCreateRequest.getPayAmount()) < 0) {
                String balanceString = BigDecimal.valueOf(sourceBalance).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).toString();
                throw new BusinessCommonException(CardErrorCode.CARD_INSUFFICIENT_BALANCE.getCode(), CardErrorCode.CARD_INSUFFICIENT_BALANCE.getMessage()+"。余额："+balanceString); // 当有异常抛出时，事务回滚，订单创建回滚
            }
            //更新卡数据
            Integer changedPoint = this.getChangedPoint(sourceCard, cardTradeCreateRequest.getPayAmount());
            int res = this.updateCard(sourceCard.getCardNum(),sourceBalance, sourceCard.getCardPoint(), sourceBalance-cardTradeCreateRequest.getPayAmount(), sourceCard.getCardPoint(), null);
            if(res <= 0) {
                throw new BusinessCommonException(CardErrorCode.PAY_FAILED_CARD_DATA_INPUT_ERROR);
            }
            //存变更数据
            Long sourceAfterBalance = sourceBalance-cardTradeCreateRequest.getPayAmount();
            this.createCardCapitalChange(sourceCard.getCardId(),sourceCard.getCardNum(),cardOrder.getCardTradeNum(),
                    -cardTradeCreateRequest.getPayAmount(), sourceBalance, sourceAfterBalance,//负数 意味着减钱
                    changedPoint, sourcePoint, sourcePoint + changedPoint,//正数 意味着增加积分
                    "卡支付消费", CardCapitalChangeType.TRANSFER.getCode(), cardOrder.getPayTime());
        } else {    // 积分支付
            if (sourcePoint - Integer.parseInt(cardTradeCreateRequest.getPayAmount().toString()) < 0) {
                throw new BusinessCommonException(CardErrorCode.CARD_INSUFFICIENT_POINT); // 当有异常抛出时，事务回滚，订单创建回滚
            }
            //更新卡数据
            int res = this.updateCard(sourceCard.getCardNum(),sourceBalance, sourcePoint, sourceBalance, sourcePoint-Integer.parseInt(cardTradeCreateRequest.getPayAmount().toString()), null);
            if(res <= 0) {
                throw new BusinessCommonException(CardErrorCode.PAY_FAILED_CARD_DATA_INPUT_ERROR);
            }
            //存变更数据
            Integer sourceAfterPoint = sourcePoint-Integer.parseInt(cardTradeCreateRequest.getPayAmount().toString());
            this.createCardCapitalChange(sourceCard.getCardId(),sourceCard.getCardNum(),cardOrder.getCardTradeNum(),
                    0L, sourceBalance, sourceBalance,
                    -Integer.parseInt(cardTradeCreateRequest.getPayAmount().toString()), sourcePoint, sourceAfterPoint,//负数 意味着减积分
                    "卡支付消费", CardCapitalChangeType.TRANSFER.getCode(), cardOrder.getPayTime());
        }
		return new ResponseData<>(this.CardTradeCreateResponseDataHandle(cardOrder, sourceCard));
	}

    @Transactional
    @PostMapping("/cancelOrder")
    @ApiOperation(value = "订单取消接口", notes = "订单取消接口")
    public ResponseData<?> cancelOrder(@RequestBody CardTradeCancelRequest cardTradeCancelRequest) {
        cardTradeService.cancelTrade(cardTradeCancelRequest);
        return new ResponseData<>();
    }

    @Transactional
    @PostMapping("/reverseOrder")
    @ApiOperation(value = "订单撤销接口", notes = "订单撤销接口")
    public ResponseData<?> reverseOrder(@RequestBody CardTradeReverseRequest cardTradeReverseRequest) {
        CardOrder cardOrder = cardTradeService.getCardOrderByOutTradeId(cardTradeReverseRequest.getOutTradeId());
        if(cardOrder == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_NOT_EXIST);
        }
        if(cardOrder.getPayStatus().equals(CardTradeConstants.CARD_TRADE_PAY_STATUS_WFK.getCode())) {
            cardTradeService.updateCardOrder2Reverse(cardOrder);
        } else if(cardOrder.getPayStatus().equals(CardTradeConstants.CARD_TRADE_PAY_STATUS_YFK.getCode())) {
            //资金退回买家card，增加资金变动记录
            Card card = cardService.getCardByPrimaryId(cardOrder.getBuyerCardId());
            if(cardOrder.getPayType().equals(CardTradeConstants.CARD_PAY_TYPE_JF.getCode())) {//积分
                int changePoint = Integer.parseInt(cardOrder.getPayAmount().toString());
                int beforePoint = card.getCardPoint();
                int afterPoint = card.getCardPoint()+changePoint;
                int res = this.updateCard(card.getCardNum(),card.getCardBalance(), card.getCardPoint(), card.getCardBalance(),afterPoint,null);
                if(res <= 0) {
                    throw new BusinessCommonException(CardErrorCode.REVERSE_FAILED_CARD_DATA_INPUT_ERROR);
                }
                this.createCardCapitalChange(card.getCardId(),card.getCardNum(),cardOrder.getCardTradeNum(),
                        0L, card.getCardBalance(), card.getCardBalance(),
                        changePoint, beforePoint, afterPoint,//正数 意味着加积分
                        "卡支付撤销", CardCapitalChangeType.REFUND.getCode(), cardOrder.getPayTime());
            } else { //余额
                Long beforeBalance = card.getCardBalance();
                Long afterBalance = card.getCardBalance()+cardOrder.getPayAmount();
                int res = this.updateCard(card.getCardNum(), beforeBalance, card.getCardPoint(),afterBalance,card.getCardPoint(),null);
                if(res <= 0) {
                    throw new BusinessCommonException(CardErrorCode.REVERSE_FAILED_CARD_DATA_INPUT_ERROR);
                }
                this.createCardCapitalChange(card.getCardId(),card.getCardNum(),cardOrder.getCardTradeNum(),
                        cardOrder.getPayAmount(), beforeBalance, afterBalance,//正数 意味着加钱
                        0, card.getCardPoint(), card.getCardPoint(),
                        "卡支付撤销", CardCapitalChangeType.REFUND.getCode(), cardOrder.getPayTime());
            }
            cardTradeService.updateCardOrder2Reverse(cardOrder);
        } else {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_CAN_NOT_REVERSE);
        }
        return new ResponseData<>();
    }

    @Transactional
    @PostMapping("/refundOrder")
    @ApiOperation(value = "订单退款接口", notes = "订单退款接口")
    public ResponseData<CardTradeRefundResponse> refundOrder(@RequestBody CardTradeRefundRequest cardTradeRefundRequest) {
        CardOrder cardOrder = cardTradeService.getCardOrderByCardTradeNum(cardTradeRefundRequest.getCardTradeNum());
        if(cardOrder == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_NOT_EXIST);
        }
        // 判断退款总金额不能超出付款金额
        Long refundedAmount = cardOrder.getRefundedAmount()+cardTradeRefundRequest.getRefundAmount();
        if (refundedAmount.compareTo(cardOrder.getPayAmount()) > 0) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_REFUND_AMOUNT_EXCEED_PAY_AMOUNT);
        }
        // 积分支付类型不支持部分退款
        if(cardOrder.getPayType().equals(CardTradeConstants.CARD_PAY_TYPE_JF.getCode())) {
            if (refundedAmount.compareTo(cardOrder.getPayAmount()) != 0) {
                throw new BusinessCommonException(CardErrorCode.CARD_ORDER_REFUND_AMOUNT_NOT_EQUAL_PAY_AMOUNT);
            }
        }

        //创建退款单
        CardRefundOrder cardRefundOrder = cardTradeService.createCardRefundOrder(cardTradeRefundRequest);

        //资金退回买家card，增加资金变动记录
        Card card = cardService.getCardByPrimaryId(cardOrder.getBuyerCardId());
        if(cardOrder.getPayType().equals(CardTradeConstants.CARD_PAY_TYPE_JF.getCode())) {//积分
            int changePoint = Integer.parseInt(cardTradeRefundRequest.getRefundAmount().toString());
            int beforePoint = card.getCardPoint();
            int afterPoint = card.getCardPoint()+changePoint;
            int res = this.updateCard(card.getCardNum(),card.getCardBalance(), card.getCardPoint(), card.getCardBalance(),afterPoint,null);
            if(res <= 0) {
                throw new BusinessCommonException(CardErrorCode.REFUND_FAILED_CARD_DATA_INPUT_ERROR);
            }
            this.createCardCapitalChange(card.getCardId(),card.getCardNum(),cardRefundOrder.getCardRefundNum(),
                    0L, card.getCardBalance(), card.getCardBalance(),
                    changePoint, beforePoint, afterPoint,//正数 意味着加积分
                    "卡支付退款", CardCapitalChangeType.REFUND.getCode(), cardOrder.getPayTime());
        } else { //余额
            Long beforeBalance = card.getCardBalance();
            Long afterBalance = beforeBalance+cardTradeRefundRequest.getRefundAmount();
            int res = this.updateCard(card.getCardNum(),beforeBalance, card.getCardPoint(), afterBalance,card.getCardPoint(),null);
            if(res <= 0) {
                throw new BusinessCommonException(CardErrorCode.REFUND_FAILED_CARD_DATA_INPUT_ERROR);
            }
            this.createCardCapitalChange(card.getCardId(),card.getCardNum(),cardRefundOrder.getCardRefundNum(),
                    cardTradeRefundRequest.getRefundAmount(), beforeBalance, afterBalance,//正数 意味着加钱
                    0, card.getCardPoint(), card.getCardPoint(),
                    "卡支付退款", CardCapitalChangeType.REFUND.getCode(), cardOrder.getPayTime());
        }

        //更新支付单
        cardTradeService.updateCardOrder2Refunded(cardOrder, refundedAmount);
        //更新退款单状态
        cardTradeService.updateCardRefundOrder2Complete(cardRefundOrder);

        return new ResponseData<>(this.CardTradeRefundResponseDataHandle(cardRefundOrder));
    }

    @PostMapping("/queryOrder")
    @ApiOperation(value = "订单查询接口", notes = "订单查询接口")
    public ResponseData<CardTradeQueryResponse> queryOrder(@RequestBody CardTradeQueryRequest cardTradeQueryRequest) {
        return new ResponseData<>(cardTradeService.queryTrade(cardTradeQueryRequest));
    }

    @GetMapping("/getRechargeList")
    @ApiOperation(value = "第三方员工卡充值记录查询接口", notes = "第三方员工卡充值记录查询接口")
    public ResponseData<GetRechargeListResponse> getRechargeList(
            @RequestParam(value = "mcode", defaultValue = "", required = false) String mcode,
            @RequestParam(value = "sign", required = false) String sign,
            @RequestParam(value = "memberCardNo", defaultValue = "", required = false) String memberCardNo,
            @RequestParam(value = "nonce", defaultValue = "", required = false) String nonce,
            @RequestParam(value = "timestamp", defaultValue = "", required = false) String timestamp) {

        Map signMapData = getSignMapData(mcode, memberCardNo, nonce, timestamp, sign);
        if (!SignUtils.isSignatureValid(signMapData, CardTradeConstants.SIGN_KTY)) {
            throw new BusinessCommonException(CardErrorCode.CARK_MCH_SIGN_VALIDATE_ERROR);
        }
        val response = new GetRechargeListResponse();

        //long balance = cardService.getCardBalance(memberCardNo, null, null);
        Card card = cardService.getSingleCard(memberCardNo,null, null, null, null, null);
        if(card == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_NOT_EXIST);
        }
        response.setBalance(card.getCardBalance());
        response.setMemberName(changeMemberName(card.getCardAnotherId()));
        response.setRechargeList(cardTradeService.queryTradeByCardNum(card.getCardId()));
        return new ResponseData<>(response);
    }

    private String changeMemberName(String memberName){
        String resultName = "";

        char[] r =  memberName.toCharArray();
        if(r.length ==1){
            resultName =  memberName;
        }else if(r.length == 2){
            resultName =  memberName.replaceFirst(memberName.substring(1),"*");
        }else if (r.length > 2) {
            int replaceSize = r.length/2;
            int replaceStart = (r.length - replaceSize)/2;
            String replacement = "";
            for(int i = 0;i<replaceSize;i++){
                replacement = replacement + "*";
            }
            resultName =  memberName.replaceFirst(memberName.substring(replaceStart,replaceStart+replaceSize) ,replacement);
        }

        return resultName;
    }

    private Map getSignMapData(String mcode, String memberCardNo, String nonce, String timestamp, String sign) {
        Map<String, String> data = new HashMap();
        data.put("mcode",mcode);
        data.put("memberCardNo",memberCardNo);
        data.put("nonce",nonce);
        data.put("timestamp",timestamp);
        data.put("sign",sign);
        return data;
    }

    // 使用充值转换策略服务
    public Long convertAmount(Card card, Long orderAmount) {
        Long newAmount = doExchange(card, orderAmount, ExchangeStrategyConstants.EXCHANGE_STRATEGY_CATEGORY_RECHARGE.getCode());
        if(newAmount < 0) {
            newAmount = orderAmount;
        }
        return newAmount;
    }

    // 积分转换规则
    public Integer getChangedPoint(Card card,  Long amount) {
        Long newAmount = doExchange(card, amount, ExchangeStrategyConstants.EXCHANGE_STRATEGY_CATEGORY_RECHARGE.getCode());
        int point = Integer.parseInt(newAmount.toString());
        if(newAmount < 0) {
            point = 0;
        }
        return point;
    }

    public Long doExchange(Card card, Long orderAmount, String strategyCategory) {
        val cardRelationRepository = SpringUtils.getBean(card.getBeanName(), ICardRelationRepository.class);
        ExchangeStrategy exchangeStrategy = cardRelationRepository.getExchangeStrategy(card.getCardId(), strategyCategory);
        if(exchangeStrategy != null) {
            ExchangeStrategyTypeDict strategyType = exchangeStrategyTypeDictService.getExchangeStrategyType(exchangeStrategy.getStrategyTypeId());
            String params = exchangeStrategy.getParams();
            if(strategyType != null) {
                val strategy = SpringUtils.getBean(strategyType.getStrategyBeanName(), IExchangeStrategy.class);
                return strategy.doExchange(orderAmount, params);
            }
        }
        return -1L;
    }

    public int updateCard(String cardNum, Long beforeBalance, Integer beforePoint, Long afterBalance, Integer afterPoint, Long rechargeAmount) {
        UpdateCardRequest updateCardRequest = new UpdateCardRequest();
        updateCardRequest.setCardNum(cardNum);
        updateCardRequest.setCardBeforeBalance(beforeBalance);
        updateCardRequest.setCardBeforePoint(beforePoint);
        updateCardRequest.setCardAfterBalance(afterBalance);
        updateCardRequest.setCardAfterPoint(afterPoint);
        updateCardRequest.setRechargeAmount(rechargeAmount);
        return cardService.updateCard(updateCardRequest);
    }

    public void createCardCapitalChange(Integer cardId, String cardNum, String cardTradeNum,
                                         Long changeAmount, Long amountBefore, Long amountAfter,
                                         Integer changePoint, Integer pointBefore, Integer pointAfter,
                                         String content, int changeType, Date changeTime) {
        CardCapitalChange cardCapitalChange = new CardCapitalChange();
        cardCapitalChange.setCardId(cardId);
        cardCapitalChange.setCardNum(cardNum);
        cardCapitalChange.setChangeOrderId(cardTradeNum);
        cardCapitalChange.setAmountChange(changeAmount);//正数 意味着加钱, 负数 意味着减钱
        cardCapitalChange.setAmountBefore(amountBefore);
        cardCapitalChange.setAmountAfter(amountAfter);
        cardCapitalChange.setPointChange(changePoint);
        cardCapitalChange.setPointBefore(pointBefore);
        cardCapitalChange.setPointAfter(pointAfter);
        cardCapitalChange.setContent(content);
        cardCapitalChange.setChangeType(changeType);
        cardCapitalChange.setChangeTime(changeTime);
        cardCapitalChangeRepository.createChange(cardCapitalChange);
    }

    public CardTradeCreateResponse CardTradeCreateResponseDataHandle(CardOrder cardOrder, Card card) {
        card = cardService.getSingleCard(card.getCardNum(),null, null, null, null, null);
        CardTradeCreateResponse cardTradeCreateResponse = new CardTradeCreateResponse();
        cardTradeCreateResponse.setOutTradeId(cardOrder.getOutTradeId());
        cardTradeCreateResponse.setCardTradeNum(cardOrder.getCardTradeNum());
        cardTradeCreateResponse.setBalance(card.getCardBalance());
        cardTradeCreateResponse.setPoint(card.getCardPoint());
        cardTradeCreateResponse.setCardNum(card.getCardNum());
        cardTradeCreateResponse.setCardOtherId(card.getCardOtherId());
        cardTradeCreateResponse.setCardAnotherId(card.getCardAnotherId());
        cardTradeCreateResponse.setPayStatus(CardTradeConstants.getEnumByCode(CardTradeConstants.CARD_TRADE_PAY_STATUS.getCode(), cardOrder.getPayStatus()).getValue());
        cardTradeCreateResponse.setPayTime(cardOrder.getPayTime());
        return cardTradeCreateResponse;
    }

    public CardTradeRefundResponse CardTradeRefundResponseDataHandle(CardRefundOrder cardRefundOrder) {
        CardTradeRefundResponse cardTradeRefundResponse = new CardTradeRefundResponse();
        cardTradeRefundResponse.setOutTradeId(cardRefundOrder.getOutTradeId());
        cardTradeRefundResponse.setOutRefundNumber(cardRefundOrder.getOutRefundNumber());
        cardTradeRefundResponse.setCardRefundNum(cardRefundOrder.getCardRefundNum());
        cardTradeRefundResponse.setRefundAmount(cardRefundOrder.getRefundAmount());
        cardTradeRefundResponse.setRefundedTime(cardRefundOrder.getRefundedTime());
        return cardTradeRefundResponse;
    }

}
