package com.izouma.nineth.service.pay;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.BankValidate;
import com.izouma.nineth.dto.pay.*;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.enums.PayMethod;
import com.izouma.nineth.enums.PayStatus;
import com.izouma.nineth.event.GiftOrderNotifyEvent;
import com.izouma.nineth.event.OrderNotifyEvent;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.service.*;
import com.izouma.nineth.service.sms.SmsService;
import com.izouma.nineth.utils.BankUtils;
import com.izouma.nineth.utils.SnowflakeIdWorker;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 杉德支付平台
 *
 */
@Service(UniformPayConstants.SANDPAY_PLATFORM)
@AllArgsConstructor
@Slf4j
public class SandpayPlatformImpl implements UniformPayService{

    private GeneralProperties generalProperties;

    private SandpayService sandpayService;

    private OrderRepo orderRepo;

    private GiftOrderRepo giftOrderRepo;

    private CollectionRepo collectionRepo;

    private SnowflakeIdWorker snowflakeIdWorker;

    private PaymentInfoRepo paymentInfoRepo;

    private DivMoneyService divMoneyService;

    private PaymentInfoService paymentInfoService;

    private RocketMQTemplate rocketMQTemplate;

    private UserRepo userRepo;

    private UserBankCardRepo userBankCardRepo;

    private SmsService smsService;

    private IdentityAuthRepo identityAuthRepo;

    private PayHelper payHelper;

    private ApplicationContext context;

    private UserFundAccountService userFundAccountService;

    private UserFundAccountForSandpayService userFundAccountForSandpayService;

    private UserFundChangeLogService userFundChangeLogService;

    @Cacheable(value = UniformPayConstants.SANDPAY_PLATFORM, key = "#request.uniqueId")
    @Override
    public UniformPayResult pay(UniformPayRequest request) throws Exception {
        UniformPayResult.UniformPayResultBuilder resultBuilder = UniformPayResult.builder();
        resultBuilder.payPlatform(UniformPayConstants.SANDPAY_PLATFORM);
        //通过交易类型，判断是支付宝还是微信
        TradeType tradeType = request.getTradeType();

        PayMethod payMethod = PayMethod.BANK;
        String payChannel;
        switch (tradeType){
            case QUICK_PAY:
                payChannel = "quickpay";
                break;
            case ALIPAY_WAP:
            case ALIPAY_APP:
            case ALIPAY_QR:
                payChannel = "alipay";
                payMethod = PayMethod.ALIPAY;
                break;
            case WX_PUB:
            case WX_LITE:
                payChannel = "weixin";
                payMethod = PayMethod.WEIXIN;
                break;
            case WALLET_ACCOUNT:
                payChannel = "wallet";
                payMethod = PayMethod.WALLET;
                break;
            default:
                throw new BusinessException("不支持的交易方式-" + tradeType);

        }

        LocalDateTime expireTime = null;
        String orderNo = String.valueOf(snowflakeIdWorker.nextId());
        String notifyUrl = payHelper.resolvePayNotifyUrl(orderNo);
        //本地保存支付信息
        PaymentInfo paymentInfo = PaymentInfo.builder()
                .orderNo(orderNo)
                .payMethod(payMethod).payChannel(payChannel)
                .status(PayStatus.UNPAID)
                .merchantName(null)
                .notifyUrl(notifyUrl).payPlatform(UniformPayConstants.SANDPAY_PLATFORM).build();
        if(request.getOrderId() != null){
            Long orderId = request.getOrderId();
            Order order = orderRepo.findByIdAndDelFalse(orderId).orElseThrow(new BusinessException("订单不存在"));
            expireTime = payHelper.checkExpireTime(order.getCreatedAt());
            Collection collection = collectionRepo.findById(order.getCollectionId())
                    .orElseThrow(new BusinessException("藏品不存在"));

            BigDecimal payAmt = order.getTotalPrice().setScale(2, RoundingMode.HALF_UP);
            String goodsTitle = order.getName();
            paymentInfo.setUserId(order.getUserId());
            paymentInfo.setPayAmt(payAmt);
            paymentInfo.setGoodsTitle(goodsTitle);
            paymentInfo.setOrderId(order.getId());
            paymentInfo.setProjectId(order.getProjectId());
            //开始记录分账
            divMoneyService.saveDivMoney(order, collection, UniformPayConstants.SANDPAY_PLATFORM);

        }else{
            Long giftOrderId = request.getGiftOrderId();
            GiftOrder order = giftOrderRepo.findById(giftOrderId).orElseThrow(new BusinessException("转赠订单不存在"));
            expireTime = payHelper.checkExpireTime(order.getCreatedAt());
            BigDecimal payAmt = order.getGasPrice().setScale(2, RoundingMode.HALF_UP);
            paymentInfo.setUserId(order.getUserId());
            paymentInfo.setPayAmt(payAmt);
            paymentInfo.setGoodsTitle(PayHelper.GIFT_GOOGS_TITLES);
            paymentInfo.setGiftOrderId(order.getId());
            paymentInfo.setProjectId(order.getProjectId());
        }

        String timeExpire = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(expireTime);
        paymentInfo.setTimeExpire(timeExpire);
        paymentInfoRepo.save(paymentInfo);


        if("quickpay".equals(payChannel)){
            //String formStr = sandpayService.quickPayCreate(paymentInfo);
            //resultBuilder.payForm(formStr);
            //新平台支付
            String payUrl = sandpayService.quickPayCreateNew(paymentInfo);
            resultBuilder.payUrl(payUrl);
        }else if("wallet".equals(payChannel)){
            UserFundAccount userFundAccount = userFundAccountForSandpayService.getAccount(paymentInfo.getUserId());
            if(userFundAccount == null){
                throw new BusinessException("用户未开通钱包账户");
            }
            paymentInfo.setUserFundAccountId(userFundAccount.getId());
            paymentInfoRepo.save(paymentInfo);

            JSONObject res = sandpayService.accountPayCreate(paymentInfo);
            resultBuilder.payParams(res);

            //记录资金流水
            userFundChangeLogService.createByPayment(paymentInfo);

        }else{
            String formStr = sandpayService.h5payCreate(paymentInfo);
            resultBuilder.payForm(formStr);
        }

        resultBuilder.orderNo(orderNo);

        return resultBuilder.build();
    }

