package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.request.AlipayTradeRefundApplyRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.izouma.nineth.ApplicationTests;
import com.izouma.nineth.domain.TokenHistory;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.domain.UserBankCard;
import com.izouma.nineth.enums.AssetStatus;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.service.pay.UniformPayUtil;
import com.izouma.nineth.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.EncoderException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
public class OrderServiceTest extends ApplicationTests {
    @Autowired
    private OrderService     orderService;
    @Autowired
    private OrderRepo        orderRepo;
    @Autowired
    private AssetRepo        assetRepo;
    @Autowired
    private TokenHistoryRepo tokenHistoryRepo;
    @Autowired
    private AssetService     assetService;
    @Autowired
    private CollectionRepo   collectionRepo;
    @Autowired
    private UserRepo         userRepo;
    @Autowired
    private IdentityAuthRepo identityAuthRepo;
    @Autowired
    private UserBankCardRepo userBankCardRepo;

    @Autowired
    private UniformPayUtil uniformPayUtil;

    @Test
    public void create() throws EncoderException, WxPayException {
    }

    @Test
    public void setNumber() {
        orderService.setNumber();
    }


    @Test
    public void commission() {
        orderService.commission(orderRepo.findById(4437L).get());
    }


    @Test
    public void fixTokenHistory() {
        for (TokenHistory tokenHistory : tokenHistoryRepo.findError()) {
            List<Asset> assets = assetRepo.findByTokenIdOrderByCreatedAt(tokenHistory.getTokenId());
            if (assets.size() == 2) {
                userRepo.findById(assets.get(0).getUserId()).ifPresent(fromUser -> {
                    tokenHistory.setFromUserId(assets.get(0).getUserId());
                    tokenHistory.setFromUser(fromUser.getNickname());
                    tokenHistory.setFromAvatar(fromUser.getAvatar());
                    tokenHistoryRepo.save(tokenHistory);
                });
            }
        }
    }

    @Test
    public void fixPay() {
        String s = "\n订单ID\t金额\t手续费\t版税\t收款用户ID\t收款人\t银行卡号\t银行";
        for (Long orderId : new Long[]{5417L, 5919L, 5923L, 8166L}) {
            try {
                Order order = orderRepo.findById(orderId).get();
                List<Asset> assets = assetRepo.findByTokenIdOrderByCreatedAt(assetRepo.findById(order.getAssetId())
                        .get()
                        .getTokenId());
                Asset asset = assets.stream().filter(a -> a.getStatus() == AssetStatus.TRANSFERRED).findAny().get();
                User user = userRepo.findById(asset.getUserId()).get();
                Optional<IdentityAuth> identityAuth = identityAuthRepo.findByUserIdAndDelFalse(user.getId()).stream()
                        .filter(i -> i.getStatus() == AuthStatus.SUCCESS).findAny();
                Optional<UserBankCard> bankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny();
                s += "\n"
                        + orderId + "\t"
                        + order.getTotalPrice().subtract(order.getGasPrice()) + "\t"
                        + order.getServiceCharge() + "\t"
                        + order.getRoyalties() + "\t"
                        + user.getId() + "\t"
                        + identityAuth.map(IdentityAuth::getRealName).orElse("") + "\t"
                        + bankCard.map(UserBankCard::getBankNo).orElse("") + "\t"
                        + bankCard.map(UserBankCard::getBankName).orElse("");
            } catch (Exception e) {

            }

        }
        log.info(s);
    }

    @Test
    public void consignmentFix() throws IOException {
        String s = FileUtils.readFile("/Users/drew/Downloads/app.log").replaceAll("</p>\n","</p>");
        String[] arr = s.split("\n");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].contains("insert into collection_info")) {
//                arr[i][2]
            }
        }
    }

    @Autowired
    private AlipayClient alipayClient;
    @Test
    public void refund(){
        AlipayTradeRefundApplyRequest request = new AlipayTradeRefundApplyRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "961647641144328192");
        bizContent.put("trade_no", "2022040722001476751427128492");
        String refundAmount = "0.61";
        bizContent.put("refund_amount", refundAmount);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        Map<String,Object> refundResult = (JSONObject)JSONObject.toJSON(response);

        System.out.println(refundResult);
    }
}