package com.example.sjkbf.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.example.sjkbf.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author l'amour solitaire
 * @Description 订单服务相关
 * @Date 2022/12/1 下午5:24
 **/
@Slf4j
@Service
public class UserOrderService {

    @Autowired
    private UserService userService;

    private final String payKey = "8658ea66fbbe4a1aad4691ddecefe5fa";

    private final String payUrl = "https://2277883.pay.lanjingzf.com/createOrder?";

    private static final String CREATE_PARAMS = "payId=%s&type=%s&price=%s&sign=%s&isHtml=1";




    public static TimedCache<String, Integer> timedCache = CacheUtil.newTimedCache(3000);

    Map<String, Integer> orderIdAndPrice=new HashMap<>();

    static {
        timedCache.schedulePrune(100);
    }



    /**
     * @param payType 【必传】微信支付传入1 支付宝支付传入2
     * @param price   【必传】订单金额
     * @Author l'amour solitaire
     * @Description 创建订单
     * @Date 2022/12/1 下午5:46
     **/
    public String create(Integer payType, int price,String name) throws IOException {

        Integer i = timedCache.get(name);
        if (i==null) {
            timedCache.put(name, 1,5*60*1000);

        }else {
            return "上次提交暂未结束，请稍后重试";
        }




        // 创建订单  订单号为uid:时间戳
        String orderId = name + ":" + System.currentTimeMillis();

        orderIdAndPrice.put(orderId,price);

        String CREATE_PARAMS = "payId=%s&type=%d&price=%s&sign=%s&isHtml=1";


        String signSource = orderId + payType + price + payKey;
        String sign = DigestUtil.md5Hex(signSource);

        String paramMap = String.format(CREATE_PARAMS, orderId, payType, price, sign);

        HttpResponse execute = HttpRequest.get(payUrl+paramMap)
//                .header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute();
        String body = execute.body();



        // 返回支付页面地址，前端进行弹框展示即可
        return "https://2277883.pay.lanjingzf.com/"+extractBetweenQuotes(body);
    }

    /**
     * 支付回调
     **/
    public String callback(String payId, String param, int type, double price, double reallyPrice, String sign) {
        Assert.isTrue(sign.equals(DigestUtil.md5Hex(payId + param + type + price + reallyPrice + payKey)), "非法请求！");
        System.out.println(payId);
        Integer i = orderIdAndPrice.get(payId);

        System.out.println(orderIdAndPrice);
        if (i==null) {
            log.info("订单不存在");
            return "订单不存在";
        }
        if (i==-1){
            log.info("订单已处理");
            return "订单已处理";
        }

        String[] split = payId.split(":");


        userService.addgold(split[0],i);
        log.info("订单支付成功");

        timedCache.remove(split[0]);

        orderIdAndPrice.put(payId,-1);

        // 返回这个字符串，支付平台就知道回调接口成功了
        return "success";
    }


    public static String extractBetweenQuotes(String input) {
        // 检查输入是否为null
        if (input == null) {
            return null;
        }

        // 找到第一个单引号的位置
        int firstQuoteIndex = input.indexOf('\'');
        // 找到第二个单引号的位置（从第一个引号之后开始查找）
        int secondQuoteIndex = input.indexOf('\'', firstQuoteIndex + 1);

        // 检查两个引号是否都存在且位置有效
        if (firstQuoteIndex != -1 && secondQuoteIndex != -1 && secondQuoteIndex > firstQuoteIndex) {
            // 提取两个引号之间的子字符串
            return input.substring(firstQuoteIndex + 1, secondQuoteIndex);
        }

        // 如果未找到有效的引号对，返回null
        return null;
    }


    public static void main(String[] args) {

        int 毛收入=1890 +1381    +60+100+80+380  -50-30;//支付宝加微信加dps端收入
        int 净收入 = 毛收入 -245-20;//扣除服务器费用和会员费
        int 董收入= (int) (净收入*0.7);
        int 扣除dps端已经付给董的费用 = 董收入 -(60+100+80+380);
        int 最终结果 = 扣除dps端已经付给董的费用 - (1220 +100+ 3600 +95 +50); //1220为上月遗留  3600为贪玩账单  剩下的吃饭



        System.out.println(最终结果);



    }
}
