package com.sonic.lion.service.impl;

import com.sonic.lion.domain.entity.GoogleUploadReceipt;
import com.sonic.lion.domain.entity.IapUploadReceipt;
import com.sonic.lion.domain.input.UploadReceiptInput;
import com.sonic.lion.domain.req.UploadReceiptReq;
import com.sonic.lion.service.*;
import com.sonic.lion.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ReceiptHandlerServiceImpl implements ReceiptHandlerService {

    @Autowired
    private IapUploadReceiptService iapUploadReceiptService;
    @Autowired
    private IapService iapService;
    @Autowired
    private GoogleService googleService;
    @Autowired
    private GoogleUploadReceiptService googleUploadReceiptService;

    @Override
    public void uploadIosSubReceipt(Long userId, UploadReceiptInput input) {
        String md5 = MD5Utils.stringToMD5(input.getReceipt());
        IapUploadReceipt receipt = IapUploadReceipt.builder().receipt(input.getReceipt()).transactionsJsonStr(md5).userId(userId).createTime(LocalDateTime.now()).build();
        Long receiptId = null;
        try {
            receiptId = iapUploadReceiptService.save(receipt);
            iapService.handReceiptSubscribe(input.getProductId(), receiptId, userId);
        } catch (org.springframework.dao.DuplicateKeyException e) {
            log.info("IOS应用商店订购上传凭据 md5:{} userId:{} 重复", md5, userId);
        } catch (Exception e2) {
            if (e2 instanceof RestClientException) {
                try {
                    Thread.sleep(300L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                iapService.handReceiptSubscribe(input.getProductId(), receiptId, userId);
            }
            log.error("IOS应用商店订购上传凭据错误userId:" + userId, e2);
        }
    }

    @Override
    public void uploadGoogleSubReceipt(Long userId, UploadReceiptReq input) {
        String md5 = MD5Utils.stringToMD5(input.getReceipt());
        try {
            GoogleUploadReceipt googleUploadReceipt = GoogleUploadReceipt.builder()
                    .transactionsJsonStr(md5)
                    .receipt(input.getReceipt())
                    .processed(Boolean.FALSE)
                    .build();
            Long receiptId = googleUploadReceiptService.save(googleUploadReceipt);
            googleService.handReceiptSubscribe(input.getProductId(), receiptId, userId);
        } catch (org.springframework.dao.DuplicateKeyException e) {
            log.info("Google上传收据 md5:{} 重复", md5);
        } catch (Exception e1) {
            log.error("Google上传收据:错误", e1);
        }
    }
}
