package com.ruoyi.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
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.*;
import com.ruoyi.pay.domain.bo.*;
import com.ruoyi.pay.domain.vo.*;
import com.ruoyi.pay.mapper.PayBaohuoWorktimeMapper;
import com.ruoyi.pay.service.IPayBaohuoEmployeeService;
import com.ruoyi.pay.service.IPayBaohuoProductService;
import com.ruoyi.pay.util.ArchiveIdUtil;
import com.ruoyi.pay.util.DateCompareUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.pay.mapper.PayWorkOrderBaohuoMapper;
import com.ruoyi.pay.service.IPayWorkOrderBaohuoService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 包活派工单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@RequiredArgsConstructor
@Service
public class PayWorkOrderBaohuoServiceImpl implements IPayWorkOrderBaohuoService {

    private final PayWorkOrderBaohuoMapper baseMapper;
    private final PayEmployeeInfoServiceImpl payEmployeeInfoService;
    private final PayBaohuoWorktimeMapper worktimeMapper;
    private final PayWorkTimeServiceImpl workTimeService;
    private final PayBaohuoWorktimeServiceImpl bhworktimeService;
    private final PayAttendanceServiceImpl attendanceService;
    private final PayWorkOrderBaohuoMapper sgrWorkOrderBaohuoMapper;
    private final PayDayWorkHoursServiceImpl dayWorkHoursService;
    private final IPayBaohuoProductService bhproductService;
    private final IPayBaohuoEmployeeService bhemployeeService;

    /**
     * 查询包活派工单
     */
    @Override
    public PayWorkOrderBaohuoBo queryById(Long id){
        PayWorkOrderBaohuo workOrderBaohuo = sgrWorkOrderBaohuoMapper.selectById(id);
        PayWorkOrderBaohuoBo bo = BeanUtil.toBean(workOrderBaohuo,PayWorkOrderBaohuoBo.class);
        // 获取工单下所有的员工
        PayBaohuoEmployeeBo sgrBaohuoEmployee = new PayBaohuoEmployeeBo();
        sgrBaohuoEmployee.setWoId(id);
        List<PayBaohuoEmployeeVo> sgrBaohuoEmployees = bhemployeeService.queryList(sgrBaohuoEmployee);
        bo.setEmpList(sgrBaohuoEmployees.stream().map(a->{
            PayBaohuoEmployee payBaohuoEmployee = BeanUtil.toBean(a, PayBaohuoEmployee.class);
            return payBaohuoEmployee;
        }).collect(Collectors.toList()));

        // 获取工单下所有的产品
        PayBaohuoProductBo product = new PayBaohuoProductBo();
        product.setWoId(id);
        List<PayBaohuoProductVo> sgrBaohuoProducts = bhproductService.queryList(product);
        bo.setProdList(sgrBaohuoProducts.stream().map(a->{
            PayBaohuoProduct payBaohuoProduct = BeanUtil.toBean(a, PayBaohuoProduct.class);
            return payBaohuoProduct;
        }).collect(Collectors.toList()));

        // 获取工单下所有的工时
        PayBaohuoWorktimeBo sgrBaohuoWorktime = new PayBaohuoWorktimeBo();
        sgrBaohuoWorktime.setWoId(id);
        if (sgrBaohuoEmployees.size() != 0) {
            sgrBaohuoWorktime.setEmpId(sgrBaohuoEmployees.get(0).getEmpId());
        }
        List<PayBaohuoWorktimeVo> sgrBaohuoWorktimes = bhworktimeService.queryList(sgrBaohuoWorktime);
        bo.setWorktimeList(sgrBaohuoWorktimes.stream().map(a->{
            PayBaohuoWorktime payBaohuoWorktime = BeanUtil.toBean(a, PayBaohuoWorktime.class);
            return payBaohuoWorktime;
        }).collect(Collectors.toList()));
        return bo;

    }

