package com.kym.huapiaoer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.kym.huapiaoer.model.request.*;
import com.kym.huapiaoer.model.response.*;
import okhttp3.*;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class HuapiaoerClient {

    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    private final HuapiaoerConfig config;
    private final OkHttpClient httpClient;

    public HuapiaoerClient(HuapiaoerConfig config) {
        this.config = config;
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    // ==================== 3.1 查询开票人列表 ====================

    public List<DrawerInfo> getDrawerIdList(String nsrsbh) {
        JSONObject body = new JSONObject();
        body.put("nsrsbh", nsrsbh);
        body.put("appsecret", config.getAppSecret());
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/getDrawerIdList", body);
        return parseStandardResponse(json, new TypeReference<List<DrawerInfo>>() {}.getType());
    }

    // ==================== 3.2 授权订单号 ====================

    public AuthorizeOrderResponse getAuthorizeOrderId(AuthorizeOrderRequest request) {
        JSONObject body = buildBody(request);
        String json = post("/ewy_weberp/api/wechatPay/getWechatShopAuthorizeOrderId", body);
        return JSONObject.parseObject(json, AuthorizeOrderResponse.class);
    }

    // ==================== 3.3 发票开具 ====================

    public OpenInvoiceResponse openBlueInvoice(OpenBlueInvoiceRequest request) {
        JSONObject body = buildBody(request);
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/openBlueInvoice", body);
        return JSONObject.parseObject(json, OpenInvoiceResponse.class);
    }

    // ==================== 3.4 发票红冲 ====================

    public HuapiaoerResponse<String> openRedInvoice(String orderId) {
        JSONObject body = new JSONObject();
        body.put("orderId", orderId);
        body.put("appsecret", config.getAppSecret());
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/openRedInvoice", body);
        return JSONObject.parseObject(json, new TypeReference<HuapiaoerResponse<String>>() {});
    }

    // ==================== 3.5 发票通知、查询 ====================

    public InvoiceInfo getInvoice(String orderId, int invoicetype) {
        JSONObject body = new JSONObject();
        body.put("orderId", orderId);
        body.put("invoicetype", invoicetype);
        body.put("appsecret", config.getAppSecret());
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/getInvoice", body);
        return parseStandardResponse(json, InvoiceInfo.class);
    }

    // ==================== 3.6 发送邮件 ====================

    public HuapiaoerResponse<String> sendMail(String orderId, int invoiceType, String email) {
        JSONObject body = new JSONObject();
        body.put("orderId", orderId);
        body.put("invoiceType", invoiceType);
        body.put("email", email);
        body.put("appsecret", config.getAppSecret());
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/sendMail", body);
        return JSONObject.parseObject(json, new TypeReference<HuapiaoerResponse<String>>() {});
    }

    // ==================== 3.7 生成开票二维码 ====================

    public HuapiaoerResponse<QrcodeResponse> getInvoiceQrcode(InvoiceQrcodeRequest request) {
        JSONObject body = buildBody(request);
        String json = post("/ewy_weberp/api/huapiaoer/outopenapis/getInvoiceQrcode", body);
        return JSONObject.parseObject(json, new TypeReference<HuapiaoerResponse<QrcodeResponse>>() {});
    }

    // ==================== 4.1 企业搜索 ====================

    public List<EnterpriseInfo> searchEnterprise(String enterpriseName) {
        JSONObject body = new JSONObject();
        body.put("enterpriseName", enterpriseName);
        body.put("appsecret", config.getAppSecret());
        String json = post("/ewy_weberp/api/piaotong/platform/getInvoiceHeaderInquiry", body);
        return parseStandardResponse(json, new TypeReference<List<EnterpriseInfo>>() {}.getType());
    }

    // ==================== 内部方法 ====================

    private String post(String path, JSONObject body) {
        String url = config.getBaseUrl() + path;
        RequestBody requestBody = RequestBody.create(body.toJSONString(), JSON_MEDIA_TYPE);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new HuapiaoerException(String.valueOf(response.code()), "HTTP " + response.code());
            }
            return response.body() != null ? response.body().string() : "";
        } catch (IOException e) {
            throw new HuapiaoerException("500", "网络请求异常: " + e.getMessage());
        }
    }

    private JSONObject buildBody(Object request) {
        JSONObject body = (JSONObject) JSON.toJSON(request);
        body.put("appsecret", config.getAppSecret());
        return body;
    }

    @SuppressWarnings("unchecked")
    private <T> T parseStandardResponse(String responseBody, Type dataType) {
        JSONObject json = JSONObject.parseObject(responseBody);
        String code = json.getString("code");
        if (!"200".equals(code)) {
            String msg = json.getString("data");
            throw new HuapiaoerException(code, msg != null ? msg : "请求失败");
        }
        return (T) json.getObject("data", dataType);
    }
}
