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

import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.project.domain.PmsIssueCompletion;
import com.microservices.pms.project.domain.vo.PmsProjectIssuesCompletionInputVo;
import com.microservices.pms.project.mapper.PmsIssueCompletionMapper;
import com.microservices.pms.project.service.IPmsIssueCompletionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class PmsIssueCompletionServiceImpl implements IPmsIssueCompletionService {

    @Resource
    private PmsIssueCompletionMapper issueCompletionMapper;

    /**
     * 添加或更新 issue 完成情况
     */
    @Override
    public boolean saveOrUpdateCompletion(PmsProjectIssuesCompletionInputVo completionInputVo) {
        PmsIssueCompletion completion = new PmsIssueCompletion();
        completion.setGitlinkIssueId(completionInputVo.getGitlinkIssueId());
        completion.setDescription(completionInputVo.getDescription());
        completion.setGitlinkUserId(String.valueOf(SecurityUtils.getGitlinkUserId()));
        if (StringUtils.isBlank(completionInputVo.getDescription())) {
            issueCompletionMapper.deleteByGitlinkIssueIdAndUserId(completion.getGitlinkIssueId(), completion.getGitlinkUserId());
            return true;
        }
        // 判断是否已存在该 gitlink_issue_id 记录
        PmsIssueCompletion existing = issueCompletionMapper.selectByGitlinkIssueIdAndUserId(completion.getGitlinkIssueId(), completion.getGitlinkUserId());
        if (existing == null) {
            issueCompletionMapper.insert(completion);
        } else {
            completion.setId(existing.getId());
            completion.setUpdateTime(new Date());
            issueCompletionMapper.updateDescription(completion);
        }
        return true;
    }
}
