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.injector.methods.DeleteById;
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.BgtAttendanceDayDTO;
import com.ruoyi.bgt.domain.dto.BgtProjectRecruitApplyConsentDTO;
import com.ruoyi.bgt.domain.dto.BgtProjectRecruitApplyQueryDTO;
import com.ruoyi.bgt.domain.dto.BgtScoreDTO;
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 com.ruoyi.wgz.bo.req.WgzAppRegisteredProjectReq;
import com.ruoyi.wgz.bo.req.WgzAppUnderwayReq;
import com.ruoyi.wgz.bo.res.WgzAppUnderwayRes;
import com.ruoyi.wgz.domain.WgzScoreRecord;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.service.IWgzScoreRecordService;
import com.ruoyi.wgz.service.IWgzUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.Arrays;
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;
	@Autowired
	private IWgzScoreRecordService scoreRecordService;
	@Autowired
	private IWgzUserService wgzUserService;

    @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())
			.in(BgtProjectRecruitApply::getStatus, Arrays.asList(RecruitApplyStatus.WGZ_PASS.getCode(), RecruitApplyStatus.WORKING.getCode()))
			.isNotNull(BgtProjectRecruitApply::getLeaveTime));

		if(CollectionUtil.isNotEmpty(list)){
			throw new BaseException("该务工者已进入其他工地");
		}
		recruitApply.setEntryTime(dto.getEntryTime());
		recruitApply.setStatus(RecruitApplyStatus.BGT_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, "3"); //包工头同意、务工者同意才算进场ok
//			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、检查当前用户是否已经有工地了、检查当前用户是否满足对应工种
		Integer i = baseMapper.selectCount(
			new LambdaQueryWrapper<BgtProjectRecruitApply>().
			eq(BgtProjectRecruitApply::getUserId, appUserId).
			eq(BgtProjectRecruitApply::getStatus, "3")
//			isNotNull(BgtProjectRecruitApply::getEntryTime).ne(BgtProjectRecruitApply::getEntryTime, "")
		);
		if (i>0){
			throw new RuntimeException("已有工地！不可再次申请！");
		}
		//2、插入数据
		BgtProjectRecruitApply bgtProjectRecruitApply = new BgtProjectRecruitApply();
		bgtProjectRecruitApply.setRecruitId(id);
		bgtProjectRecruitApply.setUserId(appUserId);
		return baseMapper.insert(bgtProjectRecruitApply) >0;
	}

	public List<BgtProjectRecruitApplyVO> todayAttendanceList(BgtAttendanceDayDTO dto){
		return baseMapper.todayAttendanceList(dto);
	}

	@Override
	public Boolean quit(Long id) {
		return super.lambdaUpdate().eq(BgtProjectRecruitApply::getId, id)
			.set(BgtProjectRecruitApply::getLeaveTime, LocalDate.now())
			.set(BgtProjectRecruitApply::getStatus, RecruitApplyStatus.OUT_WORK.getCode())
			.update();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean score(BgtScoreDTO dto) {
		dto.setScoreBy(SecurityUtils.getAppUserId());
		Boolean insert = scoreRecordService.insert(BeanUtil.copyProperties(dto, WgzScoreRecord.class));

		List<WgzScoreRecord> wgzScoreRecords = scoreRecordService.getBaseMapper().selectList(Wrappers.<WgzScoreRecord>lambdaQuery()
			.eq(WgzScoreRecord::getUserId, dto.getUserId()));
		double rawNewScore = wgzScoreRecords.stream()
			.mapToDouble(WgzScoreRecord::getScore)
			.sum();
		// 使用 DecimalFormat 格式化结果
		DecimalFormat df = new DecimalFormat("#.0");
		String formatted = df.format(rawNewScore);
		Double newScore = Double.parseDouble(formatted);
		//更新务工者
		wgzUserService.lambdaUpdate().set(WgzUser::getScore, newScore).eq(WgzUser::getUserId, dto.getUserId()).update();
		return insert;
	}
	@Override
	@Transactional
	public Boolean userCancelRegistration(Long recruitId) {
		return baseMapper.deleteById(new LambdaQueryWrapper<BgtProjectRecruitApply>().eq(BgtProjectRecruitApply::getRecruitId, recruitId)) >0;
	}


	@Override
	public TableDataInfo<WgzAppUnderwayRes> userUnderway(WgzAppUnderwayReq req) {
		req.setUserId(SecurityUtils.getAppUserId());
		Page<WgzAppUnderwayReq> pe = new Page<>();
		pe.setCurrent(req.getPageNum());
		pe.setSize(req.getPageSize());
		return PageUtils.buildDataInfo(baseMapper.underwayPage(pe));
	}

}
