package cn.qg.qaplatform.zdata.process;

import cn.qg.qaplatform.utils.DBUtils;
import cn.qg.qaplatform.utils.EncryptUtils;
import cn.qg.qaplatform.utils.HttpClientUtils;
import cn.qg.qaplatform.utils.JsonTransUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class Vcc {
    public static String readTxt(String file) throws IOException {
        String str = "";
        ClassPathResource resource = new ClassPathResource(file);
        InputStream in = resource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer content = new StringBuffer();
        while ((str=br.readLine()) != null) {
            content = content.append(str);
        }
        return content.toString();
    }

    /**
     * 标准登录
     *
     * @throws Exception
     */
    public static Map<String, String> login(String namespace, String phone, String channelId, String createdFrom) throws Exception {
        String url = "http://passportapi-" + namespace + ".liangkebang.net" + "/user/login/fastV1";
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> header = new HashMap<String, Object>();
        params.put("channelId", channelId);
        params.put("createdFrom", createdFrom);
        params.put("key", "xyqb");
        params.put("btRegisterChannelId", "");
        params.put("dimension", "");
        params.put("click_id", "");
        header.put("Content-Type", "application/x-www-form-urlencoded");
        String verification = EncryptUtils.base64Encrypt(phone);
        header.put("Authorization", verification);
        JSONObject result = HttpClientUtils.doPost(url, params, header);
        Map<String, String> map = (Map<String, String>) result.get("data");
        log.info("登录参数：" + params);
        log.info("登录结果：" + result);
        return map;
    }

    /**
     * 创建vcc用户
     */
    public static String creditUrl(String namespace, String token, String vccChannel) throws URISyntaxException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/credit_url";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        JSONObject result = HttpClientUtils.doGetReturnJson(url, null, headers);
        log.info("creaditUrl结果：" + result);
        Map<String, String> data = (Map) result.get("data");
        String returnUrl = data.get("url");
        String vccToken = returnUrl.split("=")[1];
        return vccToken;
    }

    /**
     * 身份证正面
     */
    public static void uploadFrontIdCard(String vccToken, String uuid, String vccChannel) throws IOException {
        String url = "https://operator.liangkebang.com/auth-center/h5/api/ocr/auth_sdk.json";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", vccToken);
        // 待参数化
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("clarity", 74);
        map.put("multiWarning", "00010010");
        map.put("birth", "19900104");
        map.put("nation", "汉");
        map.put("type", "xyqb");
        map.put("code", 0);
        map.put("isShootPagePortrait", true);
        map.put("address", "北京市海淀区码农村22号");
        map.put("idNo", "320101199001040432");
        map.put("orderNo", uuid.concat("1"));
        map.put("warning", "00010000");
        map.put("msg", "OCR获取成功");
        map.put("name", "张三");
        map.put("sex", "男");
        String frontBase64Str = Vcc.readTxt("front.txt");
        map.put("base64Str", frontBase64Str);
        params.put("idCard", JSON.toJSONString(map));
        JSONObject result = HttpClientUtils.doPost(url, params, headers);
        log.info("上传身份证正面结果：" + result);
    }

    /**
     * 身份证反面
     */
    public static void uploadBackIdCard(String vccToken, String uuid, String vccChannel) throws IOException{
        String url = "https://operator.liangkebang.com/auth-center/h5/api/ocr/auth_sdk.json";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", vccToken);
        // 待参数化
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("validDate", "20051008-20251008");
        map.put("authority", "上海市公安局徐汇分局");
        map.put("isShootPagePortrait", false);
        map.put("code", 0);
        map.put("orderNo", uuid.concat("2"));
        map.put("clarity", 60);
        map.put("msg", "OCR获取成功");
        map.put("type", "xyqb");
        map.put("warning", "00010000");
        map.put("multiWarning", "00010000");
        String backBase64Str = Vcc.readTxt("back.txt");
        map.put("base64Str", backBase64Str);
        params.put("idCard", JsonTransUtils.mapToJson(map));
        JSONObject result = HttpClientUtils.doPost(url, params, headers);
        log.info("上传身份证反面：" + result);
    }

    /**
     * 避免身份证重复，修改
     */
    public static void modifyExistIdNo(String namespace) throws SQLException {
        DBUtils dbUtils = new DBUtils(namespace, "acsdb", "qa", "qatest");
        String sql = "update acs_account set id_no='123456' where id_no= '320101199001040432'";
        int result = dbUtils.insert(sql);
    }

    /**
     * 保存用户信息
     */
    public static void saveUserDetails(String namespace, String token, String vccChannel) {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/account/save_user_details";
        Map<String, Object> headers = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        params.put("name", "张三");
        params.put("idNo", "320101199001040432");
        JSONObject result = HttpClientUtils.doPost(url, params, headers);
        log.info("保存用户信息：" + result);
    }

    /**
     * 提交ocr
     */
    public static void submitOcr(String vccToken, String vccChannel) {
        String url = "https://operator.liangkebang.com/auth-center/h5/api/ocr/submit.json";
        Map<String, Object> headers = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        headers.put("x-auth-token", vccToken);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        params.put("real_name", "张三");
        params.put("id_card_no", "320101199001040432");
        JSONObject result = HttpClientUtils.doPost(url, params, headers);
        log.info("提交OCR：" + result);
    }

    /**
     * 提交授信
     */
    public static void submitCredit(String namespace, String token, String vccChannel) {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/active_credit_limit";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        JSONObject result = HttpClientUtils.doPost(url, null, headers);
        log.info("提交授信：" + result);
    }

    /**
     * 授信结果查询
     */
    public static Map<String, Object> searchCreditResult(String namespace, String token, String vccChannel) throws URISyntaxException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/credit_info";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/x-www-form-urlencoded");
        JSONObject result = HttpClientUtils.doGetReturnJson(url, null, headers);
        log.info("授信结果查询：" + result);
        Map<String, Object> map = (Map<String, Object>) result.get("data");
        return map;
    }

    /**
     * 查询授信单号
     */
    public static String getRiskNo(String namespace, String uuid) throws SQLException {
        DBUtils dbUtils = new DBUtils(namespace, "vcc_talos", "qa", "qatest");
        String sql = "select risk_no from risk_record where uuid='" + uuid + "';";
        Map<String, String> map = dbUtils.queryForMap(sql);
        return map.get("risk_no");
    }

    /**
     * vcc风控授信回调
     */
    public static void vccWindControlCreditCallback(String namespace, String uuid, String riskNo, boolean auditResult) {
        String url = "https://talos-" + namespace + ".liangkebang.net/ex/vcc/risk/auth_amount_completion";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 15);
        long openingDeadLine = calendar.getTimeInMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("amount", 10000);
        params.put("auditResult", auditResult);
        params.put("bizChannel", 159904);
        params.put("bizNo", riskNo);
        params.put("code", 0);
        params.put("deadLine", "1640966399000");
        params.put("openingDeadLine", openingDeadLine); // 开户失败有效期
        params.put("success", true);
        params.put("uuid", uuid);
        params.put("sceneId", 0);
        params.put("allowInstalment", 1); // 1-允许分期，0-不允许分期
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        JSONObject result = HttpClientUtils.doPost(url, params, headers);
        log.info("vcc风控授信回调结果：" + result);
    }

    /**
     * 人脸识别回调
     */
    public static void appFaceCallback(String namespace, String token, String vccChannel) throws URISyntaxException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/app_face_callback";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        JSONObject result = HttpClientUtils.doGetReturnJson(url, null, headers);
        log.info("人脸face回调结果：" + result);
    }

    /**
     * 基本信息
     */
    public static void basicInfo(String namespace, String token, String vccChannel) throws JsonProcessingException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/base_info";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/json");
        Map<String, Object> map = new HashMap<>();
        map.put("provinceCode", "110000");
        map.put("province", "北京市");
        map.put("cityCode", "110100");
        map.put("city", "市辖区");
        map.put("districtCode", "110116");
        map.put("district", "怀柔区");
        map.put("address", "测试一下看看");
        map.put("firstName", "测试");
        map.put("firstMobile", "18300000000");
        map.put("firstRelation", "BROTHER");
        map.put("secondName", "测试");
        map.put("secondMobile", "18300000001");
        map.put("secondRelation", "BROTHER");
        map.put("vocation", "WHITE_COLLAR");
        map.put("salary", "BELOW_5000");
        map.put("education", "JUNIOR_COLLEGE");
        map.put("email", "123456@qq.com");
        String params = JsonTransUtils.mapToJson(map);
        JSONObject result = HttpClientUtils.doPostJson(url, params, headers);
        log.info("保存基本信息：" + result);
    }

    /**
     * 发送验证码
     */
    public static String bindCardSms(String namespace, String token, String vccChannel, String bankCode, String cardNo) throws JsonProcessingException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/bind_card_sms";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        headers.put("content-type", "application/json");
        Map<String, Object> map = new HashMap<>();
        map.put("bankCode", bankCode);
        map.put("cardNo", cardNo);
        map.put("preservePhoneNo", "18312345678");
        String params = JsonTransUtils.mapToJson(map);
        JSONObject result = HttpClientUtils.doPostJson(url, params, headers);
        log.info("发送验证码：" + result);
        Map data = (Map) result.get("data");
        String requestId = data.get("requestId").toString();
        return requestId;
    }

    /**
     * 额度激活
     */
    public static JSONObject quotaActivation(String namespace, String token, String vccChannel, String cardNo, String requestId) throws URISyntaxException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/bind_and_open";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        String params = "?cardNo=" + cardNo + "&validateCode=000000&requestId=" + requestId;
        JSONObject result = HttpClientUtils.doGetReturnJson(url + params, null, headers);
        log.info("额度激活结果：" + result);
        return result;
    }

    /**
     * 开户结果
     */
    public static JSONObject openResult(String namespace, String token, String vccChannel) throws URISyntaxException {
        String url = "https://talos-" + namespace + ".liangkebang.net/vcc/xyqb_mall/open_result";
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-auth-token", token);
        headers.put("vccchannel", vccChannel);
        JSONObject result = HttpClientUtils.doGetReturnJson(url, null, headers);
        log.info("开户结果：" + result);
        return result;
    }

    /**
     * 查询用户是否已有额度
     */
    public static boolean checkIfAlreadyHaveQuota(String namespace, String uuid) throws SQLException {
        DBUtils dbUtils = new DBUtils(namespace, "vcc_quota", "qa", "qatest");
        String sql = "select * from user_quota_record where uuid='" + uuid + "'";
        Map result = dbUtils.queryForMap(sql);
        if (result.isEmpty()) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> loginResult = login("vcc3", "18300000418", "214", "214");
        String uuid = loginResult.get("uuid");
        String riskNo = getRiskNo("vcc3", uuid);
        vccWindControlCreditCallback("vcc3", "1", riskNo, true);
    }
}
