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.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.IBgtProjectRecruitApplyService;
import com.ruoyi.bgt.service.IBgtProjectRecruitService;
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.WgzReissueacard;
import com.ruoyi.wgz.mapper.WgzReissueacardMapper;
import com.ruoyi.wgz.service.IWgzAttendanceService;
import com.ruoyi.wgz.service.IWgzReissueacardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 补卡申请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;

    @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();
		//2、获取当前用户所在的工地id
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		//3、根据招工id获取到具体招工信息
		BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(by.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(by.getRecruitId()).
			setUserId(appUserId).
			setAttendanceId(req.getAttendanceId()).
			setType(req.getType()).
			setRecruitName(appById.getRecruitName()).
			setRawTime(rawTime).
			setNowTime(req.getNowTime()).
			setReason(req.getReason()).
			setAttendanceId(appById.getUserId());
		return baseMapper.insert(wgzReissueacard) > 0;
	}


	@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
	public Boolean appUpdate(BgtReissueacardUpdateDTO dto) {
		return updateById(BeanUtil.copyProperties(dto,WgzReissueacard.class));
	}
}
