package com.izouma.nineth.service.pay;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.config.PayeasenetProperties;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.BankValidate;
import com.izouma.nineth.dto.pay.*;
import com.izouma.nineth.enums.*;
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.DivMoneyService;
import com.izouma.nineth.service.PayeasenetService;
import com.izouma.nineth.service.PaymentInfoService;
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.PAYEASENET_PLATFORM)
@AllArgsConstructor
@Slf4j
public class PayeasenetPlatformImpl implements UniformPayService{

    private GeneralProperties generalProperties;

    private PayeasenetProperties payeasenetProperties;

    private PayeasenetService payeasenetService;

    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 TransferMoneyInfoRepo transferMoneyInfoRepo;

    private ApplicationContext context;

    @Cacheable(value = UniformPayConstants.PAYEASENET_PLATFORM, key = "#request.uniqueId")
    @Override
    public UniformPayResult pay(UniformPayRequest request) throws Exception {

        //通过交易类型，判断是支付宝还是微信
        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;
            default:
                throw new BusinessException("不支持的交易方式-" + tradeType);

        }


        LocalDateTime expireTime = null;
        String orderNo = String.valueOf(snowflakeIdWorker.nextId());
        String notifyUrl = payHelper.resolvePayNotifyUrl(orderNo);

        String clientIp = null;
        //本地保存支付信息
        PaymentInfo paymentInfo = PaymentInfo.builder()
                .orderNo(orderNo)
                .payMethod(payMethod).payChannel(payChannel)
                .status(PayStatus.UNPAID)
                .merchantName(null)
                .notifyUrl(notifyUrl).payPlatform(UniformPayConstants.PAYEASENET_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.PAYEASENET_PLATFORM);

            clientIp = order.getIp();
        }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());
            clientIp = order.getIp();
        }

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

        JSONObject res  = payeasenetService.unifyPay(paymentInfo, clientIp);
        String status = res.getString("status");
        String redirectUrl = res.getString("redirectUrl");
        //如果是二维码方式，则有二维码图片数据
        String scanCode = res.getString("scanCode");
        String appParams = res.getString("appParams");
        String jsString = res.getString("jsString");
        String openLink = res.getString("openLink");

        UniformPayResult.UniformPayResultBuilder resultBuilder = UniformPayResult.builder();
        resultBuilder.payPlatform(UniformPayConstants.PAYEASENET_PLATFORM);
        resultBuilder.orderNo(orderNo);
        resultBuilder.payUrl(redirectUrl);
        if(StringUtils.isEmpty(redirectUrl)){
            //自定义表单内容
            String formContent =  "<script type=\"text/html\"  >"+res.toString()+"</script>";
            resultBuilder.payForm(formContent);
        }

        return resultBuilder.build();
    }

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

        String encryptKey = request.getHeader("encryptKey");
        JSONObject bodyJson = payeasenetService.checkSuccessBody(reqBody, encryptKey);

        String requestId = bodyJson.getString("requestId");//订单号
        String completeDateTime = bodyJson.getString("completeDateTime");//订单完成时间
        String transactionId = bodyJson.getString("serialNumber");
        String errorMessage = bodyJson.getString("errorMessage");
        String status = bodyJson.getString("status");

        long eventTime  = System.currentTimeMillis();


        //SUCCESS：成功, CANCEL取消, FAILED失败
        if(!"SUCCESS".equals(status)){
            log.warn("首信易收到支付通知，orderNo:" + orderNo + ",状态：" + status + ",消息：" + errorMessage);
            paymentInfoService.failedPaymentInfo(orderNo, transactionId, eventTime, completeDateTime);
            resultBuilder.content("SUCCESS");
            return resultBuilder.build();
        }


        //先修改支付状态，防止查不到的问题
        PaymentInfo paymentInfo = paymentInfoService.notifyPaymentInfo(orderNo, transactionId, eventTime, completeDateTime);
        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("SUCCESS");
        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 = payeasenetService.refund(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();
        String encryptKey = request.getHeader("encryptKey");
        JSONObject bodyJson = payeasenetService.checkSuccessBody(reqBody, encryptKey);

        String requestId = bodyJson.getString("requestId");//退款订单号
        String completeDateTime = bodyJson.getString("completeDateTime");//订单完成时间
        String serialNumber = bodyJson.getString("serialNumber");
        String errorMessage = bodyJson.getString("errorMessage");
        String status = bodyJson.getString("status");

        //SUCCESS：成功, FAILED失败
        if("SUCCESS".equals(status)){
            //更改支付信息状态
            paymentInfoService.completeRefund(orderNo, requestId, completeDateTime);
        }else{
            log.warn("首信易收到退款通知，orderNo:" + orderNo + ",状态：" + status + ",消息：" + errorMessage);
        }

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

    @Override
    public UniformNotifyResult transferNotify(UniformNotifyRequest request) throws Exception {
        UniformNotifyResult.UniformNotifyResultBuilder resultBuilder = UniformNotifyResult.builder();
        String tradeNo = request.getOrderNo();
        String reqBody = request.getRequestBody();
        String encryptKey = request.getHeader("encryptKey");
        JSONObject bodyJson = payeasenetService.checkSuccessBody(reqBody, encryptKey);

        TransferMoneyInfo transferMoneyInfo = transferMoneyInfoRepo.findByTradeNo(tradeNo)
                .orElseThrow(new BusinessException("转账记录不存在"));
        String requestId = bodyJson.getString("requestId");
        String status = bodyJson.getString("status");
        String serialNumber = bodyJson.getString("serialNumber");
        String completeDateTime = bodyJson.getString("completeDateTime");

        String resultStr = "查询结果成功";
        //SUCCESS 代付到账成功
        //FAILED 代付失败，商户可重新发起
        //CANCEL 代付取消，商户可重新发起
        //INIT 代付待处理，等待后再次查询，如果长时间保持此状态请联系首信易
        //REMITING 代付中，等待后再次查询，如果长时间保持此状态请联系首信易
        //ERROR (此状态的返回参数见异常情况说明)
        if("SUCCESS".equals(status)){
            transferMoneyInfo.setStatus(TransferStatus.SUCCESS);
        }else if("FAILED".equals(status) || "CANCEL".equals(status) || "ERROR".equals(status)){
            transferMoneyInfo.setStatus(TransferStatus.FAILED);
            resultStr = "响应状态为失败：" + status;
        }else{
            transferMoneyInfo.setStatus(TransferStatus.PROCESSING);
            resultStr = "处理中:" + status;
        }

        transferMoneyInfo.setTransactionId(serialNumber);
        transferMoneyInfo.setTransferDate(completeDateTime);
        transferMoneyInfo.setResult(resultStr);
        transferMoneyInfo.setFinishTime(LocalDateTime.now());
        transferMoneyInfoRepo.save(transferMoneyInfo);

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

    @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.PAYEASENET_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());

        //支付方绑定
        userBankCardRepo.save(userBankCard);
        return userBankCard;
    }

    @Override
    public void removeBankCard(Long userId) throws Exception {
        //直接解绑
        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;
    }


}
