package io.renren.application.common.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
public class ChaoXiangUtils {

    private static final String CODE_URL = "https://applet.diandian11.com/gwx/api-business/code?randomStr=";

    private static final String LOGIN_URL = "https://applet.diandian11.com/gwx/api-business/oauth/token?randomStr=RANDOM&code=CODE";

    private static final String SEND_INFO_URL = "https://applet.diandian11.com/gwx/api-business/tenant/coupon/web/quantityReceivedList?couponId=";

    private static final String USER_NAME = "admin";

    private static final String PASSWORD = "cdzcx0712";

    private static final String TOKEN_KEY = "authorization";

    private static final CX_Token cacheToken = new CX_Token();

    private static String getToken() throws IOException {
        if (cacheToken.getToken()!=null&&cacheToken.getExpireTime().isAfter(LocalDateTime.now())){
            return cacheToken.getToken();
        }
        return login();
    }

    public static Integer getStock(String id) throws IOException {

        OkHttpClient client = new OkHttpClient();
        String url = SEND_INFO_URL+id;
        log.info("url:{}",url);
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, "{\"loginName\":\"admin\",\"password\":\"cdzcx0712\",\"grantType\":\"password\",\"accountType\":0}");
        Request request = new Request.Builder()
                .url(url)
//                .post(body)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Encoding", "gzip, deflate, br, zstd")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Authorization", getToken())
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
//                .addHeader("Content-Length", "83")
//                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("DNT", "1")
                .addHeader("Host", "applet.diandian11.com")
                .addHeader("Origin", "http://manage.diandian11.com")
                .addHeader("Pragma", "no-cache")
                .addHeader("Referer", "http://manage.diandian11.com/")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Site", "cross-site")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
                .addHeader("dt", "0")
                .addHeader("region", "%E5%85%A8%E5%9B%BD,saas")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
//                .addHeader("content-type", "application/json")
                .build();
        Long start = System.currentTimeMillis();
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        log.info("查询库存信息结果:{}",result);
        Long cost = System.currentTimeMillis()-start;
        log.info("耗时：{}ms",cost);
        JSONArray array = JSONObject.parseObject(result).getJSONArray("data");
        if (array!=null&&!array.isEmpty()){
            Integer sum = array.getJSONObject(0).getInteger("ruleNumber");
            Integer send = array.getJSONObject(0).getInteger("receiveCount");
            return sum-send;
        }
        return 0;
    }

    public static String login() throws IOException {
        String randomStr = RandomUtil.randomString(4).toUpperCase();
        OkHttpClient client = new OkHttpClient();
        Request imageRequest = new Request.Builder()
                .url(CODE_URL+randomStr)
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("Accept-Encoding", "gzip, deflate, br, zstd")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
//                .addHeader("Authorization", "")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
//                .addHeader("Content-Length", "83")
//                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("DNT", "1")
                .addHeader("Host", "applet.diandian11.com")
                .addHeader("Origin", "http://manage.diandian11.com")
                .addHeader("Pragma", "no-cache")
                .addHeader("Referer", "http://manage.diandian11.com/")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Site", "cross-site")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
                .addHeader("dt", "0")
                .addHeader("region", "%E5%85%A8%E5%9B%BD,saas")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
//                .addHeader("content-type", "application/json")
                .build();

        Response response1 = client.newCall(imageRequest).execute();
        String base64 =
                Base64.encodeBase64String(IOUtils.toByteArray(response1.body().byteStream()));
        log.info("base64:{}",base64);
        base64 = URLEncoder.encode(base64, "utf-8");
        String code =  BaiduUtils.getImageTextBase64(base64);

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"loginName\":\"admin\",\"password\":\"cdzcx0712\",\"grantType\":\"password\",\"accountType\":0}");
        Request request = new Request.Builder()
                .url("https://applet.diandian11.com/gwx/api-business/oauth/token?randomStr="+randomStr+"&code="+code)
                .post(body)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Encoding", "gzip, deflate, br, zstd")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Authorization", "")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
                .addHeader("Content-Length", "83")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("DNT", "1")
                .addHeader("Host", "applet.diandian11.com")
                .addHeader("Origin", "http://manage.diandian11.com")
                .addHeader("Pragma", "no-cache")
                .addHeader("Referer", "http://manage.diandian11.com/")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Site", "cross-site")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
                .addHeader("dt", "0")
                .addHeader("region", "%E5%85%A8%E5%9B%BD,saas")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("content-type", "application/json")
                .build();

        Response response = client.newCall(request).execute();
        String token = JSONObject.parseObject(response.body().string()).getJSONObject("data").getString("accessToken");
        cacheToken.setToken(token);
        cacheToken.setExpireTime(LocalDateTime.now().plusMinutes(24));
        log.info("登入信息:{}",cacheToken);
        return token;
    }

    @Data
    public static class CX_Token{
        String token;
        LocalDateTime expireTime;
    }
}
