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

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cms.domain.Job;
import com.ruoyi.cms.domain.rc.JobFairSignUp;
import com.ruoyi.cms.domain.rc.PublicJobFairCompany;
import com.ruoyi.cms.domain.rc.PublicJobFairJob;
import com.ruoyi.cms.domain.vo.CompanyJobFairSignUpVO;
import com.ruoyi.cms.mapper.JobMapper;
import com.ruoyi.cms.mapper.rc.JobFairSignUpMapper;
import com.ruoyi.cms.mapper.rc.PublicJobFairMapper;
import com.ruoyi.cms.service.ICompanyService;
import com.ruoyi.cms.service.rc.IJobFairSignUpService;
import com.ruoyi.cms.util.RoleUtils;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private JobFairSignUpMapper jobFairSignUpMapper;

    @Autowired
    private PublicJobFairMapper publicJobFairMapper;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private ICompanyService companyService;

    @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);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult companySignUp(CompanyJobFairSignUpVO signUpVO) {
        // 1. 校验参数
        if (StringUtils.isBlank(signUpVO.getJobFairId())) {
            return AjaxResult.error("招聘会ID不能为空");
        }
        if (signUpVO.getJobList() == null || signUpVO.getJobList().isEmpty()) {
            return AjaxResult.error("请至少填写一个岗位");
        }

        // 2. 校验是否企业用户
        AppUser appUser = RoleUtils.getAppUser();
        if (appUser == null) {
            return AjaxResult.error("请先登录");
        }
        if (!StringUtil.IS_COMPANY_USER.equals(appUser.getIsCompanyUser())) {
            return AjaxResult.error("仅企业用户可报名招聘会");
        }

        // 3. 获取企业信息
        String companyCode = appUser.getIdCard();
        if (StringUtils.isBlank(companyCode)) {
            return AjaxResult.error("企业信息不完整，请先完善企业信息");
        }
        Company company = companyService.queryCodeCompany(companyCode);
        if (company == null) {
            return AjaxResult.error("未找到企业信息");
        }

        String jobFairId = signUpVO.getJobFairId();
        Long companyId = company.getCompanyId();

        // 4. 检查企业是否已报名该招聘会
        List<com.ruoyi.cms.domain.rc.PublicJobFairCompanyVO> existCompanies = publicJobFairMapper.selectCompanyListByJobFairId(jobFairId);
        boolean alreadySignUp = existCompanies.stream().anyMatch(c -> companyId.equals(c.getCompanyId()));
        if (alreadySignUp) {
            return AjaxResult.error("您的企业已报名该招聘会，请勿重复报名");
        }

        // 5. 创建企业-招聘会关联 (public_job_fair_company)
        PublicJobFairCompany fairCompany = new PublicJobFairCompany();
        fairCompany.setId(IdUtil.simpleUUID());
        fairCompany.setJobFairId(jobFairId);
        fairCompany.setCompanyId(companyId);
        fairCompany.setCreateTime(new Date());
        publicJobFairMapper.insertJobFairCompany(fairCompany);

        // 6. 批量插入岗位到job表，并创建岗位-招聘会关联
        List<Job> jobList = signUpVO.getJobList();
        List<PublicJobFairJob> fairJobList = new ArrayList<>();
        
        for (Job job : jobList) {
            // 插入岗位
            job.setJobId(null);
            job.setCompanyId(companyId);
            job.setCompanyName(company.getName());
            job.setIsPublish(1);
            job.setView(0L);
            job.setApplyNum(0);
            jobMapper.insert(job);

            // 创建岗位-招聘会关联
            PublicJobFairJob fairJob = new PublicJobFairJob();
            fairJob.setId(IdUtil.simpleUUID());
            fairJob.setJobFairId(jobFairId);
            fairJob.setJobId(job.getJobId());
            fairJob.setCompanyId(companyId);
            fairJob.setCreateTime(new Date());
            fairJobList.add(fairJob);
        }

        // 批量插入岗位-招聘会关联
        if (!fairJobList.isEmpty()) {
            publicJobFairMapper.insertJobFairJobBatch(fairJobList);
        }

        return AjaxResult.success("报名成功", jobList.size());
    }
}