    @Override
    public UniformNotifyResult notify(UniformNotifyRequest request) throws Exception {
        UniformNotifyResult.UniformNotifyResultBuilder resultBuilder = UniformNotifyResult.builder();
        String orderNo = request.getOrderNo();
        String reqBody = request.getRequestBody();

        JSONObject bodyJson = sandpayService.checkSuccessBody(reqBody);

        String payTime = bodyJson.getString("payTime");//格式：yyyyMMddHHmmss
        String orderCode = bodyJson.getString("orderCode");
        String transactionId = bodyJson.getString("tradeNo");
        String orderStatus = bodyJson.getString("orderStatus");

        long eventTime  = System.currentTimeMillis();


        //1：成功
        if(!"1".equals(orderStatus)){
            log.warn("杉德收到支付通知，orderNo:" + orderNo + ",状态：" + orderStatus);
            paymentInfoService.failedPaymentInfo(orderNo, transactionId, eventTime, payTime);
            resultBuilder.content("respCode=000000");
            return resultBuilder.build();
        }


        //先修改支付状态，防止查不到的问题
        PaymentInfo paymentInfo = paymentInfoService.notifyPaymentInfo(orderNo, transactionId, eventTime, payTime);
        PayMethod payMethod = null;
        if(paymentInfo != null){
            payMethod = paymentInfo.getPayMethod();
        }

        if(paymentInfo.getOrderId() != null){
            SendResult result = rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                    new OrderNotifyEvent(paymentInfo.getOrderId(), orderNo, payMethod, transactionId, eventTime ));

            log.info("发送通知到队列: {}, result={}", paymentInfo.getOrderId(), result);
        }else{
            context.publishEvent(new GiftOrderNotifyEvent(this, paymentInfo.getGiftOrderId(),
                    orderNo,
                    paymentInfo.getPayMethod(),transactionId));

        }

