package org.dromara.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.MainBackCandidate;
import org.dromara.main.domain.MainStudent;
import org.dromara.main.domain.bo.MainPostCandidateHireBo;
import org.dromara.main.domain.bo.MainPostCandidateQueryBo;
import org.dromara.main.domain.bo.MainPostCandidateStatusBo;
import org.dromara.main.domain.vo.MainPostCandidateVo;
import org.dromara.main.mapper.MainBackCandidateMapper;
import org.dromara.main.mapper.MainStudentMapper;
import org.dromara.main.service.IMainMessageService;
import org.dromara.main.service.IMainPostCandidateService;
import org.dromara.system.service.ISysOssService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class MainPostCandidateServiceImpl implements IMainPostCandidateService {

    private static final String ENTERPRISE_STATUS_ADOPTED = "adopted";
    private static final String ENTERPRISE_STATUS_REJECTED = "rejected";
    private static final String ENTERPRISE_STATUS_PENDING = "pending";

    private final MainBackCandidateMapper mainBackCandidateMapper;
    private final MainStudentMapper mainStudentMapper;
    private final ISysOssService sysOssService;
    private final IMainMessageService mainMessageService;

    @Override
    public TableDataInfo<MainPostCandidateVo> queryPageList(MainPostCandidateQueryBo bo, PageQuery pageQuery) {
        if (bo.getPostId() == null) {
            throw new ServiceException("岗位ID不能为空");
        }
        IPage<MainPostCandidateVo> page = mainBackCandidateMapper.selectPostCandidatePage(pageQuery.build(), bo);
        return TableDataInfo.build(page);
    }

    @Override
    public List<MainPostCandidateVo> queryList(MainPostCandidateQueryBo bo) {
        if (bo.getPostId() == null) {
            throw new ServiceException("岗位ID不能为空");
        }
        return mainBackCandidateMapper.selectPostCandidateList(bo);
    }

    @Override
    public Boolean hireCandidate(MainPostCandidateHireBo bo) {
        if (bo.getId() == null) {
            throw new ServiceException("报名记录ID不能为空");
        }
        if (bo.getOfferAttachment() == null || bo.getOfferAttachment().isBlank()) {
            throw new ServiceException("请先上传录用附件");
        }
        MainBackCandidate entity = new MainBackCandidate();
        entity.setId(bo.getId());
        entity.setEnterpriseStatus(ENTERPRISE_STATUS_ADOPTED);
        entity.setRemark(bo.getRemark());
        entity.setOfferFileUrl(bo.getOfferAttachment());
        entity.setOfferTime(LocalDateTime.now());
        boolean hired = mainBackCandidateMapper.updateById(entity) > 0;
        if (hired) {
            MainBackCandidate candidate = mainBackCandidateMapper.selectById(bo.getId());
            sendCandidateNotification(candidate, "投递进度更新", "企业已发送Offer，请及时查看");
        }
        return hired;
    }

    @Override
    public Boolean updateStatus(MainPostCandidateStatusBo bo) {
        if (bo.getId() == null) {
            throw new ServiceException("报名记录ID不能为空");
        }
        if (bo.getStatus() == null || bo.getStatus().isBlank()) {
            throw new ServiceException("状态不能为空");
        }
        String normalizedStatus = normalizeStatus(bo.getStatus());
        if (normalizedStatus == null) {
            throw new ServiceException("状态值不合法");
        }
        MainBackCandidate entity = new MainBackCandidate();
        entity.setId(bo.getId());
        entity.setEnterpriseStatus(normalizedStatus);
        entity.setRemark(bo.getRemark());
        boolean updated = mainBackCandidateMapper.updateById(entity) > 0;
        if (updated) {
            MainBackCandidate candidate = mainBackCandidateMapper.selectById(bo.getId());
            String msgContent = ENTERPRISE_STATUS_ADOPTED.equals(normalizedStatus) ? "企业已录用" : "企业已拒绝";
            sendCandidateNotification(candidate, "投递进度更新", msgContent);
        }
        return updated;
    }

    private String normalizeStatus(String status) {
        return switch (status.trim()) {
            case ENTERPRISE_STATUS_ADOPTED, "0" -> ENTERPRISE_STATUS_ADOPTED;
            case ENTERPRISE_STATUS_REJECTED, "1" -> ENTERPRISE_STATUS_REJECTED;
            case ENTERPRISE_STATUS_PENDING, "2" -> ENTERPRISE_STATUS_PENDING;
            default -> null;
        };
    }

    @Override
    public void downloadResume(Long candidateId, HttpServletResponse response) throws IOException {
        if (candidateId == null) {
            throw new ServiceException("候选人ID不能为空");
        }
        MainBackCandidate candidate = mainBackCandidateMapper.selectById(candidateId);
        if (candidate == null) {
            throw new ServiceException("候选人记录不存在");
        }
        if (candidate.getStudentId() == null) {
            throw new ServiceException("候选人未关联学员");
        }
        MainStudent student = mainStudentMapper.selectById(candidate.getStudentId());
        if (student == null || student.getResumeFile() == null) {
            throw new ServiceException("该候选人暂无简历附件");
        }
        sysOssService.download(student.getResumeFile(), response);
    }

    /**
     * 投递进度变化时发送通知消息给学员
     */
    private void sendCandidateNotification(MainBackCandidate candidate, String title, String content) {
        try {
            if (candidate == null || candidate.getStudentId() == null) return;
            mainMessageService.sendNotification(candidate.getStudentId(), title, content, candidate.getPostId());
        } catch (Exception e) {
            log.warn("投递进度变化发送通知消息失败，candidateId={}, error={}", candidate != null ? candidate.getId() : null, e.getMessage());
        }
    }
}
