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

import com.neusoft.smart.pos.card.constants.CardErrorCode;
import com.neusoft.smart.pos.card.constants.CardTradeConstants;
import com.neusoft.smart.pos.card.persistent.domain.CardOrder;
import com.neusoft.smart.pos.card.persistent.domain.CardRefundOrder;
import com.neusoft.smart.pos.card.persistent.repository.CardOrderRepository;
import com.neusoft.smart.pos.card.persistent.repository.CardRefundOrderRepository;
import com.neusoft.smart.pos.dto.card.request.*;
import com.neusoft.smart.pos.dto.card.response.CardOrderInfoResponse;
import com.neusoft.smart.pos.dto.card.response.CardTradeQueryResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.IdGenerateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CardTradeService{
//    private final static Logger logger = LoggerFactory.getLogger(CardTradeService.class);
	
	@Resource
	private CardOrderRepository cardOrderRepository;

    @Resource
    private CardRefundOrderRepository cardRefundOrderRepository;

    /**
     * 创建充值订单
     * @param rechargeRequest 充值请求
     * @param cardid 充值卡ID
     * @return 卡内余额
     */
    public CardOrder createRechargeOrder(RechargeRequest rechargeRequest, Integer cardid) {
        //存在数据说明已经充值过
        if (cardOrderRepository.getOrderCountByOrderId(rechargeRequest.getOutRechargeOrderNo(), CardTradeConstants.ORDER_TYPE_CZ.getCode()) > 0) {
            throw new BusinessCommonException(CardErrorCode.RECHARGE_NUM_DUPLICATE);
        }
        // 创建订单
        CardOrder cardOrder = new CardOrder();
        cardOrder.setOutTradeId(rechargeRequest.getOutRechargeOrderNo());
        cardOrder.setBuyerCardId(cardid);
        cardOrder.setOrderType(CardTradeConstants.ORDER_TYPE_CZ.getCode());
        cardOrder.setCardTradeNum(generateCardTradeNum());
        cardOrder.setPayAmount(rechargeRequest.getRechargeAmount());
        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_YFK.getCode());
        cardOrder.setPayTime(rechargeRequest.getRechargeTime());
        cardOrder.setDescription("充值");
        cardOrderRepository.createOrder(cardOrder);
        return cardOrder;
    }

    private String generateCardTradeNum() {
        return IdGenerateUtils.generateMemberCardNum();
    }

    /**
     * 创建转账订单
     * @param transferRequest 转账请求
     * @param sourceCardId 转出方卡号
     * @param targetCardId 转入方卡号
     * @return 订单信息
     */
    public CardOrder createTransferOrder(TransferRequest transferRequest, Integer sourceCardId, Integer targetCardId) {
        //存在数据说明已经转账过
        if (cardOrderRepository.getOrderCountByOrderId(transferRequest.getOutTransferOrderNo(), CardTradeConstants.ORDER_TYPE_ZZ.getCode()) > 0) {
            throw new BusinessCommonException(CardErrorCode.TRANSFER_NUM_DUPLICATE);
        }
        // 创建订单
        CardOrder cardOrder = new CardOrder();
        cardOrder.setOutTradeId(transferRequest.getOutTransferOrderNo());
        cardOrder.setBuyerCardId(sourceCardId);
        cardOrder.setSellerCardId(targetCardId);
        cardOrder.setOrderType(CardTradeConstants.ORDER_TYPE_ZZ.getCode());
        cardOrder.setCardTradeNum(generateCardTradeNum());
        cardOrder.setPayAmount(transferRequest.getTransferAmount());
        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_YFK.getCode());
        cardOrder.setPayTime(transferRequest.getTransferTime());
        cardOrder.setDescription("转账");
        cardOrderRepository.createOrder(cardOrder);
        return cardOrder;
    }

    /**
     * 创建支付订单
     * @param cardTradeCreateRequest 支付请求
     * @param sourceCardId 买方卡号
     * @param targetCardId 卖方卡号
     * @return 订单信息
     */
    public CardOrder createPayOrder(CardTradeCreateRequest cardTradeCreateRequest, Integer sourceCardId, Integer targetCardId) {
        CardOrder cardOrder = new CardOrder();
        cardOrder.setOutTradeId(cardTradeCreateRequest.getOutTradeId());
        cardOrder.setBuyerCardId(sourceCardId);
        cardOrder.setSellerCardId(targetCardId);
        cardOrder.setOrderType(CardTradeConstants.ORDER_TYPE_ZF.getCode());
        cardOrder.setCardTradeNum(generateCardTradeNum());
        cardOrder.setPayAmount(cardTradeCreateRequest.getPayAmount());
        cardOrder.setPayType(cardTradeCreateRequest.getPayType());
        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_YFK.getCode());
        cardOrder.setPayTime(new Date());
        cardOrder.setDescription("消费");
        cardOrderRepository.createOrder(cardOrder);
        return cardOrder;
    }

    /**
     * 创建支付退款单
     * @param cardTradeRefundRequest 退款请求
     * @return 退款单信息
     */
    public CardRefundOrder createCardRefundOrder(CardTradeRefundRequest cardTradeRefundRequest) {
        CardRefundOrder cardRefundOrder = new CardRefundOrder();
        cardRefundOrder.setOutTradeId(cardTradeRefundRequest.getOutTradeId());
        cardRefundOrder.setOutRefundNumber(cardTradeRefundRequest.getOutRefundNumber());
        cardRefundOrder.setCardTradeNum(cardTradeRefundRequest.getCardTradeNum());
        cardRefundOrder.setCardRefundNum(this.generateCardTradeNum());
        cardRefundOrder.setRefundAmount(cardTradeRefundRequest.getRefundAmount());
        cardRefundOrder.setRefundStatus(CardTradeConstants.CARD_TRADE_REFUND_STATUS_YTK.getCode());// 退款状态为从卖家扣款成功
        cardRefundOrder.setRefundedTime(new Date());
        cardRefundOrderRepository.createRefundOrder(cardRefundOrder);
        return cardRefundOrder;
    }


    /**
     * 更新退款订单状态为退款完成
     * @param cardRefundOrder 原退款订单
     */
    public void updateCardRefundOrder2Complete(CardRefundOrder cardRefundOrder) {
        cardRefundOrder.setRefundStatus(CardTradeConstants.CARD_TRADE_REFUND_STATUS_TKWC.getCode());
        cardRefundOrderRepository.updateByPrimarykey(cardRefundOrder);
    }


    /**
     * 根据cardTradeNum获得订单信息
     * @param cardTradeNum 卡交易单号
     * @return 订单信息
     */
    public CardOrder getCardOrderByCardTradeNum(String cardTradeNum) {
        return cardOrderRepository.getCardOrderByCardTradeNum(cardTradeNum);
    }

    /**
     * 根据outTradeId获得订单信息
     * @param outTradeId 平台交易单号
     * @return 订单信息
     */
    public CardOrder getCardOrderByOutTradeId(String outTradeId) {
        return cardOrderRepository.getCardOrderByOutTradeId(outTradeId);
    }

    /**
     * 更新订单状态为已退款
     * @param cardOrder 原订单
     * @param refundedAmount 已退款金额
     */
    public void updateCardOrder2Refunded(CardOrder cardOrder, Long refundedAmount) {
        cardOrder.setRefundedAmount(refundedAmount);
        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_YTK.getCode());
        cardOrderRepository.updateByPrimarykey(cardOrder);
    }

    /**
     * 更新订单状态为已撤销
     * @param cardOrder 原订单
     */
    public void updateCardOrder2Reverse(CardOrder cardOrder) {
        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_CX.getCode());
        cardOrderRepository.updateByPrimarykey(cardOrder);
    }


    /**
     * 取消订单
     * @param cardTradeCancelRequest 取消请求
     */
    @Transactional
    public void cancelTrade(CardTradeCancelRequest cardTradeCancelRequest) { //只能是未支付情况可以取消
        CardOrder cardOrder = this.getCardOrderByOutTradeId(cardTradeCancelRequest.getOutTradeId());
        if(cardOrder == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_NOT_EXIST);
        }
        if(!cardOrder.getPayStatus().equals(CardTradeConstants.CARD_TRADE_PAY_STATUS_WFK.getCode())) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_CAN_NOT_CANCEL);
        }

        cardOrder.setPayStatus(CardTradeConstants.CARD_TRADE_PAY_STATUS_QX.getCode());
        cardOrderRepository.updateByPrimarykey(cardOrder);
    }


    /**
     * 查询订单
     * @param cardTradeQueryRequest 查询请求
     * @return 订单查询响应
     */
    public CardTradeQueryResponse queryTrade(CardTradeQueryRequest cardTradeQueryRequest) {
        CardOrder cardOrder = cardOrderRepository.getCardOrderByOutTradeId(cardTradeQueryRequest.getOutTradeId());
        if(cardOrder == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_NOT_EXIST);
        }
        CardTradeQueryResponse cardTradeQueryResponse = new CardTradeQueryResponse();
        cardTradeQueryResponse.setOutTradeId(cardOrder.getOutTradeId());
        cardTradeQueryResponse.setCardTradeNum(cardOrder.getCardTradeNum());
        cardTradeQueryResponse.setPayStatus(cardOrder.getPayStatus());
        cardTradeQueryResponse.setPayTime(cardOrder.getPayTime());
        return cardTradeQueryResponse;
    }

    /**
     * 查询订单
     * @param cardId 员工卡Id
     * @return 订单查询响应
     */
    public List<CardOrderInfoResponse> queryTradeByCardNum(int cardId) {
        List<CardOrder> orderList = cardOrderRepository.getCardOrderByCardId(cardId);
        if(orderList == null) {
            throw new BusinessCommonException(CardErrorCode.CARD_ORDER_NOT_EXIST);
        }
        List<CardOrderInfoResponse> tradeList = new ArrayList<>();
        for (int i = 0; i < orderList.size() && i < 3; i++) {
            CardOrder cardOrder = orderList.get(i);
            CardOrderInfoResponse cardTradeQueryResponse = new CardOrderInfoResponse();
            cardTradeQueryResponse.setOrderNo(cardOrder.getOutTradeId());
            cardTradeQueryResponse.setTime(cardOrder.getPayTime());
            cardTradeQueryResponse.setAmount(cardOrder.getPayAmount());
            if ("充值:34".equals(cardOrder.getDescription())) {
                cardTradeQueryResponse.setChannel("招行APP");
            } else {
                cardTradeQueryResponse.setChannel("东软餐厅");
            }
            tradeList.add(cardTradeQueryResponse);
        }
//        for (CardOrder cardOrder:orderList) {
//            CardOrderInfoResponse cardTradeQueryResponse = new CardOrderInfoResponse();
//            cardTradeQueryResponse.setOrderNo(cardOrder.getOutTradeId());
//            cardTradeQueryResponse.setTime(cardOrder.getPayTime());
//            cardTradeQueryResponse.setAmount(cardOrder.getPayAmount());
//            if("充值:34".equals(cardOrder.getDescription())){
//                cardTradeQueryResponse.setChannel("招行APP");
//            }else {
//                cardTradeQueryResponse.setChannel("东软餐厅");
//            }
//            tradeList.add(cardTradeQueryResponse);
//        }

        return tradeList;
    }
}