        //设置响应内容
        resultBuilder.content("respCode=000000");
        return resultBuilder.build();
    }

    @Override
    public Map<String, Object> refund(String orderNo, String refundReason) throws Exception {
        PaymentInfo paymentInfo = paymentInfoRepo.findByOrderNo(orderNo)
                .orElseThrow(new BusinessException("支付信息记录不存在"));
        String transactionId = paymentInfo.getTransactionId();
        if(StringUtils.isEmpty(transactionId)){
            log.error("订单交易ID不存在，订单编号:" + paymentInfo);
            throw new BusinessException("订单交易ID不存在");
        }

        paymentInfo.setApplyRefundTime(LocalDateTime.now());
        paymentInfoRepo.save(paymentInfo);

        JSONObject resultJson;
        if("quickpay".equals(paymentInfo.getPayChannel())){
            //resultJson = sandpayService.quickPayRefund(paymentInfo, refundReason);
            resultJson = sandpayService.quickPayRefundNew(paymentInfo, refundReason);
        }else if("wallet".equals(paymentInfo.getPayChannel())){
            resultJson = sandpayService.accountPayRefund(paymentInfo, refundReason);
        }else{
            resultJson = sandpayService.h5Refund(paymentInfo, refundReason);
        }

        return resultJson;
    }

    @Override
    public UniformNotifyResult refundNotify(UniformNotifyRequest request) throws Exception {
        UniformNotifyResult.UniformNotifyResultBuilder resultBuilder = UniformNotifyResult.builder();
        String orderNo = request.getOrderNo();
        String reqBody = request.getRequestBody();
        JSONObject bodyJson = sandpayService.checkSuccessBody(reqBody);

        String tradeNo = bodyJson.getString("tradeNo");//支付方交易流水
        String payTime = bodyJson.getString("payTime");//支付时间
        String orderCode = bodyJson.getString("orderCode");//退款订单号，指发起交易的流水号，建议订单号有日期
        String oriOrderCode = bodyJson.getString("oriOrderCode");//原始订单号
        String orderStatus = bodyJson.getString("orderStatus");//状态,1-成功   3-退款失败

        if("1".equals(orderStatus)){
            //更改支付信息状态
            paymentInfoService.completeRefund(orderNo, orderCode, payTime);
        }else{
            log.warn("杉德收到退款通知，orderNo:" + orderNo + ",状态：" + orderStatus);
        }


        //设置响应内容
        resultBuilder.content("respCode=000000");
        return resultBuilder.build();
    }

    @Override
    public UniformNotifyResult transferNotify(UniformNotifyRequest request) throws Exception {
        throw new BusinessException("暂不支持");
    }

    @Override
    @Transactional
    public UserBankCard addBankCard(UniformBindBank bindBank) throws Exception {
        Long userId = bindBank.getUserId();
        String bankNo = bindBank.getBankNo();
        String phone = bindBank.getPhone();
        String smsCode = bindBank.getSmsCode();

        //短信验证
        smsService.verify(phone, smsCode);

        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
                .orElseThrow(new BusinessException("用户未通过实名认证"));
        if (identityAuth.isOrg()) {
            //throw new BusinessException("企业认证用户请绑定对公账户");
        }

        if(isBindBankCard(userId)){
            throw new BusinessException("此账号已绑定过，请先解绑");
        }

        BankValidate bankValidate = BankUtils.validate(bankNo);
        if (!bankValidate.isValidated()) {
            throw new BusinessException("暂不支持此卡");
        }

        UserBankCard userBankCard = userBankCardRepo.save(UserBankCard.builder()
                .payPlatform(UniformPayConstants.SANDPAY_PLATFORM)
                .bank(bankValidate.getBank())
                .bankName(bankValidate.getBankName())
                .bankNo(bankNo)
                .cardType(bankValidate.getCardType())
                .cardTypeDesc(bankValidate.getCardTypeDesc())
                .userId(userId)
                .phone(phone)
                .realName(identityAuth.getRealName())
                .idNo(identityAuth.getIdNo())
                .build());

        //支付方绑定
//        user.setMemberId(user.getId().toString());
//        String accountId = sandpayService.addReceiveCustomer(user.getMemberId(), identityAuth.getRealName(),
//                identityAuth.getIdNo(), userBankCard.getBankNo());
//
//        userBankCard.setThirdAccountId(accountId);

        userBankCard = userBankCardRepo.save(userBankCard);

        //支付方绑卡
        userFundAccountForSandpayService.bindCard(userBankCard);

        return userBankCard;
    }

    @Override
    public void removeBankCard(Long userId) throws Exception {
        //支付方解绑
        userFundAccountForSandpayService.unbindCard(userId);

        //直接解绑
        userBankCardRepo.deleteByUserId(userId);

    }

    @Override
    public boolean isBindBankCard(Long userId) {
        User owner = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        UserBankCard userBankCard = userBankCardRepo.findByUserId(owner.getId())
                .stream().findAny()
                .orElse(null);
        //特殊情况，需要判断是否有关联支付通道的账户
        if(userBankCard != null){
            return true;
        }

        return false;
    }


}
