package com.microservices.dms.achievementLibrary.service;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.httpClient.service.HttpAPIService;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.dms.achievementLibrary.domain.Achievements;
import com.microservices.dms.achievementLibrary.domain.BlockchainListQueryVo;
import com.microservices.dms.achievementLibrary.domain.KeyValueVo;
import com.microservices.dms.achievementLibrary.domain.TokenListVo;
import com.microservices.dms.achievementLibrary.domain.blockchain.InBlockchainData;
import com.microservices.dms.achievementLibrary.domain.blockchain.InLinkProjectVo;
import com.microservices.dms.achievementLibrary.domain.blockchain.UserProjectTransferRecords;
import com.microservices.dms.achievementLibrary.domain.blockchain.UserVo;
import com.microservices.dms.achievementLibrary.mapper.InBlockchainDataMapper;
import com.microservices.dms.achievementLibrary.mapper.UserProjectTransferRecordsMapper;
import com.microservices.dms.behaviorImage.domain.AchievementImageVo;
import com.microservices.dms.common.vo.*;
import com.microservices.dms.referral.mapper.TalentReferralMapper;
import com.microservices.dms.resourceLibrary.mapper.ProjectResourceLibraryMapper;
import com.microservices.dms.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
//import org.fisco.bcos.sdk.client.Client;
//import org.fisco.bcos.sdk.client.protocol.request.Transaction;
//import org.fisco.bcos.sdk.client.protocol.response.BcosTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.microservices.common.core.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.microservices.dms.constant.BlockChainFunConstants.*;
import static com.microservices.dms.utils.DateUtil.formatLocalDateTimePlusH;

@Service
@Slf4j
public class BlockChainService {


    @Autowired
    private ProjectResourceLibraryMapper projectResourceLibraryMapper;

    @Value("${gitlink.fiscobcosUrl:localhost}")
    public String fiscobcosUrl;

    @Autowired
    private HttpAPIService httpAPIService;

    @Autowired
    private InBlockchainDataMapper inBlockchainDataMapper;

    @Autowired
    private UserProjectTransferRecordsMapper userProjectTransferRecordsMapper;

    @Autowired
    private TalentReferralMapper talentReferralMapper;

    public List<TokenListVo> projectTokenList(String projectName) {
        List<TokenListVo> list = projectResourceLibraryMapper.selectProjectInfos(projectName);
        for (TokenListVo v : list) {
            JSONObject param = queryProjectInfo(v);
            if(param != null) {
                Long issueTokenSum = projectResourceLibraryMapper.sumProjectIssueToken(v.getId());
                v.setIssueToken(issueTokenSum);
                long totalToken = Long.parseLong(param.getString("total_supply"));//总token
                v.setTotalToken(totalToken);
                //根据创建人login，获取对应的用户id
                String userName = v.getUserId();
                //根据创建人、项目Id,获取创建人拥有token
                String tokenName  = param.getString("token_name");
                Long applyToken= getUserBlanaceProjectId("userSingleInfo",userName,tokenName);
                v.setApplyToken(applyToken);
                v.setCurrentToken(totalToken - applyToken);
            }
            v.setCreatedOn(DateUtil.plusHours(v.getCreatedOn(), 8));
        }
        return list;
    }

