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.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ruoyi.bgt.bo.BgtProjectRecruitApplyQueryBo;
import com.ruoyi.bgt.domain.BgtMessage;
import com.ruoyi.bgt.domain.BgtProjectRecruit;
import com.ruoyi.bgt.domain.BgtProjectRecruitApply;
import com.ruoyi.bgt.domain.dto.*;
import com.ruoyi.bgt.domain.vo.BgtProjectRecruitApplyVO;
import com.ruoyi.bgt.mapper.BgtProjectRecruitApplyMapper;
import com.ruoyi.bgt.service.IBgtMessageService;
import com.ruoyi.bgt.service.IBgtProjectRecruitApplyService;
import com.ruoyi.bgt.service.IBgtProjectRecruitService;
import com.ruoyi.common.constants.WgzAndBgtMessageConstant;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.domain.dto.AnnexDTO;
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.system.service.ISysDictTypeService;
import com.ruoyi.wgz.bo.req.WgzAppConfirmRegistrationReq;
import com.ruoyi.wgz.bo.req.WgzAppUnderwayReq;
import com.ruoyi.wgz.bo.res.WgzAppUnderwayRes;
import com.ruoyi.wgz.domain.WgzMessage;
import com.ruoyi.wgz.domain.WgzScoreRecord;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.service.IWgzMessageService;
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.*;

import static com.ruoyi.common.constants.WgzAndBgtMessageConstant.*;

