package com.ruoyi.bgt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.ruoyi.bgt.bo.BgtProjectRecruitApplyQueryBo;
import com.ruoyi.bgt.domain.BgtProjectRecruitApply;
import com.ruoyi.bgt.domain.dto.BgtProjectRecruitApplyConsentDTO;
import com.ruoyi.bgt.domain.dto.BgtProjectRecruitApplyQueryDTO;
import com.ruoyi.bgt.domain.vo.BgtProjectRecruitApplyVO;
import com.ruoyi.bgt.mapper.BgtProjectRecruitApplyMapper;
import com.ruoyi.bgt.service.IBgtProjectRecruitApplyService;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.RecruitApplyStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.service.IAnnexService;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 包工头招工申请Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class BgtProjectRecruitApplyServiceImpl extends ServicePlusImpl<BgtProjectRecruitApplyMapper, BgtProjectRecruitApply> implements IBgtProjectRecruitApplyService {


	@Autowired
	private IAnnexService annexService;

    @Override
    public BgtProjectRecruitApply queryById(Long id){
        return getById(id);
    }

    @Override
    public TableDataInfo<BgtProjectRecruitApply> queryPageList(BgtProjectRecruitApplyQueryBo bo) {
        Page<BgtProjectRecruitApply> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<BgtProjectRecruitApply> queryList(BgtProjectRecruitApplyQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<BgtProjectRecruitApply> buildQueryWrapper(BgtProjectRecruitApplyQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BgtProjectRecruitApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRecruitId() != null, BgtProjectRecruitApply::getRecruitId, bo.getRecruitId());
        lqw.eq(bo.getUserId() != null, BgtProjectRecruitApply::getUserId, bo.getUserId());
        return lqw;
    }

    @Override
    public Boolean insert(BgtProjectRecruitApply bo) {
        BgtProjectRecruitApply add = BeanUtil.toBean(bo, BgtProjectRecruitApply.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(BgtProjectRecruitApply bo) {
        BgtProjectRecruitApply update = BeanUtil.toBean(bo, BgtProjectRecruitApply.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(BgtProjectRecruitApply entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	@Override
	public List<BgtProjectRecruitApplyVO> appQueryList(BgtProjectRecruitApplyQueryDTO dto) {
		return baseMapper.appQueryList(dto);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean consent(BgtProjectRecruitApplyConsentDTO dto) {

		BgtProjectRecruitApply recruitApply = getById(dto.getId());
		List<BgtProjectRecruitApply> list = baseMapper.selectList(Wrappers.<BgtProjectRecruitApply>lambdaQuery()
			.eq(BgtProjectRecruitApply::getUserId, recruitApply.getUserId())
			.eq(BgtProjectRecruitApply::getStatus,RecruitApplyStatus.PASS.getCode())
			.isNotNull(BgtProjectRecruitApply::getLeaveTime));

		if(CollectionUtil.isNotEmpty(list)){
			throw new BaseException("该务工者已进入其他工地");
		}
		recruitApply.setEntryTime(dto.getEntryTime());
		recruitApply.setStatus(RecruitApplyStatus.PASS.getCode());
		dto.getEntryMaterials().addAll(dto.getInsurances());
		annexService.insertBatch(dto.getEntryMaterials());
		return updateById(recruitApply);
	}



	/**
	 * LC-APP相关
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */

	/**
	 * 根据用户唯一标识去查询当前进场的工地信息
	 */
	@Override
	public BgtProjectRecruitApply selectByUserIdProjectRecruitApplyId(Long id) {
		LambdaQueryWrapper<BgtProjectRecruitApply> lqw = Wrappers.lambdaQuery();
		lqw.eq(BgtProjectRecruitApply::getUserId, id).
			eq(BgtProjectRecruitApply::getStatus, "1").
			isNotNull(BgtProjectRecruitApply::getEntryTime).
			ne(BgtProjectRecruitApply::getEntryTime, "");
		List<BgtProjectRecruitApply> bgtProjectRecruitApplies = baseMapper.selectList(lqw);
		if (bgtProjectRecruitApplies.size()>1){
			throw new RuntimeException("异常，查询到用户同时在多个工地务工！");
		}
		return bgtProjectRecruitApplies.get(0);
	}

	@Override
	@Transactional
	public Boolean userApplyForRegistration(Long id) {
		//1、获取当前用户
		Long appUserId = SecurityUtils.getAppUserId();
		//2、插入数据
		BgtProjectRecruitApply bgtProjectRecruitApply = new BgtProjectRecruitApply();
		bgtProjectRecruitApply.setRecruitId(id);
		bgtProjectRecruitApply.setUserId(appUserId);
		return baseMapper.insert(bgtProjectRecruitApply) >0;
	}

}
