package cn.qg.qaplatform.test;

import cn.qg.qaplatform.process.Common;
import cn.qg.qaplatform.process.Xyqb;
import cn.qg.qaplatform.utils.DBUtils;
import cn.qg.qaplatform.encrypt.LexinEncrypt;
import cn.qg.qaplatform.utils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.DigestUtils;

import java.sql.SQLException;
import java.util.*;

public class Lexin {
    public static Random random = new Random();
    public static String MD5Keywy = "qEAxMJBv";
    public static String AESKeywy = "sxD8KO79EDK0N0AJ";
    public static String namespace = "pre";
    public static String phoneNo = "18995803991";
    public static String orderNo = "channel_order" + phoneNo + "_" + random.nextInt(9999);
    public static String userName = "陆康盛";
    public static String idCardNo = "530827197906309549";
    public static Integer amount = 10000;
    public static Integer term = 3;
    public static String rate = "31.86";
    public static String fixedBillDay = "2";
    public static String fixedRepayDay = "12";
    public static String bankCardNo = "6217003252470844018";
    public static String bankCode = "CCB";
    public static String bankName = "中国建设银行";

    /**
     * 进件
     */
    public static void createOrder() {
        String url = "http://qapi-" + namespace + ".liangkebang.net/ex/api/v2/applyLoan/LEXIN";
        Map<String, Object> bizData = new HashMap<>();
        bizData.put("orderNo", orderNo);
        bizData.put("userName", userName);
        bizData.put("idCardNo", idCardNo);
        bizData.put("phone", phoneNo);
        bizData.put("qq", "123456");
        bizData.put("email", "2222@qq.com");
        bizData.put("address", "北京");
        bizData.put("addressLocation", "浙江省绍兴市");
        bizData.put("addrDetail", "大鹿庄村1号");
        bizData.put("channelUserId", phoneNo);
        bizData.put("districtCode", "110101");
        bizData.put("workUnit", "北京市测试公司");
        bizData.put("industry", "TRAFFIC");
        bizData.put("loanDemandPurpose", "FURNITURE_HOME");
        List<Map> creditList = createCreditList();
        bizData.put("creditList", creditList);
        bizData.put("education", "MASTER");
        bizData.put("occupation", "UNEMPLOYED");
        bizData.put("income", "CASH_AND_PAY_CARD");
        bizData.put("incomeRange", "BELOW_3000");
        bizData.put("marryStatus", "MARRIED");
        bizData.put("hasCar", true);
        bizData.put("hasCreditCard", true);
        bizData.put("hasHouse", true);
        bizData.put("hasSocialSecurity", true);
        bizData.put("emergencyContactNameA", "测试联系人一");
        bizData.put("emergencyContactPhoneA", "18666666665");
        bizData.put("emergencyContactRelationA", "SPOUSE");
        bizData.put("emergencyContactNameB", "测试联系人二");
        bizData.put("emergencyContactPhoneB", "18066666666");
        bizData.put("emergencyContactRelationB", "FRIEND");
        Map<String, Object> authInfo = createAuthInfo();
        Map<String, Object> scenarioData = createScenarioData();
        Map<String, Object> orderInfoExtend = new HashMap<>();
        orderInfoExtend.put("creditContractTime", "2020-08-28 09:48:23");
        bizData.put("authInfo", authInfo);
        bizData.put("scenarioData", scenarioData);
        bizData.put("orderInfoExtend", orderInfoExtend);
        String bizDataStr = JSONObject.toJSONString(bizData);
        String signStr = DigestUtils.md5DigestAsHex((bizDataStr + MD5Keywy).getBytes());
        Map<String, Object> content = new HashMap<>();
        content.put("sign", signStr);
        content.put("bizData", bizDataStr);
        System.out.println("进件参数为：" + content);
        String contentStr = LexinEncrypt.encryptAndBase64Encode(JSONObject.toJSONString(content), AESKeywy);

        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        JSONObject result = HttpClientUtils.doPost(url, "content=" + contentStr);
        String response = LexinEncrypt.decryptAfterBase64Decode(result.get("content").toString(), AESKeywy);
        System.out.println(JSONObject.parseObject(response));
        System.out.println("乐信进件返回结果：" + result);

    }

