package com.malk.siku.utils;

import com.alibaba.fastjson.JSONObject;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

/**
 * 每刻报销
 */
@Slf4j
public class MkBxUtil {
    //测试环境
    /*private final static String appCode = "AP52Y01LHHTAP9";
    private final static String appSecret = "N4WuERLteAUPaWebnsHy";
    private final static String host = "ng.maycur.com";*/

    //生产环境
    private final static String appCode = "AP52RG1SCG8S6L";
    private final static String appSecret = "YFTbD2MviqUwztBTbMWd";
    private final static String host = "ng.maycur.com";

    private final Object $lock = new Object[0];

    private static final Long EXPIRES_IN = 1800000L;

    public static Map initTokenHeader(){

            Map header = new HashMap();

            String tokenId = UtilToken.get("invalid-tokenId-mkbx");
            String entCode = UtilToken.get("invalid-entCode-mkbx");

            if (StringUtils.isNotBlank(tokenId) && StringUtils.isNotBlank(entCode)) {
                header.put("tokenId",tokenId);
                header.put("entCode",entCode);

                return header;
            } else {
                //每刻登录认证
                Map body = new HashMap();

                long timeMillis = System.currentTimeMillis();
                body.put("appCode",appCode);
                body.put("secret",getSecret(appCode,appSecret,timeMillis));
                body.put("timestamp",timeMillis);

                Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/auth/login", null, null, body));

                Map data = UtilMap.getMap(result, "data");

                tokenId = UtilMap.getString(data, "tokenId");
                entCode = UtilMap.getString(data, "entCode");

                log.info("每刻报销tokenId, {}", tokenId);
                log.info("每刻报销entCode, {}", entCode);

                UtilToken.put("invalid-tokenId-mkbx", tokenId, EXPIRES_IN);
                UtilToken.put("invalid-entCode-mkbx", entCode, EXPIRES_IN);

                header.put("tokenId",tokenId);
                header.put("entCode",entCode);

                return header;
            }

    }

    public static Map initTokenHeader(String thisAppCode,String thisAppSecret){

        Map header = new HashMap();

        String tokenId = UtilToken.get("invalid-tokenId-mkbx");
        String entCode = UtilToken.get("invalid-entCode-mkbx");

        if (StringUtils.isNotBlank(tokenId) && StringUtils.isNotBlank(entCode)) {
            header.put("tokenId",tokenId);
            header.put("entCode",entCode);

            return header;
        } else {
            //每刻登录认证
            Map body = new HashMap();

            long timeMillis = System.currentTimeMillis();
            body.put("appCode",thisAppCode);
            body.put("secret",getSecret(thisAppCode,thisAppSecret,timeMillis));
            body.put("timestamp",timeMillis);

            Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/auth/login", null, null, body));

            Map data = UtilMap.getMap(result, "data");

            tokenId = UtilMap.getString(data, "tokenId");
            entCode = UtilMap.getString(data, "entCode");

            log.info("每刻报销tokenId, {}", tokenId);
            log.info("每刻报销entCode, {}", entCode);

            UtilToken.put("invalid-tokenId-mkbx", tokenId, EXPIRES_IN);
            UtilToken.put("invalid-entCode-mkbx", entCode, EXPIRES_IN);

            header.put("tokenId",tokenId);
            header.put("entCode",entCode);

            return header;
        }

    }

    //保存往来单位
    public static Map saveTradingPartner(Object body){
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/tradingPartner/batch/save", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        return result;
    }

    //保存往来单位账号
    public static Map saveAccount(Object body){
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/tradingPartner/batch/account/save", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        return result;
    }

    //报销单导入
    public static Map receiveReimburse(Object body){
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/receive/reimburse", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        return result;
    }

    //报销单费用导入
    public static List<String> receiveExpense(Object body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/receive/expense", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        String code = UtilMap.getString(result, "code");
        if ("NACK".equals(code)){
            String message = UtilMap.getString(result, "message");

            throw new RuntimeException(message);
        }

        Map data = UtilMap.getMap(result, "data");

        List<String> expenseCodes = new ArrayList<>();

        List<Map> successData = UtilMap.getList(data, "successData");

        for (Map successDatum : successData) {
            expenseCodes.add(UtilMap.getString(successDatum,"expenseCode"));
        }

        return expenseCodes;
    }