/**
 * 包工头招工申请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;
	@Autowired
	private IBgtProjectRecruitService iBgtProjectRecruitService;
	@Autowired
	private IWgzMessageService iWgzMessageService;
	@Autowired
	private IBgtMessageService iBgtMessageService;
	@Autowired
	private IWgzMessageService wgzMessageService;
	@Autowired
	private ISysDictTypeService dictTypeService;

    @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 TableDataInfo<BgtProjectRecruitApplyVO> appQueryPageList(BgtProjectRecruitApplyQueryDTO dto) {
		if(dto.getTaskId()!=null){
			List<Long> recruitIdsByTaskId = iBgtProjectRecruitService.getRecruitIdsByTaskId(dto.getTaskId());
			if(dto.getRecruitIds()==null){
				dto.setRecruitIds(recruitIdsByTaskId);
			}else {
				dto.getRecruitIds().addAll(recruitIdsByTaskId);
			}
		}

		Page<BgtProjectRecruitApplyQueryDTO> queryDTOPage = new Page<>();
		queryDTOPage.setCurrent(dto.getPageNum());
		queryDTOPage.setSize(dto.getPageSize());
		Page<BgtProjectRecruitApplyVO> queryVOPage = baseMapper.appQueryList(queryDTOPage, dto);
		return PageUtils.buildDataInfo(queryVOPage);
	}

	@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());
		for (AnnexDTO annexDTO : dto.getEntryMaterials()) {
			annexDTO.setRecruitId(recruitApply.getRecruitId());
		}
		annexService.insertBatch(dto.getEntryMaterials());
		//发消息
		HashMap<String, String> mp = new HashMap<>();
		mp.put("projectName",iBgtProjectRecruitService.getById(recruitApply.getRecruitId()).getRecruitName());
		mp.put("auditor",SecurityUtils.getUsername());
		Map<String, String> map = bgtMessage(mp, BGT_TYPE_SIGN_UP, true);
		WgzMessage wgzMessage = new WgzMessage()
			.setSenderType(USERTYPE_BGT)
			.setRecipientType(USERTYPE_WGZ)
			.setRecipientId(recruitApply.getUserId())
			.setHeadline(map.get(HEADLINE))
			.setSubheading(map.get(SUBHEADING))
			.setTableId(recruitApply.getId())
			.setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName())
			.setMessageLargeType(LARGE_APPLY)
			.setMessageSmallType(SMALL_SYSTEM);
		wgzMessageService.sendAMessage(wgzMessage);
		return updateById(recruitApply);
	}




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

	/**
	 * 根据用户唯一标识去查询当前进场的工地信息
	 */
	@Override
	public BgtProjectRecruitApply selectByUserIdProjectRecruitApplyId(Long id) {
		String[] strings = {"3","5"};
		LambdaQueryWrapper<BgtProjectRecruitApply> lqw = Wrappers.lambdaQuery();
		lqw.eq(BgtProjectRecruitApply::getUserId, id).
			in(BgtProjectRecruitApply::getStatus, strings); //包工头+务工者同意 or 进场 才算进场ok
		List<BgtProjectRecruitApply> bgtProjectRecruitApplies = baseMapper.selectList(lqw);
		if (bgtProjectRecruitApplies.isEmpty()){
			throw new RuntimeException("异常，还未查询到您进入了工地！");
		}
		if (bgtProjectRecruitApplies.size()>1){
			throw new RuntimeException("异常，查询到用户同时在多个工地务工！");
		}
		return bgtProjectRecruitApplies.get(0);
	}

	@Override
	@Transactional
	public Boolean userApplyForRegistration(Long id) {
		//1、获取当前用户
		Long appUserId = SecurityUtils.getAppUserId();
		//2、当前申请报名的工地信息
		BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(id);
		//3、检查当前用户是否已经有工地了、检查当前用户是否满足对应工种
		Integer i = baseMapper.selectCount(
			new LambdaQueryWrapper<BgtProjectRecruitApply>().
			eq(BgtProjectRecruitApply::getUserId, appUserId).
			in(BgtProjectRecruitApply::getStatus, "3","5")
		);
		if (i>0){
			throw new RuntimeException("已有工地！不可再次申请！");
		}
		WgzUser byId = wgzUserService.findByUserId(appUserId);
		if (!Objects.equals(appById.getTypeOfWork(), byId.getTypeOfWork())){
			throw new RuntimeException("工种不匹配！");
		}
		//4、判断当前用户是否已经申请过了，如果已经申请过了，就不能再次申请了
		Integer integer = baseMapper.selectCount(
			new LambdaQueryWrapper<BgtProjectRecruitApply>().
			eq(BgtProjectRecruitApply::getUserId, appUserId).
			eq(BgtProjectRecruitApply::getRecruitId, id)
		);
		if (integer>0){
			throw new RuntimeException("已申请过了！不可再次申请！");
		}
		//3、插入数据
		BgtProjectRecruitApply bgtProjectRecruitApply = new BgtProjectRecruitApply();
		bgtProjectRecruitApply.setRecruitId(id);
		bgtProjectRecruitApply.setUserId(appUserId);
		int insert = baseMapper.insert(bgtProjectRecruitApply);
		//4、发送消息
		if (insert>0){
			SysDictData typeOfWork = dictTypeService.selectDictDataByTypeAndData("type_of_work", byId.getTypeOfWork());
			Map<String, String> mp = new HashMap<>();
			mp.put("projectName",appById.getRecruitName());
			mp.put("userName",byId.getUsername());
			mp.put("post",typeOfWork.getDictLabel());
			//4-1、系统发送消息给当前用户
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(appUserId).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"101")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"102")).
				setTableId(bgtProjectRecruitApply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(LARGE_OTHER).
				setMessageSmallType(SMALL_SYSTEM);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统消息发送失败！");
			}
			//4-2、当前用户发送消息给包工头
			BgtMessage bgtMessage = new BgtMessage().
				setSenderType(USERTYPE_WGZ).
				setSenderId(appUserId).
				setRecipientType(USERTYPE_BGT).
				setRecipientId(appById.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"201")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"202")).
				setTableId(bgtProjectRecruitApply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(BGT_LARGE).
				setMessageSmallType(BGT_TYPE_SIGN_UP);
			if (!iBgtMessageService.sendAMessage(bgtMessage)){
				throw new RuntimeException("发送消息失败！");
			}
		}
		return false;
	}

	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 recruitApplyId) {
		BgtProjectRecruitApply bgtProjectRecruitApply = new BgtProjectRecruitApply();
		bgtProjectRecruitApply.setId(recruitApplyId);
		bgtProjectRecruitApply.setStatus("7");
		if(baseMapper.updateById(bgtProjectRecruitApply) >0){
			Long appUserId = SecurityUtils.getAppUserId();
			BgtProjectRecruitApply by = selectByUserIdProjectRecruitApplyId(appUserId);
			BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(by.getUserId());
			Map<String, String> mp = new HashMap<>();
			mp.put("projectName",appById.getRecruitName());
			//发送取消报名的系统消息
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(appUserId).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"103")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"104")).
				setTableId(bgtProjectRecruitApply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(LARGE_OTHER).
				setMessageSmallType(SMALL_SYSTEM);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统消息发送失败！");
			}
			return true;
		}
		return false;
	}


	@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));
	}

	@Override
	public Boolean userConfirmRegistration(WgzAppConfirmRegistrationReq req) {
		//1、获取当前用户
		WgzUser byUserId = wgzUserService.findByUserId(SecurityUtils.getAppUserId());
		//2、当前申请报名的工地信息
		BgtProjectRecruitApply recruitApply = queryById(req.getRecruitApplyId());
		BgtProjectRecruit recruit = iBgtProjectRecruitService.getAppById(recruitApply.getId());
		//3、更新报名状态
		BgtProjectRecruitApply apply = new BgtProjectRecruitApply();
		apply.setId(req.getRecruitApplyId());
		apply.setStatus(req.getStatus());
		int insert = baseMapper.insert(apply);
		if (insert == 0){
			throw new RuntimeException("插入数据失败！");
		}
		//4系统拒绝消息
		SysDictData typeOfWork = dictTypeService.selectDictDataByTypeAndData("type_of_work", recruit.getTypeOfWork());
		Map<String, String> mp = new HashMap<>();
		mp.put("projectName",recruit.getRecruitName());
		mp.put("userName",byUserId.getUsername());
		mp.put("post",typeOfWork.getDictLabel());
		if (req.getStatus().equals("3")){
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(byUserId.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"105")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"106")).
				setTableId(apply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(LARGE_APPLY);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统消息报名拒绝发送失败！");
			}
			BgtMessage bgtMessage = new BgtMessage().
				setSenderType(USERTYPE_WGZ).
				setSenderId(byUserId.getUserId()).
				setRecipientType(USERTYPE_BGT).
				setRecipientId(apply.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"203")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"204")).
				setTableId(apply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(BGT_LARGE).
				setMessageSmallType(BGT_TYPE_SIGN_UP);
			if (!iBgtMessageService.sendAMessage(bgtMessage)){
				throw new RuntimeException("发送报名拒绝消息失败！");
			}
			return true;
		}
		//系统同意消息
		if (req.getStatus().equals("4")){
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(byUserId.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"107")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"108")).
				setTableId(apply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(LARGE_APPLY);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统消息报名同意发送失败！");
			}
			BgtMessage bgtMessage = new BgtMessage().
				setSenderType(USERTYPE_WGZ).
				setSenderId(byUserId.getUserId()).
				setRecipientType(USERTYPE_BGT).
				setRecipientId(apply.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"205")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"206")).
				setTableId(apply.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(BGT_LARGE).
				setMessageSmallType(BGT_TYPE_SIGN_UP);
			if (!iBgtMessageService.sendAMessage(bgtMessage)){
				throw new RuntimeException("发送报名同意消息失败！");
			}
			return true;
		}
		return false;
	}

}
