package com.ruoyi.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.pay.domain.PayButie;
import com.ruoyi.pay.domain.PayEmployeeInfo;
import com.ruoyi.pay.domain.bo.PayButieBo;
import com.ruoyi.pay.domain.bo.PayEmployeeInfoBo;
import com.ruoyi.pay.domain.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.pay.domain.bo.PayButieEmplyeeBo;
import com.ruoyi.pay.domain.PayButieEmplyee;
import com.ruoyi.pay.mapper.PayButieEmplyeeMapper;
import com.ruoyi.pay.service.IPayButieEmplyeeService;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Optional;

/**
 * 补贴和员工联系Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@RequiredArgsConstructor
@Service
public class PayButieEmplyeeServiceImpl implements IPayButieEmplyeeService {

    private final PayButieEmplyeeMapper baseMapper;
    private final PayButieServiceImpl butieService;
    private final PayEmployeeInfoServiceImpl employeeInfoService;

    /**
     * 查询补贴和员工联系
     */
    @Override
    public PayButieEmplyeeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询补贴和员工联系列表
     */
    @Override
    public TableDataInfo<PayButieEmplyeeVo> queryPageList(PayButieEmplyeeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayButieEmplyee> lqw = buildQueryWrapper(bo);
        Page<PayButieEmplyeeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询补贴和员工联系列表
     */
    @Override
    public List<PayButieEmplyeeVo> queryList(PayButieEmplyeeBo bo) {
        LambdaQueryWrapper<PayButieEmplyee> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayButieEmplyee> buildQueryWrapper(PayButieEmplyeeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayButieEmplyee> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, PayButieEmplyee::getTenantId, bo.getTenantId());
        lqw.eq(bo.getButieId() != null, PayButieEmplyee::getButieId, bo.getButieId());
        lqw.eq(bo.getEmployeeId() != null, PayButieEmplyee::getEmployeeId, bo.getEmployeeId());
        lqw.eq(bo.getMoney() != null, PayButieEmplyee::getMoney, bo.getMoney());
        lqw.eq(StringUtils.isNotBlank(bo.getDate()), PayButieEmplyee::getDate, bo.getDate());
        return lqw;
    }

    /**
     * 新增补贴和员工联系
     */
    @Override
    public Boolean insertByBo(PayButieEmplyeeBo bo) {
        PayButieEmplyee add = BeanUtil.toBean(bo, PayButieEmplyee.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改补贴和员工联系
     */
    @Override
    public Boolean updateByBo(PayButieEmplyeeBo bo) {
        PayButieEmplyee update = BeanUtil.toBean(bo, PayButieEmplyee.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public R<Void> updateAllBtempByDate(ButieUpdateVo vo) {
        List<ButieTypeVo> btList = vo.getBtList();
        if (ObjectUtil.isNotNull(btList) && btList.size() > 0) {
            for (ButieTypeVo typeVo : btList) {
                if (ObjectUtil.isNull(typeVo.getMoney())) {
                    typeVo.setMoney(BigDecimal.ZERO);
                }
                Integer integer = baseMapper.updateButieEmplyeeByDate(typeVo.getBtid(), vo.getEmpId(), vo.getDate(), typeVo.getMoney());
                if (integer == 0) {
                    return R.fail("本月补贴数据未生成");
                }
            }
            return R.ok("修改成功");
        }
        return R.fail("数据异常");
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayButieEmplyee entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除补贴和员工联系
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<Void> generateBuTieEmpByMonth(String month, Boolean cover,Long tenantId) {
        if (ObjectUtil.isNull(month)) {
            throw new SecurityException("请完善月份信息");
        }
        String lastMonth = DateUtil.format(DateUtil.offset(DateUtil.parse(month, "yyyy-MM"), DateField.MONTH, -1).toJdkDate(), "yyyy-MM");
        // 先删除本月数据
        baseMapper.deleteSgrButieEmplyeeByDate(month,tenantId);
        PayButieBo bo = new PayButieBo();
        bo.setTenantId(tenantId);
        PayButieBo pbt = new PayButieBo();
        pbt.setTenantId(tenantId);
        List<PayButieVo> butieList = butieService.queryList(pbt); // 获取补贴列表
        PayEmployeeInfoBo yg = new PayEmployeeInfoBo();
        yg.setTenantId(tenantId);
        List<PayEmployeeInfoVo> employeeInfoList = employeeInfoService.queryList(yg);// 获取员工列表
        employeeInfoList.forEach(emp -> {
            // 首先获取用户上个月份的补贴信息
            PayButieEmplyeeBo butieEmplyee = new PayButieEmplyeeBo();
            butieEmplyee.setDate(lastMonth);
            butieEmplyee.setEmployeeId(emp.getId());
            butieEmplyee.setTenantId(tenantId);
            List<PayButieEmplyeeVo> butieEmplyeeList = this.queryList(butieEmplyee);
            if (ObjectUtil.isNotNull(butieEmplyeeList) && butieEmplyeeList.size() > 0) { // 具有某员工的上个月数据
                // 固定项继承， 非固定相为0
                for (PayButieVo butie : butieList) {
                    Optional<PayButieEmplyeeVo> first = butieEmplyeeList.stream().filter(btemp -> btemp.getButieId().equals(butie.getId())).findFirst();
                    PayButieEmplyee payButieEmplyee = new PayButieEmplyee();
                    payButieEmplyee.setTenantId(tenantId);
                   // PayEmployeeInfo employeeInfo = employeeInfoService.selectSgrEmployeeInfoById(payButieEmplyee.getEmployeeId());
                    if (first.isPresent()) { // 如果找到和补贴类型ID相同的项
                       payButieEmplyee = BeanUtil.toBean(first.get(),PayButieEmplyee.class);
                       payButieEmplyee.setId(null); // ID 设置为null
                       payButieEmplyee.setDate(month); // 本月的年月
                       payButieEmplyee.setCreateBy("system");
                       payButieEmplyee.setCreateTime(null);
                       payButieEmplyee.setUpdateBy(null);
                       payButieEmplyee.setUpdateTime(null);
                       payButieEmplyee.setRemark(null);
                        if ("0".equals(butie.getFixed())) { //非固定项金额不继承
                            payButieEmplyee.setMoney(BigDecimal.ZERO);
                        }
                        // 此处应该在上面是否非固定的判断中进行再判断
                        //// 判断是否是合同补助项，如果合同补助项不在时间范围内，继承的金额也设置为0
                        //if ("合同补助".equals(sgrButie.getName())) {
                        //    Date date = new Date();
                        //    if (ObjectUtil.isNull(employeeInfo.getHtstime()) || date.before(employeeInfo.getHtstime()) || date.after(employeeInfo.getHtstime())) {
                        //        sgrButieEmplyee.setMoney(BigDecimal.ZERO);
                        //    }
                        //}
                    } else { // 未找到相同项
                       payButieEmplyee.setButieId(butie.getId());
                       payButieEmplyee.setEmployeeId(emp.getId());
                       payButieEmplyee.setDate(month);
                       payButieEmplyee.setCreateBy("system");
                       payButieEmplyee.setMoney(BigDecimal.ZERO);
                    }
                    baseMapper.insert(payButieEmplyee);
                }
            } else { // 没有某员工的上个月数据
                for (PayButieVo butie : butieList) { // 对应生成某员工所有补贴类型的数据项
                    PayButieEmplyee paybutieEmplyee = new PayButieEmplyee();
                    paybutieEmplyee.setTenantId(tenantId);
                    paybutieEmplyee.setButieId(butie.getId());
                    paybutieEmplyee.setEmployeeId(emp.getId());
                    paybutieEmplyee.setMoney(BigDecimal.ZERO);
                    paybutieEmplyee.setDate(month);
                    paybutieEmplyee.setCreateBy("system");
                    baseMapper.insert(paybutieEmplyee);
                }
            }
        });
        return R.ok(month+"月份数据已生成");
    }

    @Override
    public R<Void> checkDataExist(String month,Long tenantId) {
        Integer count = baseMapper.getLatestDate(month,tenantId);
        if (count > 0) {
            return R.ok("数据已经存在，是否覆盖？");
        } else {
            return this.generateBuTieEmpByMonth(month, true,tenantId);
        }
    }
}