    public Long getUserBlanaceProjectId(String type,String userName,String tokenName) {
        JSONObject params = new JSONObject();
        if(type.equals(USER_SINGLE_INFO)){
            params.put(REQUEST_TYPE, USER_SINGLE_REPO);
            params.put("token_name", tokenName);
            params.put("username", userName);
        }else if(type.equals(USER_ALL_INFO)){
            params.put(REQUEST_TYPE, USER_ALL_REPOS);
            params.put("username", userName);
        }
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            return Long.parseLong(rsp.getString("balance"));
        }
        return -1L;
    }

    private JSONObject queryProjectInfo(TokenListVo v) {
        JSONObject param = new JSONObject();
        param.put(REQUEST_TYPE, QUERY_REPO);
        param.put("token_name", String.valueOf(v.getId()));

        JSONObject jsonObject = queryFiscobcos(param);
        if (jsonObject != null) {
            return jsonObject;
        }
        return null;
    }

    private JSONObject queryFiscobcos(JSONObject param) {
        try {
//            Map<String,String> p = convertParams(param);
//            JSONObject from = JSONObject.from(p);
            JSONObject reps = httpAPIService.doPost(fiscobcosUrl, param);
//            if (result.getCode() != 200) {
//                return null;
//            }
//            JSONObject reps = JSONObject.parseObject(result.getContent());
            if (reps.containsKey(RESP_STATUS) && reps.getString(RESP_STATUS).equals("0")) {
                return reps;
            }
        } catch (Exception e) {
            log.error("区块链接口请求失败", e);
            return null;
        }
        return null;
    }

    private Map<String, String> convertParams(JSONObject param) {
        Set<String> keys = param.keySet();
        Map<String, String> r = new HashMap<>();
        // 遍历 key 集合并获取对应的 value
        for (String key : keys) {
            Object o = param.get(key);
            if (o != null) {
                if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof BigDecimal || o instanceof Double) {
                    r.put(key, param.getString(key));
                } else if (o instanceof LocalDateTime) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String format = formatter.format(LocalDateTime.parse(o.toString(), formatter));
                    r.put(key, format);
                } else if (o instanceof Date) {
                    String s = DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, (Date) o);
                    r.put(key, s);
                } else if (o instanceof List || o instanceof Map) {
                    String jsonString = JSONObject.toJSONString(o);
                    r.put(key, jsonString);
                }else {
                    r.put(key, o.toString());
                }
            }else {
                r.put(key, null);
            }

        }
        return r;
    }

    public AjaxResult projectTokenDistribute(InLinkProjectVo vo) {
        //根据项目ID，获取用户ID
        //根据项目id获取项目创建人
        String userId = projectResourceLibraryMapper.getProjectUserIdById(vo.getProjectId());
        validTokenCount(vo.getProjectId(), vo.getAmount(),userId);
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, TRANSFER_AMOUNT);
        params.put("token_name", vo.getProjectId());
        params.put("amount", vo.getAmount());
        params.put("payee", vo.getUserId());
        params.put("payer", userId);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            String txHash = rsp.getString(TX_HASH);
            // insert to db 4、将3入链成功的数据存入表 ：用户/项目转账信息记录表 （type:project、 payer_id：username)
            if (StringUtils.isNotEmpty(txHash)) {
                UserProjectTransferRecords records = new UserProjectTransferRecords();
                records.setPayerId(params.getString("payer"));//转账人
                records.setPayeeId(params.getString("payee"));//收款人
                records.setProjectId(vo.getProjectId());
                records.setToken(BigDecimal.valueOf(vo.getAmount()));
                records.setType("projectApply");//项目分配
                records.setCreateTime(DateUtils.getNowDate());
                records.setTxHash(txHash);
                records.setCreateBy(SecurityUtils.getUsername());
                userProjectTransferRecordsMapper.insertUserProjectTransferRecords(records);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    public AjaxResult userCreate(UserCreateVo userCreateVo) {
        //根据项目id获取项目创建人
        String userId = projectResourceLibraryMapper.getUserIdBYLogin(userCreateVo.getPayee());//收款人ID
        userCreateVo.setPayee(userId);
        String payerId = projectResourceLibraryMapper.getUserIdBYLogin(userCreateVo.getPayer());//转账人ID
        userCreateVo.setPayer(payerId);
        //转账人token充足
         validUserTokenCount(userCreateVo);
        //进行转账
        JSONObject params = JSONObject.from(userCreateVo);
        params.put(REQUEST_TYPE, TRANSFER_AMOUNT);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            String txHash = rsp.getString(TX_HASH);
            // insert to db 将2入链成功的数据新增到用户/项目转账信息记录表 （type:user payer_id：payer)
            if (StringUtils.isNotEmpty(txHash)) {
                UserProjectTransferRecords records = new UserProjectTransferRecords();
                records.setPayerId(params.getString("payer"));
                records.setPayeeId(params.getString("payee"));
                records.setProjectId(params.getString("token_name"));
                records.setToken(params.getBigDecimal("amount"));
                records.setType("userTransfer");//用户转账
                records.setTxHash(txHash);
                records.setCreateTime(DateUtils.getNowDate());
                records.setCreateBy(SecurityUtils.getUsername());
                userProjectTransferRecordsMapper.insertUserProjectTransferRecords(records);
                return AjaxResult.success(rsp);
            }
        }
        return AjaxResult.error();
    }

    //判断用户当前项目剩余token是否还支持分配
    private void validUserTokenCount(UserCreateVo userCreateVo) {
        //现根据用户id,以及项目名称查询对应用户拥有的token
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, USER_SINGLE_REPO);
        params.put("token_name", userCreateVo.getToken_name());
        params.put("username", userCreateVo.getPayer());
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if(rsp != null) {
            long curToken = Long.parseLong(rsp.getString("balance"));
            Long amount = userCreateVo.getAmount();
            if (curToken <amount) {
                throw new ServiceException("token数量不足");
            }
        }

    }

    //判断项目剩余token是否还支持分配
    private void validTokenCount(String tokenName, Long amount,String userName) {
        TokenListVo v = new TokenListVo();
        if(StringUtils.isEmpty(tokenName)) {
            throw new ServiceException("项目ID不能为空");
        }
        v.setId(Long.parseLong(Optional.ofNullable(tokenName).orElse("-1")));
        Long issueTokenSum = projectResourceLibraryMapper.sumProjectIssueToken(v.getId());
        v.setIssueToken(issueTokenSum);
        //根据创建人、项目Id,获取创建人拥有token
        Long applyToken= getUserBlanaceProjectId("userSingleInfo",userName,tokenName);
        v.setApplyToken(applyToken);
        long curToken = applyToken - issueTokenSum;
        if (curToken < amount) {
            throw new ServiceException("token数量不足");
        }
    }

    private Long queryTotalToken(TokenListVo v) {
        if(v.getName().equals("区块链测试")){
            System.out.println("zzz");
        }
        JSONObject param = new JSONObject();
        param.put(REQUEST_TYPE, QUERY_REPO);
        param.put("token_name", String.valueOf(v.getId()));

        JSONObject jsonObject = queryFiscobcos(param);
        if (jsonObject != null) {
            return jsonObject.getLong("total_supply");
        }
        return -1L;
    }



    public AjaxResult prCreate(PrCreateVo prCreateVo) {
        Map<String, Object> res = projectResourceLibraryMapper.selectPrInfo(prCreateVo.getPr_id());
        if (res != null) {
            JSONObject params = JSONObject.from(res);
            Map<String, String> p = convertParams(params);
            params = JSONObject.from(p);
            params.put("updated_at", DataUtilsStr());
            params.put("pull_request_number", params.getLong("pull_request_number"));
            params.put(REQUEST_TYPE, CREATE_PR);
            JSONObject rsp = queryFiscobcos(params);
            if (rsp != null) {
                String txHash = rsp.getString(TX_HASH);
                //将对应的token todo
                // insert to db 新增表：pr入链关联（id,type,type_id,tx_hash,create_time） (type:pr,type_id:"pull_request_id)
                if (StringUtils.isNotEmpty(txHash)) {
                    InBlockchainData inBlockchainData = new InBlockchainData();
                    inBlockchainData.setType("pr");
                    inBlockchainData.setTxHash(txHash);
                    inBlockchainData.setTypeId(prCreateVo.getPr_id());
                    inBlockchainData.setCreateTime(DateUtils.getNowDate());
                    inBlockchainData.setCreateBy(SecurityUtils.getUsername());
                    inBlockchainDataMapper.insertInBlockchainData(inBlockchainData);
                    return AjaxResult.success(rsp);
                }
            }
        }
        return AjaxResult.error();
    }

    private String DataUtilsStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(DateUtils.getNowDate());
    }


    public AjaxResult issueCreateUpdate(IssueCreateVo issueCreateVo) {
        Map<String, Object> res = projectResourceLibraryMapper.selectIssueInfo(issueCreateVo.getIssue_id());
        if (res != null) {
            JSONObject params = JSONObject.from(res);
            params.put(REQUEST_TYPE, CREATE_UPDATE_ISSUE);
            params.put("updated_at", DataUtilsStr());
            Map<String, String> p = convertParams(params);
            params = JSONObject.from(p);
            JSONObject rsp = queryFiscobcos(params);
            if (rsp != null) {
                String txHash = rsp.getString(TX_HASH);
                // insert to db 4、 ：数据入链表（id,type,type_id,tx_hash,create_time） (type:issue,type_id:issue_id)
                if (StringUtils.isNotEmpty(txHash)) {
                    InBlockchainData inBlockchainData = new InBlockchainData();
                    inBlockchainData.setType("issue");
                    inBlockchainData.setTxHash(txHash);
                    inBlockchainData.setTypeId(issueCreateVo.getIssue_id());
                    inBlockchainData.setCreateTime(DateUtils.getNowDate());
                    inBlockchainData.setCreateBy(SecurityUtils.getUsername());
                    inBlockchainDataMapper.insertInBlockchainData(inBlockchainData);
                    return AjaxResult.success(rsp);
                }
            }
        }
        return AjaxResult.error();
    }

    public List<Map<String, Object>> issueDataList(BlockchainListQueryVo queryVo) {
        List<Map<String, Object>> maps = inBlockchainDataMapper.issueDataList(queryVo);
        handleForgeDate(maps);
        return maps;
    }

    private void handleForgeDate(List<Map<String, Object>> maps){
        for (Map<String, Object> m : maps) {
            LocalDateTime updatedAt = (LocalDateTime) m.get("updated_at");
            LocalDateTime createdAt = (LocalDateTime) m.get("created_at");
            m.put("updated_at",formatLocalDateTimePlusH(updatedAt,8));
            m.put("created_at",formatLocalDateTimePlusH(createdAt,8));

            if (m.containsKey("committer_time")) {
                LocalDateTime committer_time = (LocalDateTime) m.get("committer_time");
                m.put("committer_time",formatLocalDateTimePlusH(committer_time,8));
            }
        }
    }

    //定时任务，将commit数据入链