    /**
     * 查询包活派工单列表
     */
    @Override
    public TableDataInfo<PayWorkOrderBaohuoVo> queryPageList(PayWorkOrderBaohuoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayWorkOrderBaohuo> lqw = buildQueryWrapper(bo);
        Page<PayWorkOrderBaohuoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询包活派工单列表
     */
    @Override
    public List<PayWorkOrderBaohuoVo> queryList(PayWorkOrderBaohuoBo bo) {
        LambdaQueryWrapper<PayWorkOrderBaohuo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayWorkOrderBaohuo> buildQueryWrapper(PayWorkOrderBaohuoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayWorkOrderBaohuo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, PayWorkOrderBaohuo::getTenantId, bo.getTenantId());
        lqw.eq(StringUtils.isNotBlank(bo.getArchiveId()), PayWorkOrderBaohuo::getArchiveId, bo.getArchiveId());
        lqw.eq(bo.getProductId() != null, PayWorkOrderBaohuo::getProductId, bo.getProductId());
        lqw.eq(bo.getDeptId() != null, PayWorkOrderBaohuo::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkshop()), PayWorkOrderBaohuo::getWorkshop, bo.getWorkshop());
        lqw.like(StringUtils.isNotBlank(bo.getName()), PayWorkOrderBaohuo::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), PayWorkOrderBaohuo::getContent, bo.getContent());
        lqw.eq(bo.getProductNum() != null, PayWorkOrderBaohuo::getProductNum, bo.getProductNum());
        lqw.eq(bo.getPrice() != null, PayWorkOrderBaohuo::getPrice, bo.getPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), PayWorkOrderBaohuo::getUnit, bo.getUnit());
        lqw.eq(bo.getAmount() != null, PayWorkOrderBaohuo::getAmount, bo.getAmount());
        lqw.eq(bo.getBeginTime() != null, PayWorkOrderBaohuo::getBeginTime, bo.getBeginTime());
        lqw.eq(bo.getEndTime() != null, PayWorkOrderBaohuo::getEndTime, bo.getEndTime());
        lqw.like(StringUtils.isNotBlank(bo.getQualityName()), PayWorkOrderBaohuo::getQualityName, bo.getQualityName());
        lqw.eq(StringUtils.isNotBlank(bo.getQualityRemark()), PayWorkOrderBaohuo::getQualityRemark, bo.getQualityRemark());
        lqw.eq(bo.getInstorageTime() != null, PayWorkOrderBaohuo::getInstorageTime, bo.getInstorageTime());
        lqw.like(StringUtils.isNotBlank(bo.getInstorageName()), PayWorkOrderBaohuo::getInstorageName, bo.getInstorageName());
        lqw.eq(bo.getInstorageNum() != null, PayWorkOrderBaohuo::getInstorageNum, bo.getInstorageNum());
        lqw.like(StringUtils.isNotBlank(bo.getManagerName()), PayWorkOrderBaohuo::getManagerName, bo.getManagerName());
        lqw.eq(bo.getDeleted() != null, PayWorkOrderBaohuo::getDeleted, bo.getDeleted());
        lqw.in(bo.getWoids()!=null&&bo.getWoids().size()>0,PayWorkOrderBaohuo::getId,bo.getWoids());
        return lqw;
    }

    /**
     * 新增包活派工单
     */
    @Override
    @Transactional
    public Boolean insertByBo(PayWorkOrderBaohuoBo bo) {
        List<PayBaohuoWorktime> worktimeList = bo.getWorktimeList();

        List<PayBaohuoProduct> prodList = bo.getProdList();

        List<PayBaohuoEmployee> empList = bo.getEmpList();

        if (ObjectUtil.isNull(empList)|| ObjectUtil.isNull(prodList)|| ObjectUtil.isNull(worktimeList)) {
            throw new ServiceException("请求参数异常");
        }

        // 产品单价检测
        for (PayBaohuoProduct product : prodList) {
            this.checkPrice(product);
        }

        // 增加对应的工时列表并进行判断
        for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
            // 判断两个时间是否正确
            if (!sgrWorkTime.getStime().before(sgrWorkTime.getEtime())) {// 开始时间在结束时间之前
                throw new ServiceException(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(sgrWorkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 开始结束时间颠倒");
            }
            // 生成工时对应的工作日期
            sgrWorkTime.setDate(DateUtil.parse(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd")));
        }
        // 判断有效时长是否正确
        //for (SgrBaohuoWorktime sgrWorkTime : worktimeList) {
        //    long between = DateUtil.between(sgrWorkTime.getStime(), sgrWorkTime.getEtime(), DateUnit.MINUTE);
        //    BigDecimal valHours = new BigDecimal(between).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
        //    if (sgrWorkTime.getValidHours().compareTo(valHours) > 0) {
        //        throw new ServiceException(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(sgrWorkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " " + sgrWorkTime.getValidHours() + "小时有效时长错误");
        //    }
        //}

        // TODO 特殊部门单独判断

        // 判断每个员工对应的包活工单工时以及流程卡工时
        for (PayBaohuoEmployee emp : empList) {
            for (PayBaohuoWorktime bhworktime : worktimeList) {
                // 流程卡工单时间比对
                PayWorkTimeBo searchWorkTime = new PayWorkTimeBo();
                searchWorkTime.setDate(DateUtil.parse(DateUtil.format(bhworktime.getDate(), "yyyy-MM-dd")));
                searchWorkTime.setEmpId(emp.getEmpId());
                List<PayWorkTimeVo> workTimes = workTimeService.queryList(searchWorkTime);
                for (PayWorkTimeVo workTime : workTimes) {
                    if (DateCompareUtil.isContainOrOverlap(workTime.getStime(), workTime.getEtime(), bhworktime.getStime(), bhworktime.getEtime())) {
                        throw new ServiceException("员工："+ emp.getEmpName()+ "已经存在 " +DateUtil.format(bhworktime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworktime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 该时间段流程卡工单工时");
                    }
                }
                // 包活工单工时比对
                PayBaohuoWorktimeBo searchBaohuoWorktime = new PayBaohuoWorktimeBo();
                searchBaohuoWorktime.setDate(DateUtil.parse(DateUtil.format(bhworktime.getDate(), "yyyy-MM-dd")));
                searchBaohuoWorktime.setEmpId(emp.getEmpId());
                List<PayBaohuoWorktimeVo> baohuoWorktimes = bhworktimeService.queryList(searchBaohuoWorktime);
                for (PayBaohuoWorktimeVo baohuoWorktime : baohuoWorktimes) {
                    if (DateCompareUtil.isContainOrOverlap(baohuoWorktime.getStime(), baohuoWorktime.getEtime(), bhworktime.getStime(), bhworktime.getEtime())) {
                        throw new ServiceException("员工："+ emp.getEmpName()+ "已经存在 " +DateUtil.format(bhworktime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworktime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 该时间段包活工单工时");
                    }
                }
            }
        }

        // 判断是否包含在考勤的时间段内
        for (PayBaohuoEmployee employee : empList) {
            for (PayBaohuoWorktime bhworkTime : worktimeList) {
                PayAttendanceBo sgrAttendance = new PayAttendanceBo();
                sgrAttendance.setEmpName(employee.getEmpName());
                sgrAttendance.setKaoqinDate(bhworkTime.getDate());
                sgrAttendance.setTenantId(bo.getTenantId());
                List<PayAttendanceVo> ats = attendanceService.queryList(sgrAttendance);
                // 判断考勤是否存在-务必存在考勤，没有需要补考勤
                if (ObjectUtil.isNull(ats) || ats.size() == 0) {
                    throw new ServiceException("员工："+ employee.getEmpName() + "在 " + DateUtil.format(bhworkTime.getDate(), "yyyy-MM-dd") + " 考勤不存在，请完善考勤");
                }

                // 获取员工所在部门
                String deptName = sgrWorkOrderBaohuoMapper.getDeptNameById(employee.getDeptId());

                // 判断考勤是否完整-喷塑生产不校验
                if (!"喷塑生产".equals(deptName)) {
                    //修改喷塑生产不校验考勤
                    /*if(ObjectUtil.isNull(at.getAmStartTime())|| ObjectUtil.isNull(at.getPmEndTime())){
                        throw new ServiceException("员工："+ employee.getEmpName() + "在 " + DateUtil.format(bhworkTime.getDate(), "yyyy-MM-dd") + " 喷塑生产部门考勤不完整");
                    }

                    if (!DateCompareUtil.isContain(at.getAmStartTime(), at.getPmEndTime(), bhworkTime.getStime(), bhworkTime.getEtime())) { // 当天考勤不包含工时
                        throw new ServiceException("员工："+ employee.getEmpName() + "在" + DateUtil.format(bhworkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 时间段内不存在当日喷塑生产部门考勤");
                    }*/
                    PayAttendanceVo at = ats.get(0);
                    if ((ObjectUtil.isNull(at.getAmStartTime()) || ObjectUtil.isNull(at.getAmEndTime())) && (ObjectUtil.isNull(at.getPmStartTime()) || ObjectUtil.isNull(at.getPmEndTime()))) {
                        // 上午或者下午考勤都不完整
                        throw new ServiceException("员工："+ employee.getEmpName() + "在 " + DateUtil.format(bhworkTime.getDate(), "yyyy-MM-dd") + " 考勤不完整");
                    }
                    // 上、下午考勤都存在或存在一个
                    boolean kaoqin = false;
                    if (ObjectUtil.isNotNull(at.getAmStartTime()) && ObjectUtil.isNotNull(at.getAmEndTime())) { // 上午考勤完整
                        if (DateCompareUtil.isContain(at.getAmStartTime(), at.getAmEndTime(), bhworkTime.getStime(), bhworkTime.getEtime())) { // 上午考勤包含工时
                            kaoqin = true;
                        }
                    }
                    if (!kaoqin) { // 上午考勤不包含工时
                        if (ObjectUtil.isNotNull(at.getPmStartTime()) && ObjectUtil.isNotNull(at.getPmEndTime())) {
                            if (DateCompareUtil.isContain(at.getPmStartTime(), at.getPmEndTime(), bhworkTime.getStime(), bhworkTime.getEtime())) { // 下午考勤包含工时
                                kaoqin = true;
                            }
                        }
                    }
                    if (!kaoqin) { // 上下午考勤都不包含工时
                        throw new ServiceException("员工："+ employee.getEmpName() + "在" + DateUtil.format(bhworkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 时间段内不存在当日考勤");
                    }
                }
            }
        }

        // 判断该时间段内是否有重叠的日工工时
        for (PayBaohuoEmployee employee : empList) {
            for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
                PayDayWorkHoursQuery sgrDayWorkHoursQuery = new PayDayWorkHoursQuery();
                sgrDayWorkHoursQuery.setDate(sgrWorkTime.getDate());
                sgrDayWorkHoursQuery.setEmployeeId(employee.getEmpId());
                List<PayDayWorkHoursQuery> queryList = dayWorkHoursService.selectPayDayWorkHoursList2(sgrDayWorkHoursQuery); // 获取日工工时
                for (PayDayWorkHoursQuery query : queryList) {
                    List<PayDwHoursContrast> dwHoursContrasts = query.getDwHoursContrasts();
                    for (PayDwHoursContrast dwHoursContrast : dwHoursContrasts) {
                        if (DateCompareUtil.isContainOrOverlap(dwHoursContrast.getStartTime(), dwHoursContrast.getEndTime(), sgrWorkTime.getStime(), sgrWorkTime.getEtime())) {
                            throw new ServiceException("员工："+ employee.getEmpName() + " 存在时间重叠的日工工时");
                        }
                    }
                }
            }
        }
        //if (empList.size() == 0 || prodList.size() == 0 || worktimeList.size() == 0) {
        //    throw new ServiceException("员工数或产品数或工时数不能为0");
        //}

        // 获取总金额
        BigDecimal total = BigDecimal.ZERO;
        for (PayBaohuoProduct product : prodList) {
            total = total.add(product.getAmount());
        }

        // 获取平均工资
        BigDecimal average = BigDecimal.ZERO;
        if (ObjectUtil.isNotNull(empList) && empList.size() > 0) {
            average = total.divide(new BigDecimal(empList.size()), 3, RoundingMode.HALF_UP);
        }

        // 新增包活派工单
        bo.setCreateTime(DateUtils.getNowDate()); // 创建时间
        bo.setCreateBy(LoginHelper.getUsername()); // 创建者
        bo.setArchiveId(ArchiveIdUtil.getBHArchiveId()); // 归档ID
        PayWorkOrderBaohuo add = BeanUtil.toBean(bo, PayWorkOrderBaohuo.class);
        validEntityBeforeSave(add);
        int i = baseMapper.insert(add);
        if (i<0) {
            throw new ServiceException("包活工单新增失败");
        }


        // 增加对应的产品列表
        for (PayBaohuoProduct product : prodList) {
            product.setWoId(add.getId());
            product.setTenantId(bo.getTenantId());
            PayBaohuoProductBo productBo= BeanUtil.toBean(product,PayBaohuoProductBo.class);
            bhproductService.insertByBo(productBo);
        }
        // 增加对应的员工列表
        for (PayBaohuoEmployee employee : empList) {
            employee.setWoId(add.getId());
            employee.setEmpId(employee.getEmpId());
            employee.setMonth(DateUtil.format(bo.getInstorageTime(), "yyyy-MM"));
            employee.setIntime(bo.getInstorageTime());
            employee.setHelper(employee.getHelper());
            employee.setAmount(average);
            employee.setTenantId(bo.getTenantId());
            PayBaohuoEmployeeBo payBaohuoEmployeeBo = BeanUtil.toBean(employee, PayBaohuoEmployeeBo.class);
            boolean a = bhemployeeService.insertByBo(payBaohuoEmployeeBo);

            // 为每个工单的员工都增加对应的工时
            for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
                sgrWorkTime.setId(null);
                sgrWorkTime.setWoId(add.getId());
                sgrWorkTime.setEmpId(employee.getEmpId());
                sgrWorkTime.setBheId(payBaohuoEmployeeBo.getId());
                sgrWorkTime.setTenantId(bo.getTenantId());
                //sgrWorkTime.setIntime(sgrWorkOrderBaohuo.getInstorageTime());
                PayBaohuoWorktimeBo payBaohuoWorktimeBo = BeanUtil.toBean(sgrWorkTime, PayBaohuoWorktimeBo.class);
                bhworktimeService.insertByBo(payBaohuoWorktimeBo);
            }
        }
        return true;
    }

    private void checkPrice(PayBaohuoProduct product) {
        if (product.getPrice().compareTo(product.getMinPrice()) < 0 || product.getPrice().compareTo(product.getMaxPrice()) > 0) {
            throw new ServiceException("产品：" + product.getProductName() + "单价不在范围内");
        }
        //if (product.getPrice().compareTo(product.getAmount()) > 0) {
        //    throw new ServiceException("产品：" + product.getProductName() + "单价低于总金额");
        //}
        if (product.getAmount().compareTo(product.getPrice().multiply(new BigDecimal(String.valueOf(product.getProductNum())))) != 0) {
            throw new ServiceException("产品：" + product.getProductName() + "总金额数值异常");
        }
    }

    /**
     * 修改包活派工单
     */
    @Override
    @Transactional
    public Boolean updateByBo(PayWorkOrderBaohuoBo bo) {
        List<PayBaohuoWorktime> worktimeList = bo.getWorktimeList();

        List<PayBaohuoProduct> prodList = bo.getProdList();

        List<PayBaohuoEmployee> empList = bo.getEmpList();

        // 产品单价检测
        for (PayBaohuoProduct product : prodList) {
            this.checkPrice(product);
        }

        // 增加对应的工时列表并进行判断
        for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
            // 判断两个时间是否正确
            if (!sgrWorkTime.getStime().before(sgrWorkTime.getEtime())) {// 开始时间在结束时间之前
                throw new ServiceException(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(sgrWorkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 开始结束时间颠倒");
            }
            // 生成工时对应的工作日期
            sgrWorkTime.setDate(DateUtil.parse(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd")));
            sgrWorkTime.setId(null);
        }
        // 判断有效时长是否正确
        //for (SgrBaohuoWorktime sgrWorkTime : worktimeList) {
        //    long between = DateUtil.between(sgrWorkTime.getStime(), sgrWorkTime.getEtime(), DateUnit.MINUTE);
        //    BigDecimal valHours = new BigDecimal(between).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
        //    if (sgrWorkTime.getValidHours().compareTo(valHours) > 0) {
        //        throw new ServiceException(DateUtil.format(sgrWorkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(sgrWorkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " " + sgrWorkTime.getValidHours() + "小时有效时长错误");
        //    }
        //}

        // TODO 特殊部门单独判断

        // 判断每个员工对应的包活工单工时以及流程卡工时
        for (PayBaohuoEmployee emp : empList) {
            for (PayBaohuoWorktime bhworktime : worktimeList) {
                // 流程卡工单时间比对
                PayWorkTimeBo searchWorkTime = new PayWorkTimeBo();
                searchWorkTime.setDate(DateUtil.parse(DateUtil.format(bhworktime.getDate(), "yyyy-MM-dd")));
                searchWorkTime.setEmpId(emp.getEmpId());
                List<PayWorkTimeVo> workTimes = workTimeService.queryList(searchWorkTime);
                for (PayWorkTimeVo workTime : workTimes) {
                    if (DateCompareUtil.isContainOrOverlap(workTime.getStime(), workTime.getEtime(), bhworktime.getStime(), bhworktime.getEtime())) {
                        throw new ServiceException("员工："+ emp.getEmpName()+ "已经存在 " +DateUtil.format(bhworktime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworktime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 该时间段流程卡工单工时");
                    }
                }
                // 包活工单工时比对
                PayBaohuoWorktimeBo searchBaohuoWorktime = new PayBaohuoWorktimeBo();
                searchBaohuoWorktime.setDate(DateUtil.parse(DateUtil.format(bhworktime.getDate(), "yyyy-MM-dd")));
                searchBaohuoWorktime.setEmpId(emp.getEmpId());
                List<PayBaohuoWorktimeVo> baohuoWorktimes = bhworktimeService.queryList(searchBaohuoWorktime);
                for (PayBaohuoWorktimeVo baohuoWorktime : baohuoWorktimes) {
                    if(!baohuoWorktime.getWoId().equals(bo.getId())){
                        if (DateCompareUtil.isContainOrOverlap(baohuoWorktime.getStime(), baohuoWorktime.getEtime(), bhworktime.getStime(), bhworktime.getEtime())) {
                            throw new ServiceException("员工："+ emp.getEmpName()+ "已经存在 " +DateUtil.format(bhworktime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworktime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 该时间段包活工单工时");
                        }
                    }
                }
            }
        }

        // 判断是否包含在考勤的时间段内
        for (PayBaohuoEmployee employee : empList) {
            for (PayBaohuoWorktime bhworkTime : worktimeList) {
                PayAttendanceBo sgrAttendance = new PayAttendanceBo();
                sgrAttendance.setEmpName(employee.getEmpName());
                sgrAttendance.setKaoqinDate(bhworkTime.getDate());
                sgrAttendance.setTenantId(bo.getTenantId());
                List<PayAttendanceVo> ats = attendanceService.queryList(sgrAttendance);
                // 判断考勤是否存在-务必存在考勤，没有需要补考勤
                if (ObjectUtil.isNull(ats) || ats.size() == 0) {
                    throw new ServiceException("员工：" + employee.getEmpName() + "在 " + DateUtil.format(bhworkTime.getDate(), "yyyy-MM-dd") + " 考勤不存在，请完善考勤");
                }

                PayAttendanceVo at = ats.get(0);
                // 判断考勤是否完整-喷塑生产不校验
                if (!"喷塑生产".equals(at.getDeptName())) {
                } else {
                    if ((ObjectUtil.isNull(at.getAmStartTime()) || ObjectUtil.isNull(at.getAmEndTime())) && (ObjectUtil.isNull(at.getPmStartTime()) || ObjectUtil.isNull(at.getPmEndTime()))) {
                        // 上午或者下午考勤都不完整
                        throw new ServiceException("员工：" + employee.getEmpName() + "在 " + DateUtil.format(bhworkTime.getDate(), "yyyy-MM-dd") + " 考勤不完整");
                    }
                    // 上、下午考勤都存在或存在一个
                    boolean kaoqin = false;
                    if (ObjectUtil.isNotNull(at.getAmStartTime()) && ObjectUtil.isNotNull(at.getAmEndTime())) { // 上午考勤完整
                        if (DateCompareUtil.isContain(at.getAmStartTime(), at.getAmEndTime(), bhworkTime.getStime(), bhworkTime.getEtime())) { // 上午考勤包含工时
                            kaoqin = true;
                        }
                    }
                    if (!kaoqin) { // 上午考勤不包含工时
                        if (ObjectUtil.isNotNull(at.getPmStartTime()) && ObjectUtil.isNotNull(at.getPmEndTime())) {
                            if (DateCompareUtil.isContain(at.getPmStartTime(), at.getPmEndTime(), bhworkTime.getStime(), bhworkTime.getEtime())) { // 下午考勤包含工时
                                kaoqin = true;
                            }
                        }
                    }
                    if (!kaoqin) { // 上下午考勤都不包含工时
                        throw new ServiceException("员工：" + employee.getEmpName() + "在" + DateUtil.format(bhworkTime.getStime(), "yyyy-MM-dd HH:mm:ss") + " 到 " + DateUtil.format(bhworkTime.getEtime(), "yyyy-MM-dd HH:mm:ss") + " 时间段内不存在当日考勤");
                    }
                }
            }
        }

        // 判断该时间段内是否有重叠的日工工时
        for (PayBaohuoEmployee employee : empList) {
            for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
                PayDayWorkHoursQuery sgrDayWorkHoursQuery = new PayDayWorkHoursQuery();
                sgrDayWorkHoursQuery.setDate(sgrWorkTime.getDate());
                sgrDayWorkHoursQuery.setEmployeeId(employee.getEmpId());
                List<PayDayWorkHoursQuery> queryList = dayWorkHoursService.selectPayDayWorkHoursList2(sgrDayWorkHoursQuery); // 获取日工工时
                for (PayDayWorkHoursQuery query : queryList) {
                    List<PayDwHoursContrast> dwHoursContrasts = query.getDwHoursContrasts();
                    for (PayDwHoursContrast dwHoursContrast : dwHoursContrasts) {
                        if (DateCompareUtil.isContainOrOverlap(dwHoursContrast.getStartTime(), dwHoursContrast.getEndTime(), sgrWorkTime.getStime(), sgrWorkTime.getEtime())) {
                            throw new ServiceException("员工："+ employee.getEmpName() + " 存在时间重叠的日工工时");
                        }
                    }
                }
            }
        }
        //if (empList.size() == 0 || prodList.size() == 0 || worktimeList.size() == 0) {
        //    throw new ServiceException("员工数或产品数或工时数不能为0");
        //}

        // 删除包活工单下对应的员工表数据、产品数据、工时数据
        baseMapper.deleteAllProdByWoId(bo.getId());
        baseMapper.deleteAllEmpByWoId(bo.getId());
        baseMapper.deleteAllWorkTimeByWoId(bo.getId());

        // 获取总金额
        BigDecimal total = BigDecimal.ZERO;
        for (PayBaohuoProduct product : prodList) {
            total = total.add(product.getAmount());
        }

        // 获取平均工资
        BigDecimal average = BigDecimal.ZERO;
        if (ObjectUtil.isNotNull(empList) && empList.size() > 0) {
            average = total.divide(new BigDecimal(empList.size()), 3, RoundingMode.HALF_UP);
        }

        // 增加对应的产品列表
        for (PayBaohuoProduct product : prodList) {
            product.setWoId(bo.getId());
            product.setTenantId(bo.getTenantId());
            PayBaohuoProductBo productBo= BeanUtil.toBean(product,PayBaohuoProductBo.class);
            bhproductService.insertByBo(productBo);
        }
        // 增加对应的员工列表
        for (PayBaohuoEmployee employee : empList) {
            employee.setWoId(bo.getId());
            employee.setEmpId(employee.getEmpId());
            employee.setMonth(DateUtil.format(bo.getInstorageTime(), "yyyy-MM"));
            employee.setIntime(bo.getInstorageTime());
            employee.setHelper(employee.getHelper());
            employee.setAmount(average);
            employee.setTenantId(bo.getTenantId());
            PayBaohuoEmployeeBo payBaohuoEmployeeBo = BeanUtil.toBean(employee, PayBaohuoEmployeeBo.class);
            boolean a = bhemployeeService.insertByBo(payBaohuoEmployeeBo);

            // 为每个工单的员工都增加对应的工时
            for (PayBaohuoWorktime sgrWorkTime : worktimeList) {
                sgrWorkTime.setId(null);
                sgrWorkTime.setWoId(bo.getId());
                sgrWorkTime.setEmpId(employee.getEmpId());
                sgrWorkTime.setBheId(payBaohuoEmployeeBo.getId());
                sgrWorkTime.setTenantId(bo.getTenantId());
                //sgrWorkTime.setIntime(sgrWorkOrderBaohuo.getInstorageTime());
                PayBaohuoWorktimeBo payBaohuoWorktimeBo = BeanUtil.toBean(sgrWorkTime, PayBaohuoWorktimeBo.class);
                bhworktimeService.insertByBo(payBaohuoWorktimeBo);
            }
        }
        bo.setUpdateBy(LoginHelper.getUsername());
        bo.setUpdateTime(DateUtils.getNowDate());
        PayWorkOrderBaohuo update = BeanUtil.toBean(bo, PayWorkOrderBaohuo.class);
        LambdaQueryWrapper<PayWorkOrderBaohuo> lqw = buildQueryWrapper(bo);
        return baseMapper.update(update,lqw)>0;
    }

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

    /**
     * 批量删除包活派工单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long id : ids) {
            // 删除包活工单下对应的员工表数据、产品数据、工时数据
            baseMapper.deleteAllProdByWoId(id);
            baseMapper.deleteAllEmpByWoId(id);
            baseMapper.deleteAllWorkTimeByWoId(id);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<List<PaySalaryReport>> baohuoSum(String date, Long deptId,Long tenantId) {
        //存储所有员工总工时信息
        List<PaySalaryReport> result = new ArrayList<>();

        String year = date.split("-")[0];
        String month = date.split("-")[1];
        Date yearMonth;
        try {
            yearMonth = new SimpleDateFormat("yyyy-MM").parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return R.fail("日期格式转换错误");
        }

        //1.拿到所有员工信息遍历
        PayEmployeeInfoBo payEemployeeInfo = new PayEmployeeInfoBo();
        payEemployeeInfo.setDeptId(deptId);
        payEemployeeInfo.setTenantId(tenantId);
        List<PayEmployeeInfoVo> employeeInfoList = payEmployeeInfoService.queryList(payEemployeeInfo);
        for (PayEmployeeInfoVo employeeInfo : employeeInfoList) {
            //创建存储员工数据的对象
            PaySalaryReport paySalaryReport = new PaySalaryReport();
            String empName = employeeInfo.getName();
            paySalaryReport.setEmployeeId(employeeInfo.getId());
            paySalaryReport.setEmployeeName(employeeInfo.getName());
            paySalaryReport.setYear(year);
            paySalaryReport.setMonth(month);
            // sgrSalaryReport.setBasicSalary(employeeInfo.getBasicSalary());
            paySalaryReport.setDeptId(employeeInfo.getDeptId());

            //包活工时初始值为0
            BigDecimal baohuogongshi = BigDecimal.ZERO;
            //包活工时计算
            PayBaohuoWorktime bhtime = new PayBaohuoWorktime();
            bhtime.setEmpId(employeeInfo.getId());
            bhtime.setDate(yearMonth);
            bhtime.setTenantId(tenantId);
            List<PayBaohuoWorktime> bhtimes = worktimeMapper.selectBaohuoWorktimeList(bhtime);
            if (bhtimes != null && bhtimes.size() > 0) {
                for (PayBaohuoWorktime btime : bhtimes) {
                    baohuogongshi = baohuogongshi.add(btime.getValidHours());
                }
            }
            paySalaryReport.setWorkOrderHours(baohuogongshi);
            result.add(paySalaryReport);
        }

        return R.ok(result);
    }

    @Override
    public List<ExportBaohuoVo> getWorkOrderListByDate(Long tenantId,Date exportDate) {
        return sgrWorkOrderBaohuoMapper.getWorkOrderListByDate(tenantId,exportDate);
    }

    @Override
    public HashSet<Long> getWoIdSet(String workDate, Long empId) {
        return baseMapper.getWoIdSet(workDate,empId);
    }
}
