package com.ruoyi.wgz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
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.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ruoyi.bgt.domain.BgtMessage;
import com.ruoyi.bgt.domain.BgtProjectRecruit;
import com.ruoyi.bgt.domain.BgtProjectRecruitApply;
import com.ruoyi.bgt.domain.dto.BgtReissueacardListDTO;
import com.ruoyi.bgt.domain.dto.BgtReissueacardUpdateDTO;
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.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.wgz.bo.WgzReissueacardQueryBo;
import com.ruoyi.wgz.bo.req.WgzAppCardReplacementApplicationReq;
import com.ruoyi.wgz.bo.req.WgzAppReplacementCardRecordReq;
import com.ruoyi.wgz.bo.res.WgzReplacementCardRecordRes;
import com.ruoyi.wgz.domain.WgzAttendance;
import com.ruoyi.wgz.domain.WgzMessage;
import com.ruoyi.wgz.domain.WgzReissueacard;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.mapper.WgzReissueacardMapper;
import com.ruoyi.wgz.service.IWgzAttendanceService;
import com.ruoyi.wgz.service.IWgzMessageService;
import com.ruoyi.wgz.service.IWgzReissueacardService;
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.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;

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

/**
 * 补卡申请Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-20
 */
@Service
public class WgzReissueacardServiceImpl extends ServicePlusImpl<WgzReissueacardMapper, WgzReissueacard> implements IWgzReissueacardService {

	@Autowired
	private IBgtProjectRecruitApplyService iBgtProjectRecruitApplyService;

	@Autowired
	private IBgtProjectRecruitService iBgtProjectRecruitService;

	@Autowired
	private IWgzAttendanceService iWgzAttendanceService;

	@Autowired
	private IWgzMessageService wgzMessageService;

	@Autowired
	private IWgzMessageService iWgzMessageService;

	@Autowired
	private IBgtMessageService iBgtMessageService;

	@Autowired
	private IWgzUserService wgzUserService;

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



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

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

