package common.utils.hyg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HygSDK {
    private final static String DOMAIN = System.getenv("HYG_DOMAIN");
    private final static String RSA_PRIVATE_KEY = System.getenv("HYG_RSA_PRIVATE_KEY");
    private final static String AES_KEY = System.getenv("HYG_AES_KEY");
    private final static String COOPERATOR_ID = System.getenv("HYG_COOPERATOR_ID");

    /**
     * 自由职业者信息详情查询接口
     * 接口地址: https://${domain}/api/v2/hire/worker/findDetails
     *
     * @param workerId 自由职业者ID
     * @return JSONObject 包含statusCode, statusText, data 等信息的响应
     * @throws Exception 如果请求或签名发生错误
     */
    public static JSONObject findWorkerDetails(String workerId) throws Exception {
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("workerId", workerId);

        return HygSDK.invokeApi("/api/v2/hire/worker/findDetails", bizParams);
    }
    
    public static JSONObject findDepositAccount() throws Exception {
        Map<String, Object> bizParams = new HashMap<>();

        List<String> cooperatorIdList = new ArrayList<>();
        cooperatorIdList.add(COOPERATOR_ID);
        bizParams.put("cooperatorIdList", cooperatorIdList);

        return HygSDK.invokeApi("/batch/query/cooperator/account", bizParams);
    }
    
    /**
     * 自由职业者放款接口
     *
     * @param workerId 自由职业者id
     * @param amount 放款金额（单位：分）
     * @param requestNo 放款订单号
     * @param positionId 任务ID，需要在慧用工后台申请
     * @return 放款结果
     * @throws Exception 放款异常捕获
     */
    public static JSONObject singleDistribute(String workerId, String amount, String requestNo, String positionId) throws Exception {
        // 先获取worker details
        JSONObject workerDetails = findWorkerDetails(workerId);
        // 先获取个体账户信息
        if (!workerDetails.getString("statusCode").equals("000000")) {
            workerDetails.put("statusText", "个体账户信息获取失败：" + workerDetails.getString("statusText") + ", workerId=" + workerId);

            return workerDetails;
        }
        
        // AppConfig.LOGGER.info("工人信息获取：{}", workerDetails.getString("statusText"));
        
        // 封装打款信息
        JSONObject workerData = workerDetails.getJSONObject("data");
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("workerName", workerData.getString("workerName"));
        bizParams.put("receiptChannel", 10);
        bizParams.put("workerAccount", workerData.getString("bankCardNo"));
        bizParams.put("workerType", 1);
        bizParams.put("idNumber", workerData.getString("identNo"));
        bizParams.put("workerMobile", workerData.getString("workerMobile"));
        bizParams.put("distributeAmount", amount);
        bizParams.put("requestNo", requestNo);
        bizParams.put("positionId", positionId);

        return HygSDK.invokeApi("/api/distribute/singleDistribute", bizParams);
    }

    /**
     * 放款状态查询
     * 
     * @param requestNo 放款订单号，由平台自己生成
     * @return 放款结果
     * @throws Exception  放款查询异常捕获
     */
    public static JSONObject signalQuery(String requestNo) throws Exception {
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("requestNo", requestNo);

        return HygSDK.invokeApi("/api/query/singleQuery", bizParams);
    }
    
    /**
     * 可以添加一个公共的请求方法，处理签名、加密、响应解析等通用逻辑
     * @param apiPath 例如 FIND_DETAILS_API
     * @param bizParams 业务参数，不包含cooperatorId, timestamp, sign
     * @return
     * @throws Exception
     */
    public static JSONObject invokeApi(String apiPath, Map<String, Object> bizParams) throws Exception {
        // 加载固定参数
        Map<String, Object> fullParams = new HashMap<>();
        fullParams.put("cooperatorId", COOPERATOR_ID);
        fullParams.putAll(bizParams); // 添加传入的业务参数

        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        fullParams.put("timestamp", timestamp);

        // 签名
        String sortedParamString = RSAUtils.sortParam(fullParams);
        String sign = RSAUtils.sign(sortedParamString.getBytes(StandardCharsets.UTF_8), RSA_PRIVATE_KEY);
        fullParams.put("sign", sign);

        // 构建请求 URL
        String requestUrl = DOMAIN + apiPath;
        
        // 构造最终请求
        Map<String, Object> finalParams = new HashMap<>();
        finalParams.put("cooperatorId", COOPERATOR_ID);
        String jsonStr = JSONObject.toJSONString(fullParams);
        finalParams.put("businessBody", AESUtils.encrypt2Hex(jsonStr, AES_KEY));

        // 请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        
        // 发送请求
        String postParams = JSON.toJSONString(finalParams);
        String responseBody = HttpKit.post(requestUrl, null, postParams, headers);

        if (StrKit.isBlank(responseBody)) {
            throw new RuntimeException("API响应为空");
        }
        
        // 解密返回值
        JSONObject responseJson = JSON.parseObject(responseBody);
        if (responseJson.getString("statusCode").equals("000000")) {
            String decodeRest = AESUtils.decryptByHex(responseJson.getString("data"));
            responseJson.put("data", JSONObject.parse(decodeRest));
        }
        
        return responseJson;
    }

    public static void main(String[] args) {
        try {
            // {"data":{"workerId":"W141720xxxx8","identNo":"51xxxx1xxxxx9012","signTime":"2025-09-15 17:36:50","bankCardNo":"6217003xxxxx1392931","workerCfcaSignFlag":true,"signDesc":"签约成功","remark":"","updateTime":"2025-09-16 03:15:00","signState":2,"receiptChannel":10,"createTime":"2025-09-15 17:36:50","workerMobile":"17781855864","verifiedStatus":2,"verifiedDesc":"认证成功","workerName":"龚成明","verifiedTime":"2025-09-15 17:36:17","certificateType":1},"statusText":"success","statusCode":"000000"}
            // {"statusText":"用户记录不存在","statusCode":"200406"}
            // AppConfig.LOGGER.info(HygSDK.findWorkerDetails("W1420857775537291264").toString());
            // {"data":[{"receiverAccountName":"九江慧用工科技有限公司","receiverBankBranchNo":"308100005192","cooperatorId":"C1415369626593792000","receiverBankBranchName":"招商银行股份有限公司北京东方广场支行","bankType":"商业银行","receiverAccountNo":"755915711210409","shortBankName":"招商银行","cooperatorName":"特别火（嵌入板）O"}],"statusText":"success","statusCode":"000000"}
            // AppConfig.LOGGER.info(HygSDK.findDepositAccount().toString());
            
            // 放款100分测试
            
            /*
             * 2025-09-26 14:39:50.604 [main] INFO  common.jfinal.AppConfig - order_sn = 17588690942918042
             * 2025-09-26 14:39:51.306 [main] INFO  common.jfinal.AppConfig - {"data":{"distributeId":"BL1421144242402639872","distributeAmount":"100"},"statusText":"success","statusCode":"000000"}
             */
            // String orderSn = OrderService.generateOrderSn();
            // AppConfig.LOGGER.info("order_sn = {}", orderSn);
            // AppConfig.LOGGER.info(HygSDK.singleDistribute("W1420857775537291264", "925", "DLTBH_WD_17588741472336835", "P1421138295391289344").toString());
            
            // 一次至少提现1000分
            // {"data":{"valueAddedTax":"0","distributeStatus":75,"incomeActualAmount":0,"constructionTax":"0","localEducationSupplementaryTax":"0","educationSurchargeTax":"0","remark":"计费标准超出范围","requestNo":"17588687904896652","individualIncomeTax":"0","incomeTaxAmount":0,"serviceCharge":"0","distributeId":"BL1421144242402639872","createTime":"2025-09-26 14:39:51","useCouponAmount":0,"distributeAmount":"100"},"statusText":"success","statusCode":"000000"}
            // {"data":{"valueAddedTax":"0","distributeStatus":60,"incomeActualAmount":1000,"constructionTax":"0","localEducationSupplementaryTax":"0","payTime":"2025-09-26 14:44:55","educationSurchargeTax":"0","remark":"","requestNo":"17588690942918042","individualIncomeTax":"0","incomeTaxAmount":0,"serviceCharge":"75","distributeId":"BL1421145516409892864","createTime":"2025-09-26 14:44:55","useCouponAmount":0,"bankSerialNo":"2011000420250926143698976426","distributeAmount":"1000"},"statusText":"success","statusCode":"000000"}
            // AppConfig.LOGGER.info(HygSDK.signalQuery("DLTBH_WD_17588746359625898").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