    //还款单写入接口
    public static Map receiveRepayment(Object body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/receive/repayment", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        return result;
    }

    //费用类型查询
    public static String expenseTypeSearch(Object body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/expense/type/search", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        List<Map> data = UtilMap.getList(result, "data");

        if (!data.isEmpty()){
            String bizCode = UtilMap.getString(data.get(0), "bizCode");

            return bizCode;
        }else {
            return null;
        }
    }

    //根据工号查询员工详情
    public static Map employeeDetails(Object body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/employee/details", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        List<Map> data = UtilMap.getList(result, "data");

        if (Objects.nonNull(data)){
            return data.get(0);
        }else {
            return null;
        }
    }

    //预算信息查询接口
    public static List<Map> budgetInfo(Object body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/budget/page", MkBxUtil.initTokenHeader(), null, body,(Map) null));

        log.info("Result:{}",result);

        Map data = UtilMap.getMap(result, "data");

        if (Objects.nonNull(data)){
            List<Map> list = UtilMap.getList(data, "list");

            return list;
        }else {
            return null;
        }
    }

    //批量编制预算额
    public static Map batchBudget(Map body){
        log.info("body:{}",JSONObject.toJSONString(body));
        Map result = (Map) JSONObject.parse(UtilHttp.doPut("https://" + host + "/api/openapi/budget/unit/batch/limit", MkBxUtil.initTokenHeader(), null, body));

        log.info("Result:{}",result);

        return result;
    }

    //付款单详情
    public static Map paymentDetailInfo(String formCode){
        Map result = (Map) JSONObject.parse(UtilHttp.doGet("https://" + host + "/api/openapi/payment/detailInfo/" + formCode, MkBxUtil.initTokenHeader(), (Map) null));

        log.info("Result:{}",result);

        Map data = UtilMap.getMap(result, "data");

        return data;
    }

    //报销单详情
    public static Map reimburseDetailInfo(String formCode){
        Map result = (Map) JSONObject.parse(UtilHttp.doGet("https://" + host + "/api/openapi/form/reimburse/" + formCode, MkBxUtil.initTokenHeader(), (Map) null));

        log.info("Result:{}",result);

        Map data = UtilMap.getMap(result, "data");

        return data;
    }

    //还款单详情
    public static Map repayDetailInfo(String formCode){
        Map result = (Map) JSONObject.parse(UtilHttp.doGet("https://" + host + "/api/openapi/form/repayment/" + formCode, MkBxUtil.initTokenHeader(), (Map) null));

        log.info("Result:{}",result);

        Map data = UtilMap.getMap(result, "data");

        return data;
    }

    //借款单详情
    public static Map loanDetailInfo(String formCode){
        Map result = (Map) JSONObject.parse(UtilHttp.doGet("https://" + host + "/api/openapi/form/loan/" + formCode, MkBxUtil.initTokenHeader("AP52RG1SCG8S6L","YFTbD2MviqUwztBTbMWd"), (Map) null));

        log.info("Result:{}",result);

        Map data = UtilMap.getMap(result, "data");

        return data;
    }

    //借款单台账列表
    public static List<Map> loanManageList(){
        Boolean hasNextPage = false;

        List<Map> totalList = new ArrayList<>();
        int i = 1;
        do {
            Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/api/openapi/form/loan/manage", MkBxUtil.initTokenHeader("AP52RG1SCG8S6L","YFTbD2MviqUwztBTbMWd"),null, UtilMap.map("pageNo, pageSize",i,100)));

            log.info("Result:{}",result);

            Map data = UtilMap.getMap(result, "data");

            List<Map> list = UtilMap.getList(data, "list");

            totalList.addAll(list);

            hasNextPage = UtilMap.getBoolean(data, "hasNextPage");

            i++;
        }while (hasNextPage);

        return totalList;
    }

    private static String getSecret(String appCode, String appSecret, long timeMillis){
        log.info("time：{}",timeMillis);

        String s = DigestUtils.sha256Hex(appSecret + ":" + appCode + ":" + timeMillis);
        log.info("s:{}",s);

        return s;
    }


}
