package org.dromara.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.main.domain.MainPosition;
import org.dromara.main.domain.bo.MainPositionBo;
import org.dromara.main.domain.vo.MainPositionVo;
import org.dromara.main.mapper.MainPositionMapper;
import org.dromara.main.service.IMainPositionService;
import org.dromara.main.service.IMainStudentDislikeService;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.mapper.SysTenantMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 岗位Service业务层处理
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MainPositionServiceImpl extends ServiceImpl<MainPositionMapper, MainPosition> implements IMainPositionService {

    private final MainPositionMapper baseMapper;

    private final SysTenantMapper tenantMapper;

    private final IMainStudentDislikeService studentDislikeService;
    /**
     * 查询岗位分页列表
     */
    @Override
    public Page<MainPositionVo> queryPageList(MainPositionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainPosition> lqw = buildQueryWrapper(bo);
        if (bo.getStudentId() != null) {
            List<Long> dislikedPositionIds = studentDislikeService.getDislikedPositionIds(bo.getStudentId());
            List<String> dislikedTenantIds = studentDislikeService.getDislikedTenantIds(bo.getStudentId());
            if (!dislikedPositionIds.isEmpty()) {
                lqw.notIn(MainPosition::getId, dislikedPositionIds);
            }
            if (!dislikedTenantIds.isEmpty()) {
                lqw.notIn(MainPosition::getTenantId, dislikedTenantIds);
            }
        }
        Page<MainPositionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw, MainPositionVo.class);

        log.info("查询岗位列表，共 {} 条", result.getTotal());
        // 批量补全企业名称（根据 tenantId 查询 sys_tenant）
        if (result.getTotal() > 0) {
            result.getRecords().forEach(vo -> {
                SysTenantVo tenant = tenantMapper.selectVoOne(new LambdaQueryWrapper<org.dromara.system.domain.SysTenant>().eq(org.dromara.system.domain.SysTenant::getTenantId, vo.getTenantId()));
                if (tenant != null) {
                    vo.setCompanyName(tenant.getCompanyName());
                } else if ("000000".equals(vo.getTenantId())) {
                    vo.setCompanyName("平台推荐");
                } else {
                    vo.setCompanyName("未知企业");
                }
            });
        }
        return result;
    }

    /**
     * 查询岗位详情
     */
    @Override
    public MainPositionVo queryById(Long id) {
        MainPosition position = baseMapper.selectById(id);
        MainPositionVo vo = MapstructUtils.convert(position, MainPositionVo.class);
        if (vo != null && StringUtils.isNotBlank(vo.getTenantId())) {
            SysTenantVo tenant = tenantMapper.selectVoOne(new LambdaQueryWrapper<org.dromara.system.domain.SysTenant>().eq(org.dromara.system.domain.SysTenant::getTenantId, vo.getTenantId()));
            if (tenant != null) {
                vo.setCompanyName(tenant.getCompanyName());
            } else if ("000000".equals(vo.getTenantId())) {
                vo.setCompanyName("平台推荐");
            } else {
                vo.setCompanyName("未知企业");
            }
        }
        return vo;
    }

    /**
     * 新增岗位
     */
    @Override
    public Boolean insertPosition(MainPositionBo bo) {
        MainPosition position = MapstructUtils.convert(bo, MainPosition.class);
        validEntityBeforeSave(position);
        return baseMapper.insert(position) > 0;
    }

    /**
     * 修改岗位
     */
    @Override
    public Boolean updatePosition(MainPositionBo bo) {
        MainPosition position = MapstructUtils.convert(bo, MainPosition.class);
        validEntityBeforeSave(position);
        return baseMapper.updateById(position) > 0;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<MainPosition> buildQueryWrapper(MainPositionBo bo) {
        LambdaQueryWrapper<MainPosition> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), MainPosition::getTenantId, bo.getTenantId());
//        搜索栏查询
        lqw.like(StringUtils.isNotBlank(bo.getPostName()), MainPosition::getPostName, bo.getPostName());
//        岗位类型筛选
        lqw.eq(StringUtils.isNotBlank(bo.getPostType()), MainPosition::getPostType, bo.getPostType());
//        学历要求查询
        lqw.eq(StringUtils.isNotBlank(bo.getSchoolRequirement()),MainPosition::getSchoolRequirement,bo.getSchoolRequirement());
//        经验要求筛选
        lqw.eq(StringUtils.isNotBlank(bo.getGradeRequirement()),MainPosition::getGradeRequirement,bo.getGradeRequirement());
//
        lqw.eq(StringUtils.isNotBlank(bo.getWorkProvince()), MainPosition::getWorkProvince, bo.getWorkProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkCity()), MainPosition::getWorkCity, bo.getWorkCity());
        lqw.eq(StringUtils.isNotBlank(bo.getPostLevel()), MainPosition::getPostLevel, bo.getPostLevel());
        lqw.eq(bo.getIsUrgent() != null, MainPosition::getIsUrgent, bo.getIsUrgent());

        // 排序规则
        lqw.orderByDesc(MainPosition::getCreateTime);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MainPosition entity) {
        // 可以添加业务校验逻辑
    }
}
