package cn.qg.qaplatform.process;

import cn.qg.qaplatform.config.WebSocketServer;
import cn.qg.qaplatform.utils.DBUtils;
import cn.qg.qaplatform.utils.Encrypt.LexinEncrypt;
import cn.qg.qaplatform.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

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

@Slf4j
public class Common {

    public static String MD5Keywy = "qEAxMJBv";
    public static String AESKeywy = "sxD8KO79EDK0N0AJ";
    public static String symbol = null;

    /**
     * 登录KA联调平台
     */
    public static String loginKA(String namespace) {
        String url = "http://boss-" + namespace + ".liangkebang.net/login";
        Map<String, Object> params = new HashMap<>();
        params.put("username", "wenhaiyuan");
        params.put("password", "123");
        String jsonParams = JSON.toJSONString(params);
        JSONObject result = HttpClientUtils.doPostJson(url, jsonParams);
        System.out.println(result);
        return result.get("data").toString();
    }

    /**
     * 渠道订单审核通过
     */
    public static boolean channelOrderApprove(String namespace, String orderNo, Integer amount, String fundType, boolean isPass, Integer term) {
        String token = loginKA(namespace);
        String url = "http://boss-" + namespace + ".liangkebang.net/order/approve";
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("boss-token", token);
        params.put("amount", amount.toString());
        params.put("channelOrderNumber", orderNo);
        params.put("fundType", fundType);
        params.put("isPass", isPass);
        params.put("period", term);
        String jsonParams = JSON.toJSONString(params);
        JSONObject result = HttpClientUtils.doPostJson(url, jsonParams, headers);
        System.out.println(result);
        return (boolean) result.get("data");
    }

    /**
     * 提现
     */
    public static boolean withDraw(String namespace, String channelCode, String channelOrderNumber, String bankCardNumber, String bankCode, String bankName, String reservePhoneNumber) {
        String url = "http://qapi-" + namespace + ".liangkebang.net/ex/api/v2/withdraw/" + channelCode;
        Map<String, Object> bizData = new HashMap<>();
        bizData.put("channelOrderNumber", channelOrderNumber);
        bizData.put("bankCardNumber", bankCardNumber);
        bizData.put("bankCode", bankCode);
        bizData.put("bankName", bankName);
        bizData.put("reservePhoneNumber", reservePhoneNumber);
        String bizDataStr = JSONObject.toJSONString(bizData);
        String signStr = DigestUtils.md5DigestAsHex((bizDataStr + MD5Keywy).getBytes()).toLowerCase();
        Map<String, String> content = new HashMap<>();
        content.put("sign", signStr);
        content.put("bizData", bizDataStr);
        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);
        if (!StringUtils.isEmpty(symbol)) {
            WebSocketServer.sendInfo("提现参数为：" + content, symbol);
            WebSocketServer.sendInfo("提现结果为：" + result, symbol);
        }
        log.info("提现后结果为：" + result);
        return true;
    }

    /**
     * 查询渠道订单号
     */
    public static String queryChannelOrderNoByPhone(String namespace, String phoneNo, Integer channel) throws SQLException {
        String userId = Xyqb.checkUserId(namespace, phoneNo).get("id").toString();
        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";
        DBUtils dbUtils = new DBUtils(namespace, "cash_loan_flow", "qa", "qatest");
        Map map = dbUtils.queryForMap(sql);
        String channelOrderNo =  map.get("channel_order_no").toString();
        if (!StringUtils.isEmpty(symbol)) {
            WebSocketServer.sendInfo("查询到的订单号为：" + channelOrderNo, symbol);
        }
        log.info("{}查询到的渠道订单号为：{}", phoneNo, channelOrderNo);
        return channelOrderNo;
    }

    /**
     * 查询loanId
     */
    public static Integer queryLoanId(String namespace, String phoneNo, Integer channel) throws SQLException {
        String userId = Xyqb.checkUserId(namespace, phoneNo).get("id").toString();
        String sql = "SELECT id FROM loan_application_history WHERE user_id=" + userId + " order by id desc limit 0,1";
        DBUtils dbUtils = new DBUtils(namespace, "xyqb", "qa", "qatest");
        Map map = dbUtils.queryForMap(sql);
        String loanId = map.get("id").toString();
        if (!StringUtils.isEmpty(symbol)) {
            WebSocketServer.sendInfo("查询到的loanId为：" + loanId, symbol);
        }
        log.info("{}查询到的loanId为：{}", phoneNo, loanId);
        return Integer.parseInt(loanId);
    }

    public static boolean assignFundCorp(String namespace, Integer fundId) {
        // 登录资金方OP
        String fundOpToken = Xyqb.loginFundOP(namespace);
        boolean isAleadyAssign = false;
        // 检查是否已分配资产计划
        try {
            isAleadyAssign = Xyqb.assignFundOrNot(namespace, fundId, fundOpToken);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        boolean assignResult = false;
        boolean unblockResult = false;
        // 如果未分配
        if (!isAleadyAssign) {
            // 分配资产计划
            assignResult = Xyqb.setFundPlan(namespace, fundId, fundOpToken);
            // 打开推送放款
            unblockResult = Xyqb.unblockLoan(namespace, fundId, fundOpToken);
            if (assignResult && unblockResult) {
                return true;
            }
            return false;
        } else {
            return true;
        }
    }
}
