package com.lakala.zf.laop.java.sdk.demo.utils;

import com.lakala.zf.laop.java.sdk.demo.BaseCommonDemo;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class V3LakalaBusinessUtils extends BaseCommonDemo {

    private static final String BASE_URL = "https://test.wsmsd.cn/sit";

    private static final String CLIENT_ID = "testsit";

    private static final String CLIENT_SECRET = "EguwEckByf2I6u6z";

    /**
     * 获取access_token
     * @return access_token响应
     */
    public static String getAccessToken() {
        try {
            OkHttpClient client = new OkHttpClient.Builder().build();
            // 构建请求参数
            FormBody formBody = new FormBody.Builder()
                .add("grant_type", "client_credentials")
                .add("client_id", CLIENT_ID)
                .add("client_secret", CLIENT_SECRET)
                .build();

            // 创建POST请求
            Request request = new Request.Builder()
                .url(BASE_URL+"/htkauth/oauth/token")
                .post(formBody)
                .build();

            // 执行请求
            Response response = client.newCall(request).execute();
            // 立即读取并使用响应体
            JSONObject jsonObject = new JSONObject(response.body().string());
            return jsonObject.getString("access_token");
        } catch (IOException e) {
            throw new RuntimeException("获取access_token失败", e);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 商户进件
     * @param entryInfo 进件信息
     * @return 进件结果
     */
    public static String merchantEntry(String entryInfo) {
        try {
            OkHttpClient client = new OkHttpClient.Builder().build();
            String accessToken = getAccessToken();

            RequestBody body = RequestBody.create(
                MediaType.parse("application/json"), entryInfo
            );

            Request request = new Request.Builder()
                .url(BASE_URL + "/htkregistration/merchant")
                .addHeader("Authorization", "Bearer " + accessToken)
                .post(body)
                .build();

            Response response = client.newCall(request).execute();
            JSONObject jsonObject = new JSONObject(response.body().string());
//            return jsonObject.getString("merchantNo");
            return jsonObject.toString();
        } catch (IOException | JSONException e) {
            throw new RuntimeException("商户进件失败", e);
        }
    }

    /**
     * 获取地区信息
     * @param parentCode 父级编码，如果获取省份信息则传空
     * @return 地区信息列表
     */
    public static JSONArray getRegionInfo(String parentCode) {
        try {
            OkHttpClient client = new OkHttpClient.Builder().build();
            String accessToken = getAccessToken();

            HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/htkregistration/organization").newBuilder();
            if (parentCode != null && !parentCode.isEmpty()) {
                urlBuilder.addPathSegment(parentCode);
            }
            Request request = new Request.Builder()
                .url(urlBuilder.build())
                .addHeader("Authorization", "Bearer" + accessToken)
                .get()
                .build();

            Response response = client.newCall(request).execute();

            if (!response.isSuccessful()) {
                throw new RuntimeException("获取地区信息失败, HTTP 状态码: " + response.code());
            }

            String responseBody = response.body().string();
            // 将响应字符串转换为 JSONArray
            JSONArray jsonArray = new JSONArray(responseBody);

            // 遍历 JSONArray 中的每个 JSONObject
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 处理每个 JSONObject 的逻辑
                int id = jsonObject.getInt("id");
                String createTime = jsonObject.getString("createTime");
                int optimistic = jsonObject.getInt("optimistic");
                String updateTime = jsonObject.isNull("updateTime") ? null : jsonObject.getString("updateTime");
                String code = jsonObject.getString("code");
                String name = jsonObject.getString("name");
                String parentCode1 = jsonObject.getString("parentCode");
                // 打印或进一步处理这些字段
                System.out.println("ID: " + id + ", Name: " + name + ", Code: " + code);
            }
            return jsonArray;
        } catch (IOException e) {
            throw new RuntimeException("获取地区信息失败", e);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        /*String accessToken = getAccessToken();
        System.out.println(accessToken);*/
        String entryResult = """
        {
            "accountName": "**",
            "accountNo": "621****06879",
            "accountType": "58",
            "attchments": [
                {
                    "id": "merchant/null/20220928161350755217AGREE_MENT.jpg",
                    "type": "AGREE_MENT"
                },
                {
                    "id": "merchant/null/20220928161347099171BANK_CARD.jpg",
                    "type": "BANK_CARD"
                },
                {
                    "id": "merchant/null/20220928161349793759OTHERS.jpg",
                    "type": "OTHERS"
                },
                {
                    "id": "merchant/null/20220928161346380779ID_CARD_FRONT.jpg",
                    "type": "ID_CARD_FRONT"
                },
                {
                    "id": "merchant/null/20220928161346680398ID_CARD_BEHIND.jpg",
                    "type": "ID_CARD_BEHIND"
                },
                {
                    "id": "merchant/null/20220928161347597952SHOP_OUTSIDE_IMG.jpg",
                    "type": "SHOP_OUTSIDE_IMG"
                },
                {
                    "id": "merchant/null/20220928161348568691SHOP_INSIDE_IMG.jpg",
                    "type": "SHOP_INSIDE_IMG"
                }
            ],
            "bizContent": {
                "activityId": 12,
                "fees": [
                    {
                        "feeCode": "WECHAT",
                        "feeValue": 0.38
                    },
                    {
                        "feeCode": "ALIPAY",
                        "feeValue": 0.38
                    },
                    {
                        "feeCode": "CREDIT_CARD",
                        "feeValue": 0.6
                    },
                    {
                        "feeCode": "DEBIT_CARD",
                        "feeValue": 0.5,
                        "topFee": 20
                    }
                ],
                "mcc": "12002",
                "termNum": "1"
            },
            "busiCode": "PAPER_CODE",
            "businessContent": "",
            "cityCode": "6410",
            "clearingBankCode": "102100099996",
            "contactMobile": "18208910781",
            "contactName": "**",
            "countyCode": "986410",
            "email": "***@qq.com",
            "larIdCard": "460027200111297612",
            "larIdCardEnd": "2030-05-20",
            "larIdCardStart": "2020-05-20",
            "larIdType": "01",
            "larName": "**",
            "latitude": "117.359967",
            "merAddr": "383",
            "merName": "24",
            "merRegName": "合肥集材社",
            "merType": "TP_PERSONAL",
            "openningBankCode": "102641000266",
            "openningBankName": "1111",
            "settleProvinceCode": "11",
            "settleProvinceName": "",
            "settleCityCode": "1000",
            "settleCityName": "",
            "provinceCode": "6400",
            "settleType": "D1",
            "source": "APP",
            "userNo": 20000101
        }
        """;

         String result = merchantEntry(entryResult);
        System.out.println(result);

        // 获取省份列表
//        getRegionInfo("1");


    }

}
