package com.microservices.dms.resourceLibrary.service;

import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.dms.resourceLibrary.domain.CompetitionResourceLibrary;
import com.microservices.dms.resourceLibrary.domain.ProjectResourceLibrary;
import com.microservices.dms.resourceLibrary.domain.vo.CompetitionListVo;
import com.microservices.dms.resourceLibrary.domain.vo.KeyValVo;
import com.microservices.dms.resourceLibrary.mapper.CompetitionResourceLibraryMapper;
import com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo;
import com.microservices.dms.resourceLibrary.mapper.TaskResourceLibraryMapper;
import com.microservices.dms.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.microservices.dms.constant.TaskConstant.COMPETITION_TYPE_DOWNLOAD;
import static com.microservices.dms.constant.TaskConstant.PROJECT_DOWNLOAD_API;
import static com.microservices.dms.utils.UrlUtil.getUrlPath;

@Service
@RequiredArgsConstructor
public class CompetitionResourceLibraryService {

    @Value("${http.gitLinkUrl}")
    public String gitLinkUrl;

    private final CompetitionResourceLibraryMapper competitionResourceLibraryMapper;
    private final TaskResourceLibraryMapper taskResourceLibraryMapper;

    public List<UserActionDataVo> selectRegisterCondition(UserActionDataVo vo) {
        return competitionResourceLibraryMapper.selectRegisterCondition(vo);
    }

    public List<UserActionDataVo> selectOpusCondition(UserActionDataVo vo) {
        return competitionResourceLibraryMapper.selectOpusCondition(vo);
    }

    public List<CompetitionListVo> selectCompetitionListCondition(CompetitionListVo dataVo) {
        List<CompetitionListVo> competitionListVos = competitionResourceLibraryMapper.selectCompetitionListCondition(dataVo);
        for (CompetitionListVo vo : competitionListVos) {
            UserActionDataVo c = new UserActionDataVo();
            c.setItemId(vo.getId());
            c.setItemType(COMPETITION_TYPE_DOWNLOAD);
            long opusDownload = taskResourceLibraryMapper.countDownloaderCondition(c);
            vo.setOpusDownloadCount(opusDownload);
            Long register = competitionResourceLibraryMapper.countRegisterCondition(c);
            vo.setRegistrationsCount(register);
            c.setStatus(3);
            Long opus = competitionResourceLibraryMapper.countOpusCondition(c);
            vo.setOpusCount(opus);
        }

        return competitionListVos;
    }

    public CompetitionResourceLibrary selectCompetitionResourceLibraryById(Long id) {
        return competitionResourceLibraryMapper.selectCompetitionResourceLibraryById(id);
    }

    public List<CompetitionResourceLibrary> selectCompetitionResourceLibraryList(CompetitionResourceLibrary competitionResourceLibrary) {
        List<CompetitionResourceLibrary> list = competitionResourceLibraryMapper.selectCompetitionResourceLibraryList(competitionResourceLibrary);
        //  /api/attachments/10e9c28d-f8cb-4fbd-83c3-e46d2ff1b325
        for (CompetitionResourceLibrary l : list) {
            List<KeyValVo<String, String>> attachments = competitionResourceLibraryMapper.getAttachments(l.getCompetitionUserId());
            for (KeyValVo<String, String> a : attachments) {
                String v = a.getV();
                if (StringUtils.isNotEmpty(v)) {
                    a.setV(String.format(PROJECT_DOWNLOAD_API, gitLinkUrl, v));
                }
                l.setAttachmentList(attachments);
                l.setSubmissionTime(DateUtil.plusHours(l.getSubmissionTime(), 8));
            }
        }
        return list;
    }

    public Long insertCompetitionResourceLibrary(CompetitionResourceLibrary competitionResourceLibrary) {
        competitionResourceLibrary.setCreateTime(DateUtils.getNowDate());
        competitionResourceLibrary.setCreateBy(SecurityUtils.getUsername());
        competitionResourceLibrary.setTransferredToResultLibraryTime(DateUtils.getNowDate());
        competitionResourceLibraryMapper.insertCompetitionResourceLibrary(competitionResourceLibrary);
        return competitionResourceLibrary.getId();
    }

