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

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.cms.domain.Job;
import com.ruoyi.cms.domain.rc.*;
import com.ruoyi.cms.mapper.rc.PublicJobFairMapper;
import com.ruoyi.cms.service.rc.IPublicJobFairService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公共招聘会Service实现
 */
@Slf4j
@Service
public class PublicJobFairServiceImpl implements IPublicJobFairService {

    @Autowired
    private PublicJobFairMapper publicJobFairMapper;

    @Override
    public PublicJobFairResponse getJobFairPage(PublicJobFairQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<PublicJobFair> list = publicJobFairMapper.selectPublicJobFairList(query);
        PageInfo<PublicJobFair> pageInfo = new PageInfo<>(list);

        PublicJobFairResponse response = new PublicJobFairResponse();
        response.setCode(200);

        PublicJobFairResponse.PageData pageData = new PublicJobFairResponse.PageData();
        pageData.setTotal(pageInfo.getTotal());
        pageData.setList(list);
        pageData.setPageNum(pageInfo.getPageNum());
        pageData.setPageSize(pageInfo.getPageSize());
        pageData.setSize(pageInfo.getSize());
        pageData.setStartRow((int) pageInfo.getStartRow());
        pageData.setEndRow((int) pageInfo.getEndRow());
        pageData.setPages(pageInfo.getPages());
        pageData.setPrePage(pageInfo.getPrePage());
        pageData.setNextPage(pageInfo.getNextPage());
        pageData.setIsFirstPage(pageInfo.isIsFirstPage());
        pageData.setIsLastPage(pageInfo.isIsLastPage());
        pageData.setHasPreviousPage(pageInfo.isHasPreviousPage());
        pageData.setHasNextPage(pageInfo.isHasNextPage());
        pageData.setNavigatePages(pageInfo.getNavigatePages());
        pageData.setNavigatepageNums(Arrays.stream(pageInfo.getNavigatepageNums()).boxed().collect(Collectors.toList()));
        pageData.setNavigateFirstPage(pageInfo.getNavigateFirstPage());
        pageData.setNavigateLastPage(pageInfo.getNavigateLastPage());

        response.setData(pageData);
        return response;
    }

    @Override
    public PublicJobFairDetail getJobFairDetail(String jobFairId) {
        PublicJobFairDetail detail = publicJobFairMapper.selectPublicJobFairDetailById(jobFairId);
        if (detail == null) {
            return null;
        }

        // 获取当前登录用户ID
        Long userId = null;
        try {
            if (SiteSecurityUtils.isLogin()) {
                userId = SiteSecurityUtils.getUserId();
            }
        } catch (Exception e) {
            // 未登录，忽略
        }

        // 检查用户是否已报名
        if (userId != null) {
            Integer count = publicJobFairMapper.checkUserSignUp(jobFairId, userId);
            detail.setIsSignUp(count != null && count > 0 ? 1 : 0);
        } else {
            detail.setIsSignUp(0);
        }

        return detail;
    }

    @Override
    public List<PublicJobFairCompanyVO> getEnterprisesWithJobs(String jobFairId) {
        List<PublicJobFairCompanyVO> companyList = publicJobFairMapper.selectCompanyListByJobFairId(jobFairId);
        
        if (companyList != null && !companyList.isEmpty()) {
            for (PublicJobFairCompanyVO company : companyList) {
                List<Job> jobList = publicJobFairMapper.selectJobListByJobFairIdAndCompanyId(jobFairId, company.getCompanyId());
                company.setJobInfoList(jobList);
            }
        }
        return companyList;
    }

    // ========== CMS后台管理接口实现 ==========

    @Override
    public List<PublicJobFair> selectList(PublicJobFairQuery query) {
        return publicJobFairMapper.selectPublicJobFairList(query);
    }

    @Override
    public PublicJobFair selectById(String jobFairId) {
        PublicJobFair jobFair = publicJobFairMapper.selectPublicJobFairById(jobFairId);
        if (jobFair != null) {
            // 查询关联的企业及岗位
            List<PublicJobFairCompanyVO> companyList = getEnterprisesWithJobs(jobFairId);
            jobFair.setCompanyList(companyList);
        }
        return jobFair;
    }

    @Override
    @Transactional
    public int insert(PublicJobFair publicJobFair) {
        publicJobFair.setJobFairId(IdUtils.fastSimpleUUID());
        publicJobFair.setCreateTime(new Date());
        publicJobFair.setCreateBy(SecurityUtils.getUsername());
        return publicJobFairMapper.insertPublicJobFair(publicJobFair);
    }

    @Override
    @Transactional
    public int update(PublicJobFair publicJobFair) {
        publicJobFair.setUpdateTime(new Date());
        publicJobFair.setUpdateBy(SecurityUtils.getUsername());
        return publicJobFairMapper.updatePublicJobFair(publicJobFair);
    }

    @Override
    @Transactional
    public int deleteByIds(String[] jobFairIds) {
        return publicJobFairMapper.deletePublicJobFairByIds(jobFairIds);
    }

    @Override
    @Transactional
    public int addCompany(PublicJobFairCompany company) {
        company.setId(IdUtils.fastSimpleUUID());
        company.setCreateTime(new Date());
        company.setCreateBy(SecurityUtils.getUsername());
        return publicJobFairMapper.insertJobFairCompany(company);
    }

    @Override
    @Transactional
    public int addCompanyBatch(List<PublicJobFairCompany> companies) {
        String username = SecurityUtils.getUsername();
        Date now = new Date();
        for (PublicJobFairCompany company : companies) {
            company.setId(IdUtils.fastSimpleUUID());
            company.setCreateTime(now);
            company.setCreateBy(username);
        }
        return publicJobFairMapper.insertJobFairCompanyBatch(companies);
    }

    @Override
    @Transactional
    public int removeCompany(String id) {
        return publicJobFairMapper.deleteJobFairCompanyById(id);
    }

    @Override
    @Transactional
    public int addJob(PublicJobFairJob job) {
        job.setId(IdUtils.fastSimpleUUID());
        job.setCreateTime(new Date());
        job.setCreateBy(SecurityUtils.getUsername());
        return publicJobFairMapper.insertJobFairJob(job);
    }

    @Override
    @Transactional
    public int addJobBatch(List<PublicJobFairJob> jobs) {
        String username = SecurityUtils.getUsername();
        Date now = new Date();
        for (PublicJobFairJob job : jobs) {
            job.setId(IdUtils.fastSimpleUUID());
            job.setCreateTime(now);
            job.setCreateBy(username);
        }
        return publicJobFairMapper.insertJobFairJobBatch(jobs);
    }

    @Override
    @Transactional
    public int removeJob(String id) {
        return publicJobFairMapper.deleteJobFairJobById(id);
    }

    @Override
    public List<JobFairSignUpVO> selectSignUpList(String jobFairId) {
        return publicJobFairMapper.selectSignUpListByJobFairId(jobFairId);
    }
}