//    @Scheduled(cron = "${cron.commitPushBlock}")
    public void commitPushBlock() {
        //先查询需要入链的数据
        List<String> commitIdList = inBlockchainDataMapper.getNeedToBlockCommitList();
        if(commitIdList!=null && commitIdList.size()>0) {
            //遍历数据入区块链
            for(String commitId : commitIdList) {
                CommitCreateVo commitCreateVo = new CommitCreateVo();
                commitCreateVo.setCommit_id(commitId);
                commitCreate(commitCreateVo);
            }
        }
    }

    public AjaxResult commitCreate(CommitCreateVo commitCreateVo) {
        List<CommitResultVo> CommitCreateVoList = new ArrayList<>();
        if(StringUtils.isEmpty(commitCreateVo.getCommit_id())) {
            String projectId = commitCreateVo.getProject_id();
            if (StringUtils.isNotEmpty(projectId)) {
                CommitCreateVoList = inBlockchainDataMapper.getCommitListById(projectId);
            }
        }else{
            CommitResultVo resultVo = new CommitResultVo();
            resultVo.setCommitId(commitCreateVo.getCommit_id());
            resultVo.setCommitDiff(commitCreateVo.getCommit_diff());
            CommitCreateVoList.add(resultVo);
        }
        if(CommitCreateVoList!=null && CommitCreateVoList.size()>0) {
            for(CommitResultVo commit : CommitCreateVoList) {
                commitDataTnBlock(commit);
            }
        }
        return AjaxResult.success();
    }

    private AjaxResult commitDataTnBlock(CommitResultVo commitCreateVo) {
        String commitId = commitCreateVo.getCommitId();
        //根据项目id,查询对应的需要入链的commit
        Map<String, Object> res = projectResourceLibraryMapper.selectCommitInfo(commitId,commitCreateVo.getCommitDiff());
        JSONObject params = JSONObject.from(res);
        params.put(REQUEST_TYPE, CREATE_COMMIT);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            String txHash = rsp.getString(TX_HASH);
            // insert to db 4、 ：数据入链表（id,type,type_id,tx_hash,create_time） (type:issue,type_id:issue_id)
            if (StringUtils.isNotEmpty(txHash)) {
                InBlockchainData inBlockchainData = new InBlockchainData();
                inBlockchainData.setType("commit");
                inBlockchainData.setTxHash(txHash);
                inBlockchainData.setTypeId(commitId);
                inBlockchainData.setCreateTime(DateUtils.getNowDate());
                inBlockchainData.setCreateBy(SecurityUtils.getUsername());
                inBlockchainDataMapper.insertInBlockchainData(inBlockchainData);
                return AjaxResult.success(rsp);
            }
        }
        return AjaxResult.error();
    }

    public List<Map<String, Object>> commitDataList(BlockchainListQueryVo queryVo) {
        List<Map<String, Object>> maps = inBlockchainDataMapper.commitDataList(queryVo);
        handleForgeDate(maps);
        return maps;
    }

    public List<Map<String, Object>> prDataList(BlockchainListQueryVo queryVo) {
        List<Map<String, Object>> maps = inBlockchainDataMapper.prDataList(queryVo);
        handleForgeDate(maps);
        return maps;
    }
    //产权转让
    public List<Map> userDataList(BlockchainListQueryVo queryVo) {
        Long gitlinkUserId = SecurityUtils.getGitlinkUserId();
        Map<String, Object> stringObjectMap = Optional.ofNullable(talentReferralMapper.selectUsersById(gitlinkUserId)).orElse(new HashMap<>());
        if (!Objects.equals(stringObjectMap.get("admin"), "1")) {
            queryVo.setUserId(gitlinkUserId);
        }
        return userProjectTransferRecordsMapper.userDataList(queryVo);
    }

    public List<UserVo> userList(UserVo userVo) {
        return userProjectTransferRecordsMapper.userList(userVo);
    }

    public AjaxResult projectCreate(ProjectCreateVo projectCreateVo) {
        //先根据项目id(token_name)判断项目是否存在，存在才入链
        String tokenName = projectCreateVo.getToken_name();
        int num = talentReferralMapper.selectProjectById(tokenName);
        if(num>0) {
            JSONObject params = new JSONObject();
            params.put(REQUEST_TYPE, CREATE_REPO);
            params.put("owner", projectCreateVo.getOwner());
            params.put("token_name", projectCreateVo.getToken_name());
//            params.put("cur_supply", projectCreateVo.getCur_supply());
            Map<String, String> p = convertParams(params);
            params = JSONObject.from(p);
            params.put("total_supply", projectCreateVo.getTotal_supply());
            JSONObject rsp = queryFiscobcos(params);
            if (rsp != null) {
                String txHash = rsp.getString(TX_HASH);
                // insert to db 4、 ：数据入链表（id,type,type_id,tx_hash,create_time） (type:issue,type_id:issue_id)
                if (StringUtils.isNotEmpty(txHash)) {
                    InBlockchainData inBlockchainData = new InBlockchainData();
                    inBlockchainData.setType("project");
                    inBlockchainData.setTxHash(txHash);
                    inBlockchainData.setTypeId(projectCreateVo.getToken_name());
                    inBlockchainData.setCreateTime(DateUtils.getNowDate());
                    inBlockchainData.setCreateBy(SecurityUtils.getUsername());
                    inBlockchainDataMapper.insertInBlockchainData(inBlockchainData);
                    return AjaxResult.success(rsp);
                }
            }
        }
        return AjaxResult.error();
    }

    public AjaxResult queryBlockInfo(String type,String typeId) {
        JSONObject params = paramsQuery(type,typeId);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        return AjaxResult.success(rsp);
    }

    private JSONObject paramsQuery(String type, String typeId) {
        JSONObject params = new JSONObject();
        if(type.equals(PROJECT_INFO)){
            params.put(REQUEST_TYPE, QUERY_REPO);
            params.put("token_name", typeId);
        }else if(type.equals(COMMIT_INTO)){
            params.put(REQUEST_TYPE, QUERY_COMMIT);
            params.put("commit_hash", typeId);
        }else if(type.equals(PR_LATEST_INFO)){
            params.put(REQUEST_TYPE, QUERY_PR_LATEST);
            params.put("pull_request_id", typeId);
        }else if(type.equals(PR_ALL_INFO)){
            params.put(REQUEST_TYPE, QUERY_PR_ALL);
            params.put("pull_request_id", typeId);
        }else if(type.equals(ISSUE_LATEST_INFO)){
            params.put(REQUEST_TYPE, QUERY_ISSUE_LATEST);
            params.put("issue_id", typeId);
        }else if(type.equals(ISSUE_ALL_INFO)){
            params.put(REQUEST_TYPE, QUERY_ISSUE_ALL);
            params.put("issue_id", typeId);
        }
        return params;
    }


    public AjaxResult getTransactionByHash(String txHash) {
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, GET_TRANSACTION_BYHASH);
        params.put("tx_hash", txHash);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        return AjaxResult.success(rsp);
    }

    public AjaxResult getTransactionReceipt(String txHash) {
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, GET_TRANSACTION_RECEIPT);
        params.put("tx_hash", txHash);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        return AjaxResult.success(rsp);
    }

    public AjaxResult getTotalTransactionCount() {
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, GET_TOTAL_TRANSACTION_COUNTT);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        return AjaxResult.success(rsp);
    }

    public AjaxResult getBlockNumber() {
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, GET_BLOCK_NUM);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            return AjaxResult.success(rsp);
        }
        return AjaxResult.error();
    }

    public AjaxResult getUserTokenByProjectId(String type,String userName,String tokenName) {
        JSONObject params = new JSONObject();
        if(type.equals(USER_SINGLE_INFO)){
            params.put(REQUEST_TYPE, USER_SINGLE_REPO);
            params.put("token_name", tokenName);
            params.put("username", userName);
        }else if(type.equals(USER_ALL_INFO)){
            params.put(REQUEST_TYPE, USER_ALL_REPOS);
            params.put("username", userName);
        }
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            return AjaxResult.success(rsp);
        }
        return AjaxResult.error();
    }

    //
    public AjaxResult getUserAllProjectToken(String userName) {
        JSONObject params = new JSONObject();
        params.put(REQUEST_TYPE, USER_ALL_REPOS);
        params.put("username", userName);
        Map<String, String> p = convertParams(params);
        params = JSONObject.from(p);
        JSONObject rsp = queryFiscobcos(params);
        if (rsp != null) {
            return AjaxResult.success(rsp);
        }
        return AjaxResult.error();
    }
}
