package com.microservices.pms.project.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.common.service.IPmsCommonService;
import com.microservices.pms.enterprise.domain.PmsEnterprise;
import com.microservices.pms.enterprise.service.IPmsEnterpriseService;
import com.microservices.pms.project.domain.PmsProject;
import com.microservices.pms.project.domain.SimpleRepository;
import com.microservices.pms.project.domain.vo.*;
import com.microservices.pms.utils.PmsConstants;
import com.microservices.pms.utils.PmsGitLinkRequestUrl;
import com.microservices.pms.utils.PmsUtils;
import com.microservices.system.api.domain.SimpleSysUser;
import com.microservices.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URISyntaxException;
import java.util.*;

import static com.microservices.common.core.utils.DateUtils.YYYY_MM_DD;
import static com.microservices.common.core.utils.JSONUtils.convertObjectToJSONObject;
import static com.microservices.common.core.web.domain.AjaxResult.DATA_TAG;
import static com.microservices.common.httpClient.constant.GitLinkConstants.DATA_KEY;


/**
 * 项目工作项Service业务层处理
 *
 * @author wanjia
 * @date 2023-10-13
 */
@Service
public class PmsProjectIssuesService {

    private static final Logger logger = LoggerFactory.getLogger(PmsProjectIssuesService.class);

    @Autowired
    private GitLinkRequestHelper gitLinkRequestHelper;

    @Autowired
    @Lazy
    private IPmsProjectService pmsProjectService;

    @Autowired
    @Lazy
    private IPmsProjectTestsheetIssuesService pmsProjectTestsheetIssuesService;

    @Autowired
    private IPmsEnterpriseService pmsEnterpriseService;

    @Autowired
    private IPmsCommonService pmsCommonService;


    public JSONObject selectPmsProjectIssuesList(PmsProjectIssuesSearchVo pmsProjectIssuesSearchVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssuesSearchVo.getPmProjectId());
        JSONObject issueSearch = new JSONObject();
        convertObjectToJSONObject(pmsProjectIssuesSearchVo, issueSearch, null);
        try {
            return setProjectIssueListUserState(gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE_LIST(issueSearch)));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject setProjectIssueListUserState(JSONObject issueListResult) {
        HashMap<Long, String> gitlinkUserNickNameMap = new HashMap<>();
        if (issueListResult.containsKey("issues")) {
            JSONArray issues = issueListResult.getJSONArray("issues");
            for (int i = 0; i < issues.size(); i++) {
                JSONObject issue = issues.getJSONObject(i);
                setIssueAssignersState(issue, gitlinkUserNickNameMap);
                issues.set(i, issue);
            }
            issueListResult.put("issues", issues);
        }
        return issueListResult;
    }