    private LambdaQueryWrapper<WgzReissueacard> buildQueryWrapper(WgzReissueacardQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WgzReissueacard> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRecruitId() != null, WgzReissueacard::getRecruitId, bo.getRecruitId());
        lqw.eq(bo.getUserId() != null, WgzReissueacard::getUserId, bo.getUserId());
        lqw.eq(bo.getAttendanceId() != null, WgzReissueacard::getAttendanceId, bo.getAttendanceId());
        lqw.eq(StrUtil.isNotBlank(bo.getType()), WgzReissueacard::getType, bo.getType());
        lqw.like(StrUtil.isNotBlank(bo.getRecruitName()), WgzReissueacard::getRecruitName, bo.getRecruitName());
        lqw.eq(StrUtil.isNotBlank(bo.getRawTime()), WgzReissueacard::getRawTime, bo.getRawTime());
        lqw.eq(bo.getNowTime() != null, WgzReissueacard::getNowTime, bo.getNowTime());
        lqw.eq(StrUtil.isNotBlank(bo.getReason()), WgzReissueacard::getReason, bo.getReason());
        lqw.eq(bo.getAuditorUserId() != null, WgzReissueacard::getAuditorUserId, bo.getAuditorUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getAuditorType()), WgzReissueacard::getAuditorType, bo.getAuditorType());
        lqw.eq(StrUtil.isNotBlank(bo.getAuditorOpinion()), WgzReissueacard::getAuditorOpinion, bo.getAuditorOpinion());
        lqw.eq(bo.getAuditorTime() != null, WgzReissueacard::getAuditorTime, bo.getAuditorTime());
        return lqw;
    }

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

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

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

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

	/**
	 * APP相关
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */


	@Override
	@Transactional
	public Boolean userCardReplacementApplication(WgzAppCardReplacementApplicationReq req) {
		//1、获取当前用户信息
		Long appUserId = SecurityUtils.getAppUserId();
		BgtProjectRecruitApply recruitApply = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		BgtProjectRecruit recruit = iBgtProjectRecruitService.getAppById(recruitApply.getId());
		//4、获取到原打卡的信息
		WgzAttendance attendanceInfo = iWgzAttendanceService.findById(req.getAttendanceId());
		if (Objects.isNull(attendanceInfo)) {
			throw new RuntimeException("打卡信息不存在");
		}
		String rawTime = "";
		if (attendanceInfo.getClockInTime() == null) {
			rawTime = "缺卡";
		}else{
			rawTime = attendanceInfo.getClockInTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		}
		//5、组装补卡申请数据
		WgzReissueacard wgzReissueacard = new WgzReissueacard().
			setRecruitId(recruitApply.getRecruitId()).
			setUserId(appUserId).
			setAttendanceId(req.getAttendanceId()).
			setType(req.getType()).
			setRecruitName(recruit.getRecruitName()).
			setRawTime(rawTime).
			setNowTime(req.getNowTime()).
			setReason(req.getReason()).
			setAttendanceId(recruit.getUserId());
		int insert = baseMapper.insert(wgzReissueacard);
		//6、发送消息
		WgzUser byId = wgzUserService.findByUserId(appUserId);
		Map<String, String> mp = new HashMap<>();
		mp.put("projectName", recruit.getRecruitName());
		mp.put("userName", byId.getUsername());
		mp.put("data",String.valueOf(req.getNowTime()));
		if (insert > 0) {
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(appUserId).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"109")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"110")).
				setTableId(wgzReissueacard.getId()).
				setTableName(SqlHelper.table(WgzReissueacard.class).getTableName()).
				setMessageLargeType(LARGE_OTHER).
				setMessageSmallType(SMALL_CARD);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统补卡消息发送失败！");
			}
			BgtMessage bgtMessage = new BgtMessage().
				setSenderType(USERTYPE_WGZ).
				setSenderId(appUserId).
				setRecipientType(USERTYPE_BGT).
				setRecipientId(recruit.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"207")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"208")).
				setTableId(wgzReissueacard.getId()).
				setTableName(SqlHelper.table(BgtProjectRecruitApply.class).getTableName()).
				setMessageLargeType(BGT_LARGE).
				setMessageSmallType(BGT_TYPE_MAKE_UP);
			if (!iBgtMessageService.sendAMessage(bgtMessage)){
				throw new RuntimeException("发送补卡消息失败！");
			}
			return true;
		}
		return false;
	}


	@Override
	public TableDataInfo<WgzReplacementCardRecordRes> userReplacementCardRecord(WgzAppReplacementCardRecordReq req) {
		Long userId = SecurityUtils.getAppUserId();
		Page<WgzAppReplacementCardRecordReq> queryDTOPage = new Page<>();
		queryDTOPage.setCurrent(req.getPageNum());
		queryDTOPage.setSize(req.getPageSize());
		return PageUtils.buildDataInfo(baseMapper.userReplacementCardRecordListPage(queryDTOPage,userId));
	}

	@Override
	public TableDataInfo<WgzReplacementCardRecordRes> appQueryPageList(BgtReissueacardListDTO dto) {
		dto.setAuditorUserId(SecurityUtils.getAppUserId());
		Page<BgtReissueacardListDTO> queryDTOPage = new Page<>();
		queryDTOPage.setCurrent(dto.getPageNum());
		queryDTOPage.setSize(dto.getPageSize());
		return PageUtils.buildDataInfo(baseMapper.appQueryPageList(queryDTOPage,dto));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean appUpdate(BgtReissueacardUpdateDTO dto) {
		WgzReissueacard byId = getById(dto.getId());
		BeanUtil.copyProperties(dto, byId);
		boolean b = updateById(byId);
		//发消息
		HashMap<String, String> mp = new HashMap<>();
		mp.put("projectName",iBgtProjectRecruitService.getById(byId.getRecruitId()).getRecruitName());
		mp.put("auditor",SecurityUtils.getUsername());
		Map<String, String> map = bgtMessage(mp, BGT_TYPE_MAKE_UP, true);
		WgzMessage wgzMessage = new WgzMessage()
			.setSenderType(USERTYPE_BGT)
			.setRecipientType(USERTYPE_WGZ)
			.setRecipientId(byId.getUserId())
			.setHeadline(map.get(HEADLINE))
			.setSubheading(map.get(SUBHEADING))
			.setTableId(byId.getId())
			.setTableName(SqlHelper.table(WgzReissueacard.class).getTableName())
			.setMessageLargeType(LARGE_OTHER)
			.setMessageSmallType(SMALL_CARD);
		wgzMessageService.sendAMessage(wgzMessage);
		return b;
	}
}
