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.BgtPayCalculationDetailBaseVO;
import com.ruoyi.bgt.domain.dto.BgtPayCalculationDetailListVO;
import com.ruoyi.bgt.domain.dto.BgtPayCalculationListDTO;
import com.ruoyi.bgt.domain.dto.BgtPayCalculationUpdateDTO;
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.SysUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.AuditStatus;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fbs.domain.FbsProjectTask;
import com.ruoyi.fbs.service.IFbsProjectTaskService;
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.WgzMessage;
import com.ruoyi.wgz.domain.WgzPayCalculation;
import com.ruoyi.wgz.domain.WgzPayCalculationFiles;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.domain.*;
import com.ruoyi.wgz.mapper.WgzPayCalculationMapper;
import com.ruoyi.wgz.service.*;
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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

/**
 * 工资结算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;

	@Autowired
	private IWgzUserService wgzUserService;

	@Autowired
	private IFbsProjectTaskService taskService;

	@Autowired
	private IWgzAttendanceService attendanceService;

	@Autowired
	private IWgzMessageService wgzMessageService;

	@Autowired
	private IWgzMessageService iWgzMessageService;

	@Autowired
	private IBgtMessageService iBgtMessageService;

	@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 recruitApply = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(user.getUserId());
		BgtProjectRecruit recruit = iBgtProjectRecruitService.getAppById(recruitApply.getId());
		//2、组装数据
		WgzPayCalculation wgzPayCalculation = new WgzPayCalculation();
		BeanUtils.copyProperties(req,wgzPayCalculation);
		wgzPayCalculation.
			setUserId(user.getUserId()).
			setUserName(user.getUserName()).
			setAuditorUserId(recruit.getUserId());
		//3、获取附件信息并插入
		iWgzPayCalculationFilesService.saveBatch(req.getPayCalculation());
		//4、插入工资结算信息
		boolean save = save(wgzPayCalculation);
		if (save) {
			WgzUser byId = wgzUserService.findByUserId(user.getUserId());
			Map<String, String> mp = new HashMap<>();
			mp.put("projectName", recruit.getRecruitName());
			mp.put("userName", byId.getUsername());
			mp.put("num", String.valueOf(wgzPayCalculation.getNum()));
			mp.put("money", String.valueOf(new BigDecimal(wgzPayCalculation.getNum()).multiply(wgzPayCalculation.getRecruitAmount())));
			WgzMessage wgzMessage = new WgzMessage().
				setSenderType(USERTYPE_SYSTEM).
				setRecipientType(USERTYPE_WGZ).
				setRecipientId(user.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"111")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"112")).
				setTableId(wgzPayCalculation.getId()).
				setTableName(SqlHelper.table(WgzPayCalculation.class).getTableName()).
				setMessageLargeType(LARGE_SALARY);
			if (!iWgzMessageService.sendAMessage(wgzMessage)){
				throw new RuntimeException("系统工资结算消息发送失败！");
			}
			BgtMessage bgtMessage = new BgtMessage().
				setSenderType(USERTYPE_WGZ).
				setSenderId(user.getUserId()).
				setRecipientType(USERTYPE_BGT).
				setRecipientId(recruit.getUserId()).
				setHeadline(WgzAndBgtMessageConstant.wgzMessage(mp,"209")).
				setSubheading(WgzAndBgtMessageConstant.wgzMessage(mp,"210")).
				setTableId(wgzPayCalculation.getId()).
				setTableName(SqlHelper.table(WgzPayCalculation.class).getTableName()).
				setMessageLargeType(BGT_LARGE).
				setMessageSmallType(BGT_TYPE_PAY);
			if (!iBgtMessageService.sendAMessage(bgtMessage)){
				throw new RuntimeException("发送补卡消息失败！");
			}
			return true;
		}
		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 List<WgzPayCalculation> findByUserIdRecruitIdNewestData(Long userId, Long recruitId) {
		LambdaQueryWrapper<WgzPayCalculation> eq = new LambdaQueryWrapper<WgzPayCalculation>().
			eq(WgzPayCalculation::getUserId, userId).
			eq(WgzPayCalculation::getRecruitId, recruitId).
			eq(WgzPayCalculation::getAuditorType, "2");
		return baseMapper.selectList(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());

		//发消息
		//发消息
		HashMap<String, String> mp = new HashMap<>();
		mp.put("projectName",iBgtProjectRecruitService.getById(payCalculation.getRecruitId()).getRecruitName());
		mp.put("auditor",SecurityUtils.getUsername());
		Map<String, String> map = bgtMessage(mp, BGT_TYPE_PAY, AuditStatus.PASS.getCode().equals(dto.getAuditorType()));
		WgzMessage wgzMessage = new WgzMessage()
			.setSenderType(USERTYPE_BGT)
			.setRecipientType(USERTYPE_WGZ)
			.setRecipientId(payCalculation.getUserId())
			.setHeadline(map.get(HEADLINE))
			.setSubheading(map.get(SUBHEADING))
			.setTableId(payCalculation.getId())
			.setTableName(SqlHelper.table(WgzPayCalculation.class).getTableName())
			.setMessageLargeType(LARGE_SALARY)
			.setMessageSmallType(SMALL_SYSTEM);
		wgzMessageService.sendAMessage(wgzMessage);
		return updateById(payCalculation);
	}

	@Override
	public BigDecimal getPayByTaskAndBgt(Long taskId,Long auditorUserId) {

		List<WgzPayCalculation> list = list(Wrappers.<WgzPayCalculation>lambdaQuery().eq(WgzPayCalculation::getTaskId, taskId)
			.eq(WgzPayCalculation::getAuditorUserId, auditorUserId));
		return list.stream().map(WgzPayCalculation::getRecruitAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
	}

	@Override
	public BgtPayCalculationDetailBaseVO baseInfo(Long userId, Long recruitId) {
		BgtPayCalculationDetailBaseVO vo = new BgtPayCalculationDetailBaseVO();
		WgzUser wgzUser = wgzUserService.getById(userId);
		vo.setScore(wgzUser.getScore());
		vo.setUsername(wgzUser.getUsername());
		vo.setAvatarName(wgzUser.getAvatarName());

		BgtProjectRecruit recruit = iBgtProjectRecruitService.getById(recruitId);
		vo.setRecruitName(recruit.getRecruitName());

		FbsProjectTask task = taskService.getById(recruit.getTaskId());
		vo.setTaskName(task.getTaskName());

		BgtProjectRecruitApply apply = iBgtProjectRecruitApplyService.getOne(Wrappers.<BgtProjectRecruitApply>lambdaQuery()
			.eq(BgtProjectRecruitApply::getRecruitId, recruitId).eq(BgtProjectRecruitApply::getUserId, userId)
			.last("limit 1"));
		vo.setEntryTime(apply.getEntryTime());

		Integer i = attendanceService.attendanceDetail(userId, apply.getId(), null);
		BigDecimal totalAmount = recruit.getRecruitAmount().multiply(BigDecimal.valueOf(i));
		vo.setAllAmount(totalAmount);

		List<WgzPayCalculation> gzs = findByUserIdRecruitIdNewestData(userId, apply.getId());
		BigDecimal addSum = new BigDecimal(0);
		for (WgzPayCalculation gz : gzs) {
			//金额*天数=实际工资
			BigDecimal multiply = gz.getRecruitAmount().multiply(BigDecimal.valueOf(gz.getNum()));
			addSum = addSum.add(multiply);
		}
		vo.setPayAmount(totalAmount);

		vo.setResidueAmount(vo.getAllAmount().subtract(vo.getPayAmount()));
		return vo;
	}

	@Override
	public List<BgtPayCalculationDetailListVO> record(Long userId, Long recruitId) {
		List<WgzPayCalculation> wgzPayCalculations = baseMapper.selectList(Wrappers.<WgzPayCalculation>lambdaQuery()
			.eq(WgzPayCalculation::getUserId, userId)
			.eq(WgzPayCalculation::getRecruitId, recruitId));
		return BeanUtil.copyToList(wgzPayCalculations, BgtPayCalculationDetailListVO.class);
	}
}
