package org.dromara.main.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.MainAudit;
import org.dromara.main.domain.MainBackCandidate;
import org.dromara.main.domain.MainPostApply;
import org.dromara.main.domain.bo.MainPostApplyBo;
import org.dromara.main.domain.vo.MainPostApplyVo;
import org.dromara.main.mapper.MainAuditMapper;
import org.dromara.main.mapper.MainBackCandidateMapper;
import org.dromara.main.mapper.MainPostApplyMapper;
import org.dromara.main.service.IMainPostApplyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class MainPostApplyServiceImpl implements IMainPostApplyService {

    private final MainPostApplyMapper baseMapper;
    private final MainAuditMapper mainAuditMapper;
    private final MainBackCandidateMapper mainBackCandidateMapper;

    @Override
    public TableDataInfo<MainPostApplyVo> queryPageList(MainPostApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainPostApply> lqw = buildQueryWrapper(bo);
        Page<MainPostApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        fillApplyCount(result.getRecords());
        return TableDataInfo.build(result);
    }

    @Override
    public List<MainPostApplyVo> queryList(MainPostApplyBo bo) {
        LambdaQueryWrapper<MainPostApply> lqw = buildQueryWrapper(bo);
        List<MainPostApplyVo> list = baseMapper.selectVoList(lqw);
        fillApplyCount(list);
        return list;
    }

    @Override
    public MainPostApplyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MainPostApplyBo bo) {
        MainPostApply add = MapstructUtils.convert(bo, MainPostApply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            MainAudit audit = buildPendingAudit(add.getId(), add.getTenantId());
            mainAuditMapper.insert(audit);
            add.setAuditId(audit.getId());
            add.setApplyStatus(0);
            baseMapper.updateById(add);
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MainPostApplyBo bo) {
        MainPostApply update = MapstructUtils.convert(bo, MainPostApply.class);
        validEntityBeforeSave(update);
        update.setApplyStatus(0);
        update.setRejectReason(null);
        boolean updated = baseMapper.updateById(update) > 0;
        if (!updated) {
            return false;
        }

        if (update.getAuditId() != null) {
            LambdaUpdateWrapper<MainAudit> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(MainAudit::getId, update.getAuditId())
                .set(MainAudit::getAuditResult, 0)
                .set(MainAudit::getAuditRemark, null)
                .set(MainAudit::getAuditTime, null)
                .set(MainAudit::getAuditBy, null);
            mainAuditMapper.update(null, updateWrapper);
        } else {
            MainAudit audit = buildPendingAudit(update.getId(), update.getTenantId());
            mainAuditMapper.insert(audit);
            MainPostApply apply = new MainPostApply();
            apply.setId(update.getId());
            apply.setAuditId(audit.getId());
            baseMapper.updateById(apply);
        }
        return true;
    }

    @Override
    public Boolean publishById(Long id) {
        MainPostApply entity = new MainPostApply();
        entity.setId(id);
        entity.setStatus("0");
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public Boolean unpublishById(Long id) {
        MainPostApply entity = new MainPostApply();
        entity.setId(id);
        entity.setStatus("1");
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    private LambdaQueryWrapper<MainPostApply> buildQueryWrapper(MainPostApplyBo bo) {
        LambdaQueryWrapper<MainPostApply> lqw = Wrappers.lambdaQuery();
        lqw.like(ObjectUtil.isNotNull(bo.getApplyNo()), MainPostApply::getApplyNo, bo.getApplyNo());
        lqw.eq(ObjectUtil.isNotNull(bo.getTenantId()), MainPostApply::getTenantId, bo.getTenantId());
        lqw.like(ObjectUtil.isNotNull(bo.getPostName()), MainPostApply::getPostName, bo.getPostName());
        lqw.like(ObjectUtil.isNotNull(bo.getCompanyName()), MainPostApply::getCompanyName, bo.getCompanyName());
        lqw.eq(ObjectUtil.isNotNull(bo.getApplyStatus()), MainPostApply::getApplyStatus, bo.getApplyStatus());
        lqw.eq(ObjectUtil.isNotNull(bo.getPostType()), MainPostApply::getPostType, bo.getPostType());
        lqw.eq(ObjectUtil.isNotNull(bo.getIsUrgent()), MainPostApply::getIsUrgent, bo.getIsUrgent());
        lqw.eq(ObjectUtil.isNotNull(bo.getPostLevel()), MainPostApply::getPostLevel, bo.getPostLevel());
        lqw.eq(ObjectUtil.isNotNull(bo.getWorkCity()), MainPostApply::getWorkCity, bo.getWorkCity());
        lqw.orderByDesc(MainPostApply::getCreateTime);
        return lqw;
    }

    private void validEntityBeforeSave(MainPostApply entity) {
        if (entity.getRegistrationStartDate() != null && entity.getRegistrationEndDate() != null) {
            if (entity.getRegistrationStartDate().after(entity.getRegistrationEndDate())) {
                throw new ServiceException("报名开始时间不能晚于结束时间");
            }
        }

        if (entity.getRecruitNum() != null && entity.getRecruitNum() <= 0) {
            throw new ServiceException("招聘人数必须大于0");
        }

        if (entity.getGradeA() != null && (entity.getGradeA().compareTo(BigDecimal.ZERO) < 0
            || entity.getGradeA().compareTo(new BigDecimal("100")) > 0)) {
            throw new ServiceException("能力A及格分必须在0-100之间");
        }

        if (entity.getGradeB() != null && (entity.getGradeB().compareTo(BigDecimal.ZERO) < 0
            || entity.getGradeB().compareTo(new BigDecimal("100")) > 0)) {
            throw new ServiceException("能力B及格分必须在0-100之间");
        }

        if (entity.getGradeC() != null && (entity.getGradeC().compareTo(BigDecimal.ZERO) < 0
            || entity.getGradeC().compareTo(new BigDecimal("100")) > 0)) {
            throw new ServiceException("能力C及格分必须在0-100之间");
        }
    }

    private void fillApplyCount(List<MainPostApplyVo> postList) {
        if (postList == null || postList.isEmpty()) {
            return;
        }

        Set<Long> postIds = postList.stream()
            .map(MainPostApplyVo::getPostId)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        if (postIds.isEmpty()) {
            postList.forEach(item -> item.setApplyCount(0L));
            return;
        }

        QueryWrapper<MainBackCandidate> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("post_id", "COUNT(1) AS applyCount");
        queryWrapper.in("post_id", postIds);
        queryWrapper.eq("del_flag", "0");
        queryWrapper.groupBy("post_id");

        List<Map<String, Object>> countRows = mainBackCandidateMapper.selectMaps(queryWrapper);
        Map<Long, Long> countMap = countRows == null ? Collections.emptyMap() : countRows.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                row -> Long.valueOf(String.valueOf(row.get("post_id"))),
                row -> Long.valueOf(String.valueOf(row.get("applyCount"))),
                (left, right) -> left,
                HashMap::new
            ));

        postList.forEach(item -> item.setApplyCount(countMap.getOrDefault(item.getPostId(), 0L)));
    }

    private MainAudit buildPendingAudit(Long targetId, String tenantId) {
        MainAudit audit = new MainAudit();
        audit.setAuditType(2);
        audit.setTargetId(targetId);
        audit.setAuditResult(0);
        audit.setTenantId(tenantId);
        return audit;
    }
}