    public int updateCompetitionResourceLibrary(CompetitionResourceLibrary competitionResourceLibrary) {
        competitionResourceLibrary.setUpdateTime(DateUtils.getNowDate());
        return competitionResourceLibraryMapper.updateCompetitionResourceLibrary(competitionResourceLibrary);
    }

    public int deleteCompetitionResourceLibraryByIds(Long[] ids) {
        return competitionResourceLibraryMapper.deleteCompetitionResourceLibraryByIds(ids);
    }

    public int deleteCompetitionResourceLibraryById(Long id) {
        return competitionResourceLibraryMapper.deleteCompetitionResourceLibraryById(id);
    }


    /**
     * 返回开放竞赛总数
     *
     * @return 开放竞赛总数
     */
    public long getTotalOpenCompetitions() {
        // 这里替换成你的实际逻辑，例如从数据库查询
        return competitionResourceLibraryMapper.getTotalOpenCompetitions();
    }

    /**
     * 返回竞赛转换成果数
     *
     * @return 竞赛转换成果数
     */
    public long getTotalCompetitionAchievements() {
        // 这里替换成你的实际逻辑
        return competitionResourceLibraryMapper.getTotalCompetitionAchievements();
    }

    /**
     * 返回竞赛提交作品数
     *
     * @return 竞赛提交作品数
     */
    public long getTotalCompetitionSubmissions() {
        // 这里替换成你的实际逻辑
        return competitionResourceLibraryMapper.getTotalCompetitionSubmissions();
    }

    /**
     * 返回已结束竞赛数
     *
     * @return 已结束竞赛数
     */
    public long getTotalFinishedCompetitions() {
        // 这里替换成你的实际逻辑
        return competitionResourceLibraryMapper.getTotalFinishedCompetitions();
    }

    /**
     * 返回需评审竞赛数
     *
     * @return 需评审竞赛数
     */
    public long getReviewCompetitionCount() {
        // 这里替换成你的实际逻辑
        return competitionResourceLibraryMapper.getReviewCompetitionCount();
    }

    public String batchInsertCompetitionResourceLibrary(List<CompetitionResourceLibrary> list, boolean updateSupport, String operName) {
        if (list == null || list.isEmpty()) {
            return "导入数据为空";
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (CompetitionResourceLibrary competitionResourceLibrary : list) {
            try {
                String competitionName = competitionResourceLibrary.getOpenCompetitionName();
                if (competitionName == null || competitionName.trim().isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、竞赛名称为空，导入失败");
                    continue;
                }

                CompetitionResourceLibrary existCompetition = competitionResourceLibraryMapper.selectCompetitionResourceLibraryByCompetitionName(competitionName);

                if (existCompetition == null) {
                    // 不存在，插入
                    competitionResourceLibrary.setCreateBy(operName);
                    competitionResourceLibrary.setCreateTime(DateUtils.getNowDate());
                    competitionResourceLibraryMapper.insertCompetitionResourceLibrary(competitionResourceLibrary);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、竞赛 ").append(competitionName).append(" 导入成功");
                } else if (updateSupport) {
                    // 存在且支持更新
                    competitionResourceLibrary.setId(existCompetition.getId());
                    competitionResourceLibrary.setUpdateBy(operName);
                    competitionResourceLibrary.setUpdateTime(DateUtils.getNowDate());
                    competitionResourceLibraryMapper.updateCompetitionResourceLibrary(competitionResourceLibrary);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、竞赛 ").append(competitionName).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、竞赛 ").append(competitionName).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、竞赛 " + competitionResourceLibrary.getOpenCompetitionName() + " 导入失败";
                failureMsg.append(msg);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "导入完成，共 " + failureNum + " 条数据格式不正确：");
            if (successNum > 0) {
                failureMsg.append("<br/>成功导入 ").append(successNum).append(" 条数据");
            }
            return failureMsg.toString();
        }
        successMsg.insert(0, "导入成功，共 " + successNum + " 条数据：");
        return successMsg.toString();
    }
}
