package org.dromara.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.main.domain.MainBackCandidate;
import org.dromara.main.domain.MainPosition;
import org.dromara.main.mapper.MainBackCandidateMapper;
import org.dromara.main.mapper.MainPositionMapper;
import org.dromara.main.service.IMainBackCandidateService;
import org.dromara.system.domain.SysTenant;
import org.dromara.system.mapper.SysTenantMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 背调候选人Service实现
 */
@RequiredArgsConstructor
@Service
public class MainBackCandidateServiceImpl implements IMainBackCandidateService {

    private final MainBackCandidateMapper mainBackCandidateMapper;
    private final MainPositionMapper mainPositionMapper;
    private final SysTenantMapper sysTenantMapper;

    @Override
    public List<Map<String, Object>> getStudentOfferList(Long studentId) {
        LambdaQueryWrapper<MainBackCandidate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MainBackCandidate::getStudentId, studentId)
               .eq(MainBackCandidate::getDelFlag, "0")
               .orderByDesc(MainBackCandidate::getCreateTime);
        List<MainBackCandidate> list = mainBackCandidateMapper.selectList(wrapper);

        // 批量查询岗位名称和企业名称
        List<Long> postIds = list.stream().map(MainBackCandidate::getPostId).distinct().collect(Collectors.toList());
        List<String> tenantIds = list.stream().map(MainBackCandidate::getTenantId).distinct().collect(Collectors.toList());

        Map<Long, String> postNameMap = new HashMap<>();
        if (!postIds.isEmpty()) {
            List<MainPosition> positions = mainPositionMapper.selectByIds(postIds);
            postNameMap.putAll(positions.stream()
                .collect(Collectors.toMap(MainPosition::getId, MainPosition::getPostName, (v1, v2) -> v1)));
        }

        Map<String, String> companyNameMap = new HashMap<>();
        for (String tenantId : tenantIds) {
            SysTenant tenant = sysTenantMapper.selectOne(new LambdaQueryWrapper<SysTenant>()
                .eq(SysTenant::getTenantId, tenantId));
            if (tenant != null) {
                companyNameMap.put(tenantId, tenant.getCompanyName());
            }
        }

        // 组装返回数据
        return list.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("postId", item.getPostId());
            map.put("postName", postNameMap.getOrDefault(item.getPostId(), "未知岗位"));
            map.put("tenantId", item.getTenantId());
            map.put("companyName", companyNameMap.getOrDefault(item.getTenantId(), "未知企业"));
            map.put("studentId", item.getStudentId());
            map.put("enterpriseStatus", item.getEnterpriseStatus());
            map.put("studentStatus", item.getStudentStatus());
            map.put("offerFileUrl", item.getOfferFileUrl());
            map.put("offerFileName", item.getOfferFileName());
            map.put("offerTime", item.getOfferTime());
            map.put("studentReplyTime", item.getStudentReplyTime());
            map.put("remark", item.getRemark());
            map.put("createTime", item.getCreateTime());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public Boolean acceptOffer(Long id, Long studentId) {
        MainBackCandidate candidate = mainBackCandidateMapper.selectById(id);
        if (candidate == null) {
            throw new ServiceException("候选记录不存在");
        }
        if (!candidate.getStudentId().equals(studentId)) {
            throw new ServiceException("无权操作该记录");
        }
        if (!"adopted".equals(candidate.getEnterpriseStatus())) {
            throw new ServiceException("企业未发出Offer，无法接受");
        }
        if (!"pending".equals(candidate.getStudentStatus())) {
            throw new ServiceException("已处理过该Offer");
        }

        MainBackCandidate update = new MainBackCandidate();
        update.setId(id);
        update.setStudentStatus("accepted");
        update.setStudentReplyTime(LocalDateTime.now());
        // 同时更新旧status字段保持兼容
        update.setStatus("adopted");

        return mainBackCandidateMapper.updateById(update) > 0;
    }

    @Override
    public Boolean rejectOffer(Long id, Long studentId) {
        MainBackCandidate candidate = mainBackCandidateMapper.selectById(id);
        if (candidate == null) {
            throw new ServiceException("候选记录不存在");
        }
        if (!candidate.getStudentId().equals(studentId)) {
            throw new ServiceException("无权操作该记录");
        }
        if (!"adopted".equals(candidate.getEnterpriseStatus())) {
            throw new ServiceException("企业未发出Offer");
        }
        if (!"pending".equals(candidate.getStudentStatus())) {
            throw new ServiceException("已处理过该Offer");
        }

        MainBackCandidate update = new MainBackCandidate();
        update.setId(id);
        update.setStudentStatus("rejected");
        update.setStudentReplyTime(LocalDateTime.now());
        // 同时更新旧status字段保持兼容
        update.setStatus("rejected");

        return mainBackCandidateMapper.updateById(update) > 0;
    }
}