    public JSONObject insertPmsProjectIssues(PmsProjectIssuesInputVo pmsProjectIssuesInputVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssuesInputVo.getPmProjectId());
        JSONObject issueInput = convertPmsProjectIssuesInputVoToIssueInputJSON(pmsProjectIssuesInputVo);
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.CREATE_ISSUE(), issueInput);
    }

    public JSONObject updatePmsProjectIssues(Long id, PmsProjectIssuesInputVo pmsProjectIssuesInputVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssuesInputVo.getPmProjectId());
        JSONObject updatedIssue;
        try {
            updatedIssue = gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE(id, pmsProjectIssuesInputVo.getPmProjectId()));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        if (PmsConstants.PROJECT_ISSUE_TYPE_WEEKLY_REPORT.equals(updatedIssue.getString("pm_issue_type"))
                && updatedIssue.getString("root_id") != null
                && !updatedIssue.getJSONObject("author").getLong("id").equals(SecurityUtils.getGitlinkUserId())) {
            throw new ServiceException("非本人周报，不可编辑");
        }
        JSONObject issueInput = convertPmsProjectIssuesInputVoToIssueInputJSON(pmsProjectIssuesInputVo);
        return gitLinkRequestHelper.doPut(PmsGitLinkRequestUrl.UPDATE_ISSUE(id), issueInput);
    }

    public JSONObject batchUpdatePmsProjectIssues(Long pmProjectId, PmsProjectIssuesBatchUpdateVo pmsProjectIssuesUpdateVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        //转换为issue入参
        JSONObject issueBatchUpdate = new JSONObject();
        convertObjectToJSONObject(pmsProjectIssuesUpdateVo, issueBatchUpdate, null);
        return gitLinkRequestHelper.doPatch(PmsGitLinkRequestUrl.UPDATE_ISSUE_BATCH(pmProjectId), issueBatchUpdate);
    }

    public JSONObject selectPmsProjectIssueById(Long id, Long pmProjectId) {
        PmsProject pmsProject = pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        try {
            JSONObject result = setProjectIssueUserState(gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE(id, pmProjectId)));
            result.put("pm_project_name", pmsProject.getProjectName());
            return result;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }


    private JSONObject setProjectIssueUserState(JSONObject issueResult) {
        HashMap<Long, String> gitlinkUserNickNameMap = new HashMap<>();
        setIssueAssignersState(issueResult, gitlinkUserNickNameMap);
        return issueResult;
    }

    private JSONObject genDeleteUserJsonObject() {
        SysUser deleteUser = SysUser.genDeleteUser();
        JSONObject deleteUserJSONObject = new JSONObject();
        deleteUserJSONObject.put("id", deleteUser.getGitlinkUserId());
        deleteUserJSONObject.put("image_url", deleteUser.getAvatar());
        deleteUserJSONObject.put("login", deleteUser.getUserName());
        deleteUserJSONObject.put("name", deleteUser.getNickName());
        deleteUserJSONObject.put("type", "User");
        return deleteUserJSONObject;
    }

    private void setIssueAssignersState(JSONObject issueResult, HashMap<Long, String> gitlinkUserNickNameMap) {
        if (issueResult.containsKey("assigners")) {
            JSONArray assigners = issueResult.getJSONArray("assigners");
            for (int j = 0; j < assigners.size(); j++) {
                JSONObject assigner = assigners.getJSONObject(j);
                if (assigner == null) {
                    assigner = genDeleteUserJsonObject();
                } else if (assigner.containsKey("id")) {
                    Long gitlinkUserId = assigner.getLong("id");
                    String nickName;
                    if (gitlinkUserNickNameMap.containsKey(gitlinkUserId)) {
                        nickName = gitlinkUserNickNameMap.get(gitlinkUserId);
                    } else {
                        SimpleSysUser simpleSysUser = pmsCommonService.getSimpleSysUserByGitlinkUserId(gitlinkUserId);
                        nickName = simpleSysUser.getNickName();
                        gitlinkUserNickNameMap.put(gitlinkUserId, nickName);
                    }
                    assigner.put("name", nickName);
                }
                assigners.set(j, assigner);
            }
            issueResult.put("assigners", assigners);
        }
        if (issueResult.containsKey("author")) {
            JSONObject author = issueResult.getJSONObject("author");
            if (author == null) {
                author = genDeleteUserJsonObject();
            } else if (author.containsKey("id")) {
                Long gitlinkUserId = author.getLong("id");
                String nickName;
                if (gitlinkUserNickNameMap.containsKey(gitlinkUserId)) {
                    nickName = gitlinkUserNickNameMap.get(gitlinkUserId);
                } else {
                    SimpleSysUser simpleSysUser = pmsCommonService.getSimpleSysUserByGitlinkUserId(gitlinkUserId);
                    nickName = simpleSysUser.getNickName();
                    gitlinkUserNickNameMap.put(gitlinkUserId, nickName);
                }
                author.put("name", nickName);
            }
            issueResult.put("author", author);
        }
        if (issueResult.containsKey("changer")) {
            JSONObject changer = issueResult.getJSONObject("changer");
            if (changer == null) {
                changer = genDeleteUserJsonObject();
            } else if (changer.containsKey("id")) {
                Long gitlinkUserId = changer.getLong("id");
                String nickName;
                if (gitlinkUserNickNameMap.containsKey(gitlinkUserId)) {
                    nickName = gitlinkUserNickNameMap.get(gitlinkUserId);
                } else {
                    SimpleSysUser simpleSysUser = pmsCommonService.getSimpleSysUserByGitlinkUserId(gitlinkUserId);
                    nickName = simpleSysUser.getNickName();
                    gitlinkUserNickNameMap.put(gitlinkUserId, nickName);
                }
                changer.put("name", nickName);
            }
            issueResult.put("changer", changer);
        }
        if (issueResult.containsKey("user")) {
            JSONObject user = issueResult.getJSONObject("user");
            if (user == null) {
                user = genDeleteUserJsonObject();
            } else if (user.containsKey("id")) {
                Long gitlinkUserId = user.getLong("id");
                String nickName;
                if (gitlinkUserNickNameMap.containsKey(gitlinkUserId)) {
                    nickName = gitlinkUserNickNameMap.get(gitlinkUserId);
                } else {
                    SimpleSysUser simpleSysUser = pmsCommonService.getSimpleSysUserByGitlinkUserId(gitlinkUserId);
                    nickName = simpleSysUser.getNickName();
                    gitlinkUserNickNameMap.put(gitlinkUserId, nickName);
                }
                user.put("name", nickName);
            }
            issueResult.put("user", user);
        }
    }

    public JSONObject deletePmsProjectIssueByIds(Long[] ids, Long pmProjectId) {
        // 删除缺陷与测试单关联关系
        pmsProjectTestsheetIssuesService.deletePmsProjectTestsheetIssuesByIssueIds(ids);
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        if (ids != null && ids.length == 1 && ids[0] != -1) {
            return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ISSUE(ids[0], pmProjectId));
        }
        if (ids != null && ids.length == 1) {
            ids = new Long[0];
        }
        JSONArray jsonArray = new JSONArray();
        if (ids != null) {
            // 使用Arrays.asList直接转换为JSONArray
            jsonArray = new JSONArray(Arrays.asList(ids));
        }
        JSONObject jsonObject = new JSONObject();
        // 将JSONArray放入JSONObject
        jsonObject.put("ids", jsonArray);
        return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ISSUES_BATCH(pmProjectId), jsonObject);
    }

    public JSONObject selectPmsProjectIssueStatus() {
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_REPO_ISSUE_DEFAULT_STATUS());
    }

    public JSONObject selectPmsProjectIssuePriorities() {
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_REPO_ISSUE_DEFAULT_PRIORITIES());
    }

    public JSONObject selectPmsProjectIssueTags(Long pmProjectId, Long repositoryId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        Map<String, String> params = new HashMap<>();
        params.put("pm_project_id", String.valueOf(pmProjectId));
        params.put("project_id", String.valueOf(repositoryId));
        try {
            return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_REPO_ISSUE_DEFAULT_TAGS(params));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public JSONArray selectPmsProjectRepoBranches(Long repositoryId) {
        JSONObject repoBranches = null;
        SimpleRepository simpleRepository = getSimpleRepository(repositoryId);
        if (simpleRepository != null) {
            repoBranches = gitLinkRequestHelper.doGet(
                    PmsGitLinkRequestUrl.GET_BRANCHES_BY_REPO_ID(
                            simpleRepository.getRepoOwner(),
                            simpleRepository.getRepoIdentifier())
            );
        }

        JSONArray repoBranchArray = null;
        if (repoBranches != null) {
            repoBranchArray = repoBranches.getJSONArray(DATA_TAG);
        }
        return repoBranchArray;
    }

    public SimpleRepository getSimpleRepository(Long repositoryId) {
        SimpleRepository simpleRepository = new SimpleRepository();
        JSONObject repoInfo = gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_OWNER_AND_REPO_BY_REPO_ID(repositoryId));
        JSONObject repoData = repoInfo.getJSONObject(DATA_KEY);
        if (repoData == null) {
            return null;
        }
        simpleRepository.setRepoIdentifier(repoData.getString("identifier"));
        simpleRepository.setRepoOwner(repoData.getString("owner"));
        return simpleRepository;
    }

    public JSONObject uploadAttachment(MultipartFile file) {
        return gitLinkRequestHelper.doPostFile(PmsGitLinkRequestUrl.UPLOAD_ATTACHMENTS(), file);
    }

    public JSONObject deleteAttachment(Long id) {
        return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ATTACHMENTS(id));
    }

    public JSONObject getProjectIssuesCount(List<String> projectIdList, String participantCategory, String category) {
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE_COUNT(projectIdList, participantCategory, category));
    }

    public JSONObject deletePmsProjectIssueLink(Long issueId, String linkIssueId, Long pmProjectId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        try {
            return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ISSUE_LINK(issueId, linkIssueId, pmProjectId));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getPmsProjectIssueLink(Long issueId, Long pmProjectId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        return setProjectIssueListUserState(gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE_LINK(issueId, pmProjectId)));
    }

    public JSONObject getPmsProjectIssueUnlink(Long issueId, Long pmProjectId, Integer pmIssueType, String issueFilterType, Integer pageNum, Integer pageSize) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        return setProjectIssueListUserState(gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE_UNLINK(issueId, pmProjectId, pmIssueType, issueFilterType, pageNum, pageSize)));
    }

    public JSONObject addPmsProjectIssueLink(Long issueId, PmsProjectIssuesLinkVo pmsProjectIssuesLinkVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssuesLinkVo.getPmProjectId());
        JSONObject params = new JSONObject();
        params.put("link_ids", pmsProjectIssuesLinkVo.getLinkIssueIds());
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.ADD_ISSUE_LINK(issueId, pmsProjectIssuesLinkVo.getPmProjectId()), params);
    }

    public void deletePmsProjectIssueByProjectId(Long projectId) {
        pmsProjectService.selectAndCheckPmsProjectById(projectId);
        JSONObject jsonObject = new JSONObject();
        // 将空数组放入JSONObject
        jsonObject.put("ids", new Long[0]);
        gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ISSUES_BATCH(projectId), jsonObject);
    }

    public JSONObject addPmsProjectIssueJournals(Long issueId, PmsProjectIssueJournalInputVo pmsProjectIssueJournalInputVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssueJournalInputVo.getPmProjectId());
        JSONObject journalsJson = new JSONObject();
        PmsProjectIssueJournalAddVo pmsProjectIssueJournalAddVo = new PmsProjectIssueJournalAddVo();
        BeanUtils.copyProperties(pmsProjectIssueJournalInputVo, pmsProjectIssueJournalAddVo);
        convertObjectToJSONObject(pmsProjectIssueJournalAddVo, journalsJson, null);
        return gitLinkRequestHelper.doPost(
                PmsGitLinkRequestUrl.ADD_ISSUE_JOURNAL(issueId,
                        pmsProjectIssueJournalInputVo.getPmProjectId(),
                        pmsProjectIssueJournalInputVo.getPmProjectRepositoryId()),
                journalsJson
        );
    }

    public JSONObject removePmsProjectIssueJournals(Long issueId, Long journalId, Long pmProjectId, Long pmProjectRepositoryId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ISSUE_JOURNAL(issueId, journalId, pmProjectId, pmProjectRepositoryId));
    }

    public JSONObject editPmsProjectIssueJournals(Long issueId, Long journalId, PmsProjectIssueJournalEditVo pmsProjectIssueJournalEditVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssueJournalEditVo.getPmProjectId());
        JSONObject journalsJson = new JSONObject();
        PmsProjectIssueJournalEditDTO pmsProjectIssueJournalEditDTO = new PmsProjectIssueJournalEditDTO();
        BeanUtils.copyProperties(pmsProjectIssueJournalEditVo, pmsProjectIssueJournalEditDTO);
        convertObjectToJSONObject(pmsProjectIssueJournalEditDTO, journalsJson, null);
        return gitLinkRequestHelper.doPatch(
                PmsGitLinkRequestUrl.DELETE_ISSUE_JOURNAL(issueId,
                        journalId,
                        pmsProjectIssueJournalEditVo.getPmProjectId(),
                        pmsProjectIssueJournalEditVo.getPmProjectRepositoryId()),
                journalsJson
        );
    }

    public JSONObject getPmsProjectIssueJournals(Long issueId, PmsProjectIssueJournalSearchVo pmsProjectIssueJournalSearchVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectIssueJournalSearchVo.getPmProjectId());
        JSONObject searchObj = new JSONObject();
        convertObjectToJSONObject(pmsProjectIssueJournalSearchVo, searchObj, null);
        searchObj.keySet().stream()
                .filter(key -> searchObj.get(key) != null)
                .forEach(key -> searchObj.put(key, String.valueOf(searchObj.get(key))));
        try {
            JSONObject result = gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ISSUE_JOURNALS(issueId, searchObj));
            return setProjectIssueJournalsUserState(result);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    private JSONObject setProjectIssueJournalsUserState(JSONObject journalsResult) {
        HashMap<Long, String> gitlinkUserNickNameMap = new HashMap<>();
        if (journalsResult.containsKey("journals")) {
            JSONArray journals = journalsResult.getJSONArray("journals");
            for (int i = 0; i < journals.size(); i++) {
                JSONObject journal = journals.getJSONObject(i);
                setIssueAssignersState(journal, gitlinkUserNickNameMap);
                if (journal.containsKey("children_journals")) {
                    JSONArray childrenJournals = journal.getJSONArray("children_journals");
                    for (int j = 0; j < childrenJournals.size(); j++) {
                        JSONObject childrenJournal = childrenJournals.getJSONObject(j);
                        setIssueAssignersState(childrenJournal, gitlinkUserNickNameMap);
                    }
                    journal.put("children_journals", childrenJournals);
                }
                journals.set(i, journal);
            }
            journalsResult.put("journals", journals);
        }
        return journalsResult;
    }

    public JSONObject getPmsProjectSprintLinkIssues(PmsProjectSprintLinkIssuesSearchVo pmsProjectSprintLinkIssuesSearchVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectSprintLinkIssuesSearchVo.getPmProjectId());
        JSONObject searchObj = new JSONObject();
        convertObjectToJSONObject(pmsProjectSprintLinkIssuesSearchVo, searchObj, null);
        try {
            JSONObject result = gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_SPRINT_ISSUES(searchObj));
            return setProjectIssueListUserState(result);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    private JSONObject convertPmsProjectIssuesInputVoToIssueInputJSON(PmsProjectIssuesInputVo pmsProjectIssuesInputVo) {
        PmsUtils.validStartTimeAndEndTime(DateUtils.dateTime(YYYY_MM_DD, pmsProjectIssuesInputVo.getStartDate()),
                DateUtils.dateTime(YYYY_MM_DD, pmsProjectIssuesInputVo.getDueDate()));
        //转换为issue入参
        JSONObject issueInput = new JSONObject();
        Map<Class<?>, String> formatPatterns = new HashMap<>();
        // 添加Date类型的格式化pattern
        formatPatterns.put(Date.class, "yyyy-MM-dd");
        convertObjectToJSONObject(pmsProjectIssuesInputVo, issueInput, formatPatterns);
        return issueInput;
    }

    public JSONObject getPmsProjectIssueOptionalParentIssueList(Long issueId, String pmIssueType, String pmProjectId, String keyword, Integer pageNum, Integer pageSize) {
        pmsProjectService.selectAndCheckPmsProjectById(pmProjectId);
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_OPTIONAL_PARENT_ISSUES(issueId, pmIssueType, pmProjectId, keyword, pageNum, pageSize));
    }

    public JSONObject selectPmsEnterpriseIssueTags(PmsEnterpriseIssueTagsSearchVo pmsEnterpriseIssueTagsSearchVo) {
        JSONObject issueTagsSearchParams = new JSONObject();
        convertObjectToJSONObject(pmsEnterpriseIssueTagsSearchVo, issueTagsSearchParams, null);
        try {
            return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_ORGANIZATION_ISSUE_TAGS_LIST(issueTagsSearchParams));
        } catch (URISyntaxException e) {
            logger.error("buildUri error: " + e);
            throw new ServiceException("输入参数转换为url出错");
        }
    }

    public JSONObject createPmsEnterpriseIssueTag(PmsEnterpriseIssueTagInputVo pmsEnterpriseIssueTagInputVo) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsEnterpriseIssueTagInputVo.getPmProjectId());
        JSONObject pmsEnterpriseIssueTagInput = new JSONObject();
        convertObjectToJSONObject(pmsEnterpriseIssueTagInputVo, pmsEnterpriseIssueTagInput, null);
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.CREATE_ORGANIZATION_ISSUE_TAG(), pmsEnterpriseIssueTagInput);
    }

    public JSONObject editPmsEnterpriseIssueTag(Long tagId, PmsEnterpriseIssueTagUpdateVo pmsEnterpriseIssueTagUpdateVo) {
        JSONObject pmsEnterpriseIssueTagUpdate = new JSONObject();
        convertObjectToJSONObject(pmsEnterpriseIssueTagUpdateVo, pmsEnterpriseIssueTagUpdate, null);
        return gitLinkRequestHelper.doPatch(PmsGitLinkRequestUrl.UPDATE_ORGANIZATION_ISSUE_TAG(tagId), pmsEnterpriseIssueTagUpdate);
    }

    public JSONObject deletePmsEnterpriseIssueTag(Long tagId) {
        return gitLinkRequestHelper.doDelete(PmsGitLinkRequestUrl.DELETE_ORGANIZATION_ISSUE_TAG(tagId));
    }

    public JSONObject importIssuesFromFile(String enterpriseIdentifier, MultipartFile file, Long pmProjectId) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(enterpriseIdentifier);
        JSONObject result;
        try {
            result = gitLinkRequestHelper.doPostFile(PmsGitLinkRequestUrl.IMPORT_ISSUES(pmProjectId, pmsEnterprise.getGitlinkOrgId()), file);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("导入失败，请上传正确格式的excel文件");
        }
        return result;
    }

    public void exportIssues(HttpServletResponse response, Long pmProjectId) {
        try {
            gitLinkRequestHelper.doGetResponse(PmsGitLinkRequestUrl.EXPORT_ISSUES(pmProjectId), response);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("导出工作项失败");
        }
    }
}
