package com.ruoyi.cms.service.rc.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cms.domain.rc.JobFairSignUp;
import com.ruoyi.cms.mapper.rc.JobFairSignUpMapper;
import com.ruoyi.cms.service.rc.IJobFairSignUpService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SiteSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 招聘会报名Service业务层处理
 */
@Service
public class JobFairSignUpServiceImpl extends ServiceImpl<JobFairSignUpMapper, JobFairSignUp> implements IJobFairSignUpService {

    @Autowired
    private JobFairSignUpMapper jobFairSignUpMapper;

    @Override
    public int signUp(Long jobFairId) {
        Long userId = SiteSecurityUtils.getUserId();
        
        // 检查是否已有报名记录
        JobFairSignUp existSignUp = jobFairSignUpMapper.checkSignUp(jobFairId, userId);
        
        if (existSignUp != null) {
            // 已有记录
            if ("0".equals(existSignUp.getStatus())) {
                throw new ServiceException("您已报名该招聘会，请勿重复报名");
            }
            // 已取消的记录，重新激活
            existSignUp.setStatus("0");
            existSignUp.setSignUpTime(new Date());
            return jobFairSignUpMapper.updateById(existSignUp);
        }
        
        // 新增报名记录
        JobFairSignUp signUp = new JobFairSignUp();
        signUp.setJobFairId(jobFairId);
        signUp.setUserId(userId);
        signUp.setSignUpTime(new Date());
        signUp.setStatus("0");
        
        return jobFairSignUpMapper.insert(signUp);
    }

    @Override
    public int cancelSignUp(Long jobFairId) {
        Long userId = SiteSecurityUtils.getUserId();
        
        JobFairSignUp existSignUp = jobFairSignUpMapper.checkSignUp(jobFairId, userId);
        if (existSignUp == null || "1".equals(existSignUp.getStatus())) {
            throw new ServiceException("您未报名该招聘会");
        }
        
        existSignUp.setStatus("1"); // 已取消
        return jobFairSignUpMapper.updateById(existSignUp);
    }
}
