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.BgtPayCalculationListDTO;
import com.ruoyi.bgt.domain.dto.BgtPayCalculationUpdateDTO;
import com.ruoyi.bgt.service.IBgtProjectRecruitApplyService;
import com.ruoyi.bgt.service.IBgtProjectRecruitService;
import com.ruoyi.common.core.domain.entity.SysUser;
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.WgzPayCalculationQueryBo;
import com.ruoyi.wgz.bo.req.WgzAppApplyForPayrollSettlementListReq;
import com.ruoyi.wgz.bo.req.WgzApplyForPayrollSettlementAddReq;
import com.ruoyi.wgz.bo.res.WgzAppApplyForPayrollSettlementListRes;
import com.ruoyi.wgz.domain.WgzPayCalculation;
import com.ruoyi.wgz.domain.WgzPayCalculationFiles;
import com.ruoyi.wgz.mapper.WgzPayCalculationMapper;
import com.ruoyi.wgz.service.IWgzPayCalculationFilesService;
import com.ruoyi.wgz.service.IWgzPayCalculationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 工资结算Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-21
 */
@Service
public class WgzPayCalculationServiceImpl extends ServicePlusImpl<WgzPayCalculationMapper, WgzPayCalculation> implements IWgzPayCalculationService {

	@Autowired
	private IBgtProjectRecruitApplyService iBgtProjectRecruitApplyService;

	@Autowired
	private IBgtProjectRecruitService iBgtProjectRecruitService;

	@Autowired
	private IWgzPayCalculationFilesService iWgzPayCalculationFilesService;


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

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

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

    private LambdaQueryWrapper<WgzPayCalculation> buildQueryWrapper(WgzPayCalculationQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WgzPayCalculation> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTaskId() != null, WgzPayCalculation::getTaskId, bo.getTaskId());
        lqw.eq(bo.getRecruitId() != null, WgzPayCalculation::getRecruitId, bo.getRecruitId());
        lqw.eq(bo.getUserId() != null, WgzPayCalculation::getUserId, bo.getUserId());
        lqw.like(StrUtil.isNotBlank(bo.getTaskName()), WgzPayCalculation::getTaskName, bo.getTaskName());
        lqw.eq(StrUtil.isNotBlank(bo.getTaskAddress()), WgzPayCalculation::getTaskAddress, bo.getTaskAddress());
        lqw.like(StrUtil.isNotBlank(bo.getRecruitName()), WgzPayCalculation::getRecruitName, bo.getRecruitName());
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), WgzPayCalculation::getUserName, bo.getUserName());
        lqw.eq(bo.getEntryTime() != null, WgzPayCalculation::getEntryTime, bo.getEntryTime());
        lqw.eq(bo.getRecruitAmount() != null, WgzPayCalculation::getRecruitAmount, bo.getRecruitAmount());
        lqw.eq(bo.getNum() != null, WgzPayCalculation::getNum, bo.getNum());
        lqw.eq(StrUtil.isNotBlank(bo.getWorkingState()), WgzPayCalculation::getWorkingState, bo.getWorkingState());
        lqw.eq(StrUtil.isNotBlank(bo.getPhone()), WgzPayCalculation::getPhone, bo.getPhone());
        lqw.eq(StrUtil.isNotBlank(bo.getBank()), WgzPayCalculation::getBank, bo.getBank());
        lqw.eq(StrUtil.isNotBlank(bo.getCardNo()), WgzPayCalculation::getCardNo, bo.getCardNo());
        lqw.eq(bo.getAuditorUserId() != null, WgzPayCalculation::getAuditorUserId, bo.getAuditorUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getAuditorType()), WgzPayCalculation::getAuditorType, bo.getAuditorType());
        lqw.eq(StrUtil.isNotBlank(bo.getAuditorOpinion()), WgzPayCalculation::getAuditorOpinion, bo.getAuditorOpinion());
        lqw.eq(bo.getAuditorTime() != null, WgzPayCalculation::getAuditorTime, bo.getAuditorTime());
        return lqw;
    }

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

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

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

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

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

	@Override
	@Transactional
	public Boolean userApplyForPayrollSettlementAdd(WgzApplyForPayrollSettlementAddReq req) {
		//1、获取当前人
		SysUser user = SecurityUtils.getLoginUser().getUser();
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(user.getUserId());
		BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(by.getId());
		//2、组装数据
		WgzPayCalculation wgzPayCalculation = new WgzPayCalculation();
		BeanUtils.copyProperties(req,wgzPayCalculation);
		wgzPayCalculation.
			setUserId(user.getUserId()).
			setUserName(user.getUserName()).
			setAuditorUserId(appById.getUserId());
		//3、获取附件信息并插入
		iWgzPayCalculationFilesService.saveBatch(req.getPayCalculation());
		return save(wgzPayCalculation);
	}

	@Override
	public TableDataInfo<WgzAppApplyForPayrollSettlementListRes> userApplyForPayrollSettlementList(WgzAppApplyForPayrollSettlementListReq req) {
		Page<WgzAppApplyForPayrollSettlementListReq> pe = new Page<>();
		pe.setCurrent(req.getPageNum());
		pe.setSize(req.getPageSize());
		return PageUtils.buildDataInfo(baseMapper.userApplyForPayrollSettlementList(pe));
	}

	@Override
	public WgzPayCalculation findByUserIdRecruitIdNewestData(Long userId, Long recruitId) {
		LambdaQueryWrapper<WgzPayCalculation> eq = new LambdaQueryWrapper<WgzPayCalculation>().
			eq(WgzPayCalculation::getUserId, userId).
			eq(WgzPayCalculation::getRecruitId, recruitId).
			orderByDesc(WgzPayCalculation::getCreateTime).
			last("limit 1");
		return baseMapper.selectOne(eq);
	}

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

	@Override
	public WgzAppApplyForPayrollSettlementListRes appQueryById(Long id) {
		WgzPayCalculation payCalculation = getById(id);
		WgzAppApplyForPayrollSettlementListRes res = BeanUtil.copyProperties(payCalculation, WgzAppApplyForPayrollSettlementListRes.class);
		List<WgzPayCalculationFiles> list = iWgzPayCalculationFilesService.list(Wrappers.<WgzPayCalculationFiles>lambdaQuery().eq(WgzPayCalculationFiles::getCalculationId, id));
		res.setPayCalculation(list);
		return res;
	}

	@Override
	public Boolean appUpdate(BgtPayCalculationUpdateDTO dto) {
		WgzPayCalculation payCalculation = BeanUtil.copyProperties(dto, WgzPayCalculation.class);
		payCalculation.setAuditorTime(LocalDateTime.now());
		return updateById(payCalculation);
	}
}
