package com.microservices.pms.repository.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.html.EscapeUtil;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.pms.enterprise.domain.PmsEnterprise;
import com.microservices.pms.enterprise.service.IPmsEnterpriseService;
import com.microservices.pms.repository.domain.PmsRepositorySearchVo;
import com.microservices.pms.repository.service.IPmsRepositoryService;
import com.microservices.pms.utils.PmsConstants;
import com.microservices.pms.utils.PmsGitLinkRequestUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评论功能Service业务层处理
 *
 * @author otto
 * @date 2023-11-01
 */
@Service
public class PmsRepositoryServiceImpl implements IPmsRepositoryService {

    @Autowired
    private IPmsEnterpriseService pmsEnterpriseService;
    @Autowired
    private GitLinkRequestHelper gitLinkRequestHelper;

    @Override
    public GenericsTableDataInfo<JSONObject> selectGitlinkProjectList(PmsRepositorySearchVo pmsRepositorySearchVo) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(pmsRepositorySearchVo.getEnterpriseIdentifier());
        JSONObject result = gitLinkRequestHelper.doGet(
                PmsGitLinkRequestUrl.PROJECTS(pmsEnterprise.getEnterpriseIdentifier(), pmsRepositorySearchVo.genQueryString())
        );
        JSONArray jsonArray = result.getJSONArray(PmsConstants.GITLINK_RESPONSE_PROJECTS_KEY);
        if (jsonArray == null) {
            throw new ServiceException("Gitlink项目列表获取失败");
        }
        List<JSONObject> list = jsonArray.toJavaList(JSONObject.class);
        list.forEach(x -> {
            x.put("url", EscapeUtil.removeExtraSlashOfUrl(
                    gitLinkRequestHelper.gitLinkUrl
                            + "/" + pmsEnterprise.getEnterpriseIdentifier()
                            + "/" + x.getString("identifier")));
        });
        Long size = result.getLong(PmsConstants.GITLINK_RESPONSE_TOTAL_COUNT_KEY);
        return new GenericsTableDataInfo<>(list, size);
    }
}