    public static Map<String, Object> createAuthInfo() {
        Map<String, Object> authInfo = new HashMap<>();
        Map<String, Object> ocr = new HashMap<>();
        ocr.put("address", "浙江省绍兴市市辖区飞双村6号院57号楼2门509");
        ocr.put("agency", "绍兴市公安局");
        ocr.put("citizen_id", idCardNo);
        ocr.put("gender", "女");
        ocr.put("idCardBaseContentA", "OWJZWU81MkRmeTI1bCtGaGxFL3hBUndjb3I0MUQ0YzZVTEZwZkdRM1VRREFxUDJBR1RnZVdVa3lxRVFmRVpSTlZuUm5XZ3FjSUJ1VWFlTmV5cG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GxFL3hBUndjb3I0MUQ0YzZVTEZwZkdRM1VRREFxUDJBR1RnZVdVa3lxRVFmRVpSTlZuUm5XZ3FjSUJ1VWFlTmV5cGMvSW5meFRLR1cvUWNXRWZXejhSeDNCNWs9OWJZWU81MkRmeTI1bCtGaGxFL3hBUndjb3I0MUQ0YzZVTEZwZkdRM1VRREFxUDJBR1RnZVdVa3lxRVFmRVpSTlZuUm5XZ3FjSUJ1VWFlTmV5cGMvSW5meFRLR1cvUWNXRWZXejhSeDNCNWs9");
        ocr.put("name", userName);
        ocr.put("nation", "壮");
        ocr.put("picModel", "2");
        ocr.put("valid_date_begin", "20150908");
        ocr.put("valid_date_end", "20250908");
        ocr.put("liveType", "face");
        Map<String, Object> result_idcard_photo = new HashMap<>();
        result_idcard_photo.put("confidence", 82.584);
        Map<String, Double> thresholds = new HashMap<>();
        thresholds.put("1e-3", 62.169);
        thresholds.put("1e-5", 74.399);
        thresholds.put("1e-4", 69.315);
        thresholds.put("1e-6", 78.038);
        result_idcard_photo.put("thresholds", thresholds);
        ocr.put("result_idcard_photo", result_idcard_photo);
        authInfo.put("ocr", ocr);
        return authInfo;
    }

    public static Map<String, Object> createScenarioData() {
        Map<String, Object> scenarioData = new HashMap<>();
        Map<String, Object> auditInfo = new HashMap<>();
        Map<String, Object> extra = new HashMap<>();
        auditInfo.put("auditAmount", amount);
        auditInfo.put("auditTerm", term);
        auditInfo.put("rate", rate);
        auditInfo.put("fixedBillDay", fixedBillDay);
        auditInfo.put("fixedRepayDay", fixedRepayDay);
        extra.put("orderType", "取现");
        scenarioData.put("auditInfo", auditInfo);
        scenarioData.put("extra", extra);
        return scenarioData;
    }

    public static List createCreditList() {
        List<Map<String, String>> creditList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("name", "OCR");
        map.put("organization", "1");
        creditList.add(map);
        return creditList;
    }

    /**
     * 查询渠道订单号
     * @param namespace
     * @param phone
     * @param channel
     * @return
     * @throws SQLException
     */
    public static String queryChannelOrderNo(String namespace, String phone, Integer channel) throws SQLException {
        String userId = Xyqb.checkUserId(namespace, phone).get("id").toString();
        System.out.println("userId: " + userId);
        String sql = "SELECT channel_order_no FROM order_mapping WHERE qg_user_id=" + userId + " and registered_from=" + channel + " order by id desc limit 0,1";
        System.out.println(sql);
        DBUtils dbUtils = new DBUtils(namespace, "cash_loan_flow", "qa", "qatest");
        Map map = dbUtils.queryForMap(sql);
        return map.get("channel_order_no").toString();
    }

    public static void main(String[] args) throws Exception {
        String fundOpToken = Xyqb.loginFundOP(namespace);
        Xyqb.setFundPlan(namespace, 1010, fundOpToken);
        Xyqb.unblockLoan(namespace, 1010, fundOpToken);
        // 进件
        createOrder();
        String channelOrderNo = Common.queryChannelOrderNoByPhone(namespace, phoneNo, 159886);
        // 审批
        Common.channelOrderApprove(namespace, channelOrderNo, amount, "0", true, term);
        Thread.sleep(180000);
        // 提现
        Common.withDraw(namespace, "LEXIN", channelOrderNo, bankCardNo, bankCode, bankName, phoneNo);
        String token = Xyqb.login(namespace, 1, phoneNo);
        Map userInfoResult = Xyqb.checkUserId(namespace, phoneNo);
        String uuid = userInfoResult.get("uuid").toString();
        String userId = userInfoResult.get("id").toString();
        Integer loanId = Common.queryLoanId(namespace, phoneNo, 159886);
        // 二次风控
        boolean result = Xyqb.externalQuotaOrderAuditNotify(namespace, 1, token, uuid, loanId, 11, true);
        Thread.sleep(30000);
        Xyqb.modifyContactStatus(namespace, userId);
        // 放款
        String opToken = Xyqb.loginOP(namespace);
        // 查询待打款数量
        Map<String, Integer> peopleMap = Xyqb.checkWaitingFundingCorpOperatePeople(namespace, 1010);
        Integer money = peopleMap.get("money");
        Integer people = peopleMap.get("people");
        // 修改待放款用户创建时间
        Xyqb.modifyWaitingFundingCreatedAt(namespace, loanId);
        Thread.sleep(5000);
        // 直接打款
        Xyqb.fundsPlanLoanApply(namespace,opToken, 1010, money, people);
        Thread.sleep(30000);
        // 放款结果通知
        boolean makeLoanResult = Xyqb.payNotify(namespace, loanId, true);
    }
}
