package com.izouma.nineth.service.pay;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.config.SumpayProperties;
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.*;
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.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 java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service(UniformPayConstants.SUMPAY_PLATFORM)
@AllArgsConstructor
@Slf4j
public class SumpayPlatformImpl implements  UniformPayService{

    private GeneralProperties generalProperties;

    private SumpayProperties sumpayProperties;

    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 SumpayMerchantService sumpayMerchantService;

    private UserFundAccountService userFundAccountService;

    private UserFundAccountForSumpayService userFundAccountForSumpayService;
    private PayHelper payHelper;

    private ApplicationContext context;

    @Cacheable(value = UniformPayConstants.SUMPAY_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);

        //本地保存支付信息
        PaymentInfo paymentInfo = PaymentInfo.builder()
                .orderNo(orderNo)
                .payMethod(payMethod).payChannel(payChannel)
                .status(PayStatus.UNPAID)
                .merchantName(null)
                .notifyUrl(notifyUrl).payPlatform(UniformPayConstants.SUMPAY_PLATFORM).build();

        List<DivMoney> divMoneyList = null;
        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());
            //开始记录分账
            divMoneyList  = divMoneyService.saveDivMoney(order, collection, UniformPayConstants.SUMPAY_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);


        JSONObject response = sumpayMerchantService.qrCodeTrade(paymentInfo, divMoneyList);
        String codeUrl = response.getString("code_url");
        UniformPayResult.UniformPayResultBuilder resultBuilder = UniformPayResult.builder();
        resultBuilder.payPlatform(UniformPayConstants.SUMPAY_PLATFORM);
        resultBuilder.orderNo(orderNo);
        resultBuilder.payUrl(codeUrl);
        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 = JSONObject.parseObject(reqBody);
        sumpayMerchantService.verifySign(bodyJson);

        String orderTime = bodyJson.getString("order_time");//订单创建日期yyyymmddhhmmss
        String successTime = bodyJson.getString("success_time");
        //String orderNo = bodyJson.getString("order_no");
        String tradeNo = bodyJson.getString("trade_no");//商盟订单号
        String transactionId = bodyJson.getString("channel_serial_no");//渠道流水
        String status = bodyJson.getString("status");
        long eventTime  = System.currentTimeMillis();
        //0：失败
        //1：成功
        //2：处理中
        if(!"1".equals(status)){
            log.warn("商盟收到支付通知，orderNo:" + orderNo + ",状态：" + status);
            paymentInfoService.failedPaymentInfo(orderNo, transactionId, tradeNo, eventTime, orderTime);
            //设置响应内容
            JSONObject resContent = new JSONObject();
            resContent.put("resp_code", "000000");
            resContent.put("resp_msg", "success");
            resultBuilder.content(resContent.toJSONString());
            return resultBuilder.build();
        }

        //先修改支付状态，防止查不到的问题
        PaymentInfo paymentInfo = paymentInfoService.notifyPaymentInfo(orderNo, tradeNo, eventTime, orderTime);
        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, tradeNo, eventTime ));

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

        }

        //设置响应内容
        JSONObject resContent = new JSONObject();
        resContent.put("resp_code", "000000");
        resContent.put("resp_msg", "success");
        resultBuilder.content(resContent.toJSONString());
        return resultBuilder.build();
    }

    @Override
    public Map<String, Object> refund(String orderNo, String refundReason) throws Exception {
        PaymentInfo paymentInfo = paymentInfoRepo.findByOrderNo(orderNo)
                .orElseThrow(new BusinessException("支付信息记录不存在"));


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

        Map<String,Object> result = sumpayMerchantService.tradeRefund(paymentInfo.getOrderNo(), paymentInfo.getPayAmt(), refundReason);
        return result;
    }

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

        JSONObject bodyJson = JSONObject.parseObject(reqBody);
        sumpayMerchantService.verifySign(bodyJson);

        String refundNo = bodyJson.getString("refund_no");
        String serialNo = bodyJson.getString("serial_no");
        String status = bodyJson.getString("status");
        //0：失败
        //1：成功
        //2：处理中
        if(!"1".equals(status)){
            log.warn("商盟收到退款通知，orderNo:" + orderNo + ",状态：" + status);
            //设置响应内容
            JSONObject resContent = new JSONObject();
            resContent.put("resp_code", "000000");
            resContent.put("resp_msg", "success");
            resultBuilder.content(resContent.toJSONString());
            return resultBuilder.build();
        }

        //更改支付信息状态
        paymentInfoService.completeRefund(orderNo, refundNo);


        //设置响应内容
        JSONObject resContent = new JSONObject();
        resContent.put("resp_code", "000000");
        resContent.put("resp_msg", "success");
        resultBuilder.content(resContent.toJSONString());
        return resultBuilder.build();
    }

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

    @Override
    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.SUMPAY_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);


        //支付方绑定
        userFundAccountForSumpayService.bindCard(userBankCard);
        return userBankCard;
    }

    @Override
    public void removeBankCard(Long userId) throws Exception {
        //直接解绑
        userBankCardRepo.deleteByUserId(userId);
    }

    @Override
    public boolean isBindBankCard(Long userId) {
        UserBankCard userBankCard = userBankCardRepo.findByUserId(userId)
                .stream().findAny()
                .orElse(null);
        //特殊情况，需要判断是否有关联支付通道的账户
        if(userBankCard != null){
            return true;
        }

        return false;
    }
}
