package org.jeecg.modules.projectManagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.modules.basedata.entity.FdPersonnel;
import org.jeecg.modules.basedata.mapper.FdPersonnelMapper;
import org.jeecg.modules.basedata.service.IFdPersonnelService;
import org.jeecg.modules.projectManagement.entity.FdProjectFile;
import org.jeecg.modules.projectManagement.entity.FdProjectFileCompound;
import org.jeecg.modules.projectManagement.entity.FdWorkingHours;
import org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems;
import org.jeecg.modules.projectManagement.mapper.FdWorkingHoursItemsMapper;
import org.jeecg.modules.projectManagement.service.IFdProjectFileCompoundService;
import org.jeecg.modules.projectManagement.service.IFdWorkingHoursItemsService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.common.util.oConvertUtils.isEmpty;

/**
 * @Description: 工时记录明细
 * @author： jeecg-boot
 * @date： 2019-06-25
 * @version： V1.0
 */
@Service
public class FdWorkingHoursItemsServiceImpl extends ServiceImpl<FdWorkingHoursItemsMapper, FdWorkingHoursItems> implements IFdWorkingHoursItemsService {

    @Resource
    FdWorkingHoursItemsMapper fdWorkingHoursItemsMapper;
    @Resource
    IFdProjectFileCompoundService iFdProjectFileCompoundService;

    @Resource
    IFdPersonnelService iFdPersonnelService;

    @Resource
    FdPersonnelMapper fdPersonnelMapper;

    @Resource
    SysUserMapper sysUserMapper;

    @Override
    public FdWorkingHoursItems queryByContractId(String contractId) {
        return fdWorkingHoursItemsMapper.queryByContractId(contractId);
    }

    @Override
    public FdWorkingHoursItems queryBySpecialType() {
        return fdWorkingHoursItemsMapper.queryBySpecialType();
    }

    @Override
    public IPage<FdWorkingHoursItems> findByPage(Page<FdWorkingHoursItems> page, QueryWrapper<FdWorkingHoursItems> queryWrapper) {
        return fdWorkingHoursItemsMapper.findByPage(page, queryWrapper);
    }

    /***
     * @Title:按部门分组查询工时记录明细数据（报表）
     * @Description:TODO
     * @return java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>
     * @exception
     * @author 陈创
     * @date 2019/8/21 13:38
     * @updatehistory:
     *   2019/8/21 13:38 新增
     */
    @Override
    public List<FdWorkingHoursItems> getWorkingReport(String startDate, String endDate,List<String> departs) {
        List<FdWorkingHoursItems> fdWorkingHoursItemsList = fdWorkingHoursItemsMapper.getWorkingReport(startDate, endDate,departs);
        //用于查找同样部门名称
        String deparName = "";
        //用于查找同样合同号
        String contractCode = "";
        //循环报表数据
        for (FdWorkingHoursItems fdWorkingHoursItems : fdWorkingHoursItemsList) {
            //部门合并
            if (fdWorkingHoursItems.getDepartName() == null) {
                fdWorkingHoursItems.setRowMerge(1);
            } else {
                //找到不同部门名称的时候获取合并行数
                if (!deparName.equals(fdWorkingHoursItems.getDepartName())) {
                    deparName = fdWorkingHoursItems.getDepartName();
                    //到不同的部门重新开始开始寻找相同合同号
                    contractCode = "";
                    Integer rowM = 0;
                    for (FdWorkingHoursItems fdWorkingHoursItems1 : fdWorkingHoursItemsList) {
                        if (fdWorkingHoursItems.getDepartName().equals(fdWorkingHoursItems1.getDepartName())) {
                            rowM++;
                        }
                    }
                    fdWorkingHoursItems.setRowMerge(rowM);
                } else {
                    fdWorkingHoursItems.setRowMerge(0);
                }
            }

            //合同号合并
            if (fdWorkingHoursItems.getContractCode() == null) {
                fdWorkingHoursItems.setContractMergeRow(1);
            } else {
                //下一个合同号不同则获取合并行数
                if (!contractCode.equals(fdWorkingHoursItems.getContractCode())) {
                    contractCode = fdWorkingHoursItems.getContractCode();
                    //获取合并行数
                    derpartContractMergeRow(fdWorkingHoursItems, fdWorkingHoursItemsList);
                } else {
                    fdWorkingHoursItems.setContractMergeRow(0);
                }
            }
        }

        return fdWorkingHoursItemsList;
    }

    /***
     * @Title:部门报表中合同合并行
     * @Description:TODO
     * @param fdWorkingHoursItems, fdWorkingHoursItemsList]
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/9/11 15:30
     * @updatehistory:
     *   2019/9/11 15:30 新增
     */
    public void derpartContractMergeRow(FdWorkingHoursItems fdWorkingHoursItems, List<FdWorkingHoursItems> fdWorkingHoursItemsList) {
        Integer contractMergerRow = 0;
        String deperName = fdWorkingHoursItems.getDepartName();//部门名称
        String contraCode = fdWorkingHoursItems.getContractCode();//合同号
        for (FdWorkingHoursItems fdWorkingHoursItems1 : fdWorkingHoursItemsList) {
            //查询对应部门下的合同相同数目
            if (StringUtils.isNotBlank(deperName) && StringUtils.isNotBlank(contraCode)){
                if (deperName.equals(fdWorkingHoursItems1.getDepartName()) && contraCode.equals(fdWorkingHoursItems1.getContractCode())) {
                    contractMergerRow++;
                }
            }
        }
        fdWorkingHoursItems.setContractMergeRow(contractMergerRow);
    }

    /***
     * @Title:按照人员查询工时记录报表
     * @Description:TODO
     * @param startDate, endDate]
     * @return java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>
     * @exception
     * @author 陈创
     * @date 2019/8/21 16:42
     * @updatehistory:
     *   2019/8/21 16:42 新增
     */
    @Override
    public List<FdWorkingHoursItems> getWorkingReportPersonnel(String startDate, String endDate,List<String> personnelCodes) {
        List<FdWorkingHoursItems> fdWorkingHoursItemsList = fdWorkingHoursItemsMapper.getWorkingReportPersonnel(startDate, endDate,personnelCodes);
        //获取合并行
        rowMeger(fdWorkingHoursItemsList);
        return fdWorkingHoursItemsList;
    }

    /***
     * @Title:根据相同部分名称分组
            * @Description:TODO
            * @param fdWorkingHoursItems, fdWorkingHoursItemsList]
            * @return void
            * @exception 
            * @author 陈创
            * @date 2019/9/17 15:36
            * @updatehistory:
     *   2019/9/17 15:36 新增
            */
    public void personnelMerge(FdWorkingHoursItems fdWorkingHoursItems,List<FdWorkingHoursItems> fdWorkingHoursItemsList){
        Integer rowM = 0;
        for (FdWorkingHoursItems fdWorkingHoursItems1 : fdWorkingHoursItemsList) {
            if (fdWorkingHoursItems.getPersonnelName().equals(fdWorkingHoursItems1.getPersonnelName())) {
                rowM++;
            }
        }
        fdWorkingHoursItems.setRowMerge(rowM);
    }

    /***
     * @Title:人员报表中合同合并行
     * @Description:TODO
     * @param fdWorkingHoursItems, fdWorkingHoursItemsList]
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/9/11 15:59
     * @updatehistory:
     *   2019/9/11 15:59 新增
     */
    public void perContractMergeRow(FdWorkingHoursItems fdWorkingHoursItems, List<FdWorkingHoursItems> fdWorkingHoursItemsList) {
        Integer contractMergerRow = 0;
        String personnelName = fdWorkingHoursItems.getPersonnelName();//人员名称
        String contraCode = fdWorkingHoursItems.getContractCode();//合同号
        for (FdWorkingHoursItems fdWorkingHoursItems1 : fdWorkingHoursItemsList) {
            //查询对应部门下的合同相同数目
            if (StringUtils.isNotBlank(personnelName) && StringUtils.isNotBlank(contraCode)){
                if (personnelName.equals(fdWorkingHoursItems1.getPersonnelName()) && contraCode.equals(fdWorkingHoursItems1.getContractCode())) {
                    contractMergerRow++;
                }
            }
        }
        fdWorkingHoursItems.setContractMergeRow(contractMergerRow);
    }

    /***
     * @Title:查询已审核合同
     * @Description:TODO
     * @param fdProjectFile
     * @return java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @exception
     * @author 陈创
     * @date 2019/9/4 9:36
     * @updatehistory:
     *   2019/9/4 9:36 新增
     */
    @Override
    public List<FdProjectFile> getContractList(FdProjectFile fdProjectFile) {
        //合同
        List<FdProjectFile> fdProjectFileList = fdWorkingHoursItemsMapper.getContractList(fdProjectFile);

        //查询化合物
        LambdaQueryWrapper<FdProjectFileCompound> fdProjectFileCompoundLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fdProjectFileCompoundLambdaQueryWrapper.eq(FdProjectFileCompound::getDelFlag, "0");
        List<FdProjectFileCompound> fdProjectFileCompoundList = iFdProjectFileCompoundService.list(fdProjectFileCompoundLambdaQueryWrapper);
        //循环合同
        for (FdProjectFile fdProjectFile1 : fdProjectFileList) {
            String file1Id = fdProjectFile1.getId();//档案id
            //储存档案所对应的化合物
            List<FdProjectFileCompound> fdProjectFileCompoundList1 = new ArrayList<>();
            //循环档案中全部化合物
            for (FdProjectFileCompound fdProjectFileCompound : fdProjectFileCompoundList) {
                //找到当前档案下的化合物
                if (file1Id.equals(fdProjectFileCompound.getProjectId())) {
                    fdProjectFileCompoundList1.add(fdProjectFileCompound);
                }
            }
            //获取对应的化合物
            fdProjectFile1.setFdProjectFileCompoundList(fdProjectFileCompoundList1);
        }

        //查询条件存在化合物则
        if (fdProjectFile.getCompound() != null && !fdProjectFile.getCompound().equals("")) {
            whereCompound(fdProjectFileList, fdProjectFile.getCompound());
        }
        return fdProjectFileList;
    }

    /***
     * @Title:根据化合物查询条件排除合同数据
     * @Description:TODO
     * @param fdProjectFileList, compoundName]
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/9/4 11:22
     * @updatehistory:
     *   2019/9/4 11:22 新增
     */
    public void whereCompound(List<FdProjectFile> fdProjectFileList, String compoundName) {
        //利用迭代器删除集合数据
        Iterator<FdProjectFile> it = fdProjectFileList.iterator();
        //循环项目档案中合同数据
        while (it.hasNext()) {
            FdProjectFile fdProjectFile = it.next();
            //是否存在化合物
            if (fdProjectFile.getFdProjectFileCompoundList().size() <= 0) {
                //不存在则直接删除
                it.remove();
            } else {
                boolean isC = true;
                //循环化合物
                for (FdProjectFileCompound fdProjectFileCompound : fdProjectFile.getFdProjectFileCompoundList()) {
                    //判断查询条件的化合物是否存在其中
                    if (fdProjectFileCompound.getCompound().matches(".*"+compoundName+".*")) {
                        isC = false;
                    }
                }
                //不存在则删除集合中的对象
                if (isC) {
                    it.remove();
                }
            }
        }
    }


    /***
     * @Title:获取两个时间段的时间
     * @Description:TODO
     * @param endDate, endDate]
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/9/12 17:19
     * @updatehistory:
     *   2019/9/12 17:19 新增
     */
    public List<Date> startDateAndEndDate(String startDate, String endDate) {
        List<Date> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = startDate; //开始时间
        String date2 = endDate; //结束时间
        Long startTIme = null;
        try {
            startTIme = sdf.parse(date1).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long endTime = null;
        try {
            endTime = sdf.parse(date2).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long oneDay = 1000 * 60 * 60 * 24l;
        Long time = startTIme;
        while (time <= endTime) {
            Date d = new Date(time);
            // DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // String date=df.format(d);
            list.add(d);
            time += oneDay;
        }
        return list;
    }

    /***
     * @Title:异常报表数据
     * @Description:TODO
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/9/16 9:22
     * @updatehistory:
     *   2019/9/16 9:22 新增
     */
    @Override
    public List<FdWorkingHoursItems> abnormalHoursReport(String startDate,String endDate,String roleId) {
        List<FdWorkingHoursItems> fdWorkingHoursItemsList = new ArrayList<>();
        // List<FdWorkingHoursItems> personnelList=new ArrayList<>();
        // //根据全部人员分组查询出的工时
        // List<FdWorkingHoursItems> personnelItemsList = allPersonnel(startDate,endDate,roleId);
        // //两时间之间的时间
        // List<Date> dateList = startDateAndEndDate(startDate, endDate);
        // String personnelName="";
        // int onePersonnel=0;
        // for (FdWorkingHoursItems fdWorkingHoursItems : personnelItemsList) {
        //
        //     if(!personnelName.equals(fdWorkingHoursItems.getPersonnelName())){
        //         //根据选择的时间点对人员工时处理项目
        //         dateAllByItem(dateList,personnelList,fdWorkingHoursItemsList);
        //         personnelList=new ArrayList<>();
        //         personnelName=fdWorkingHoursItems.getPersonnelName();
        //         personnelList.add(fdWorkingHoursItems);
        //         onePersonnel++;
        //     }else{
        //         personnelList.add(fdWorkingHoursItems);
        //     }
        // }
        // //只出现一个人员的记录时
        // if(onePersonnel==1){
        //     dateAllByItem(dateList,personnelList,fdWorkingHoursItemsList);
        // }
        fdWorkingHoursItemsList=aa(startDate,endDate,roleId);
        //获取相关合并行
        rowMeger(fdWorkingHoursItemsList);
        return fdWorkingHoursItemsList;
    }



    /***
     * @Title:根据全部人员处理对应工时项目
            * @Description:TODO
            * @param endDate, endDate]
            * @return java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>
            * @exception
            * @author 陈创
            * @date 2019/9/16 18:06
            * @updatehistory:
     *   2019/9/16 18:06 新增
            */
    public List<FdWorkingHoursItems> allPersonnel(String startDate,String endDate,String roleId){
        List<FdWorkingHoursItems> personnelAllItemsList=new ArrayList<>();
        //根据人员分组查询的工时项
        List<FdWorkingHoursItems> personnelItemsList = fdWorkingHoursItemsMapper.getWorkingReportPersonnel(startDate, endDate,null);
        //全部人员
        // List<FdPersonnel> fdPersonnelList=iFdPersonnelService.list();
        List<String>  roleIds=new ArrayList<>();
        //是否存在有选取角色
        if(StringUtils.isNotBlank(roleId)){
            roleIds.add(roleId);
        }
        List<FdPersonnel> fdPersonnelList = fdPersonnelMapper.getPersonnelByRoleLists(roleIds);
        if(!fdPersonnelList.isEmpty()&&fdPersonnelList.size()>0){
            for(FdPersonnel fdPersonnel:fdPersonnelList){
                boolean isP=true;
                for(FdWorkingHoursItems fdWorkingHoursItems:personnelItemsList){
                    //找到对应人员的工时项
                    if(fdPersonnel.getName().equals(fdWorkingHoursItems.getPersonnelName())){
                        personnelAllItemsList.add(fdWorkingHoursItems);
                        isP=false;
                    }
                }
                //一个工时没做则
                if(isP){
                    FdWorkingHoursItems fdWorkingHoursItems=new FdWorkingHoursItems();
                    fdWorkingHoursItems.setPersonnelName(fdPersonnel.getName());
                    personnelAllItemsList.add(fdWorkingHoursItems);
                }
            }
        }

        return personnelAllItemsList;
    }

    /***
     * @Title:根据两个时间点处理对应工时项目
            * @Description:TODO
            * @param dateList, personnelList, fdWorkingHoursItemsList]
            * @return void
            * @exception
            * @author 陈创
            * @date 2019/9/16 18:06
            * @updatehistory:
     *   2019/9/16 18:06 新增
            */
    public void dateAllByItem(List<Date> dateList,List<FdWorkingHoursItems> personnelList,List<FdWorkingHoursItems> fdWorkingHoursItemsList) {
        if(!personnelList.isEmpty()&&personnelList.size()>0){
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            for(Date date:dateList){
                boolean isE=true;
                String personnelName="";
                for(FdWorkingHoursItems fdWorkingHoursItems:personnelList){
                    Date actualHours = fdWorkingHoursItems.getActualHours();
                    //获取对应时间点的项目
                    if(actualHours!=null&&fmt.format(date).equals(fmt.format(actualHours))){
                        fdWorkingHoursItemsList.add(fdWorkingHoursItems);
                        isE=false;
                    }else{
                        personnelName=fdWorkingHoursItems.getPersonnelName();
                    }
                }
                //没有对应时间点则只有名字
                if(isE){
                    FdWorkingHoursItems fdWorkingHoursItems=new FdWorkingHoursItems();
                    fdWorkingHoursItems.setPersonnelName(personnelName);
                    fdWorkingHoursItems.setActualHours(date);
                    fdWorkingHoursItemsList.add(fdWorkingHoursItems);
                }
            }
        }
    }

    /***
     * @Title:获取人员，合同的合并行，工时时间
            * @Description:TODO
            * @param fdWorkingHoursItemsList
            * @return void
            * @exception 
            * @author 陈创
            * @date 2019/9/17 15:56
            * @updatehistory:
     *   2019/9/17 15:56 新增
            */
    public void rowMeger(List<FdWorkingHoursItems> fdWorkingHoursItemsList){
        //用于查找同样部门名称
        String personnelName = "";
        //用于查找合同号合并
        String contractCode = "";
        //用于查找工时时间
        Date hourDate=null;
        //循环报表数据
        for (FdWorkingHoursItems fdWorkingHoursItems : fdWorkingHoursItemsList) {
            if (fdWorkingHoursItems.getPersonnelName() == null) {
                fdWorkingHoursItems.setRowMerge(1);
            } else {
                //找到不同部门名称的时候获取合并行数
                if (!personnelName.equals(fdWorkingHoursItems.getPersonnelName())) {
                    personnelName = fdWorkingHoursItems.getPersonnelName();
                    //到不同的部门重新开始开始寻找相同合同号
                    contractCode = "";
                    //到不同部门重新开始寻找相同工时时间
                    hourDate=null;
                    //人员合并行
                    personnelMerge(fdWorkingHoursItems,fdWorkingHoursItemsList);
                } else {
                    fdWorkingHoursItems.setRowMerge(0);
                }
            }

            //合同号合并
            if (fdWorkingHoursItems.getContractCode() == null) {
                fdWorkingHoursItems.setContractMergeRow(1);
            } else {
                //下一个合同号不同则获取合并行数
                if (!contractCode.equals(fdWorkingHoursItems.getContractCode())) {
                    contractCode = fdWorkingHoursItems.getContractCode();
                    //获取合并行数
                    perContractMergeRow(fdWorkingHoursItems, fdWorkingHoursItemsList);
                } else {
                    fdWorkingHoursItems.setContractMergeRow(0);
                }
            }

            //工时时间合并行
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            if(hourDate!=null){
                String hDate=fmt.format(hourDate);
                String actualHours=fmt.format(fdWorkingHoursItems.getActualHours());
                if(!hDate.equals(actualHours)){
                    hourDate=fdWorkingHoursItems.getActualHours();
                    //获取工时时间合并行
                    actualHoursMeger(fdWorkingHoursItems,fdWorkingHoursItemsList);
                }else{
                    fdWorkingHoursItems.setActualHoursMerge(0);
                }
            }else{
                hourDate=fdWorkingHoursItems.getActualHours();
                //获取工时时间合并行
                actualHoursMeger(fdWorkingHoursItems,fdWorkingHoursItemsList);
            }

        }
    }


    /***
     * @Title:工时时间合并行方法
            * @Description:TODO
            * @param fdWorkingHoursItems, fdWorkingHoursItemsList]
            * @return void
            * @exception
            * @author 陈创
            * @date 2019/9/17 16:26
            * @updatehistory:
     *   2019/9/17 16:26 查询
            */
    public void actualHoursMeger(FdWorkingHoursItems fdWorkingHoursItems, List<FdWorkingHoursItems> fdWorkingHoursItemsList){
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Integer actualHoursMerge = 0;
        String personnelName = fdWorkingHoursItems.getPersonnelName();//人员名称
        Date actualHours = fdWorkingHoursItems.getActualHours();//工时时间
        for (FdWorkingHoursItems fdWorkingHoursItems1 : fdWorkingHoursItemsList) {
            Date actualHours2 = fdWorkingHoursItems1.getActualHours();
            //查询对应部门下的合同相同数目
            if (StringUtils.isNotBlank(personnelName) && actualHours != null){
                if (personnelName.equals(fdWorkingHoursItems1.getPersonnelName()) && fmt.format(actualHours).equals(fmt.format(actualHours2))) {
                    actualHoursMerge++;
                }
            }
        }
        fdWorkingHoursItems.setActualHoursMerge(actualHoursMerge);
    }


    public List<FdWorkingHoursItems> aa(String startDate,String endDate,String roleId){
        List<String>  roleIds=new ArrayList<>();
        //是否存在有选取角色
        if(StringUtils.isNotBlank(roleId)){
            roleIds.add(roleId);
        }
        //筛选的人员数据集合
        List<FdPersonnel> fdPersonnelList = fdPersonnelMapper.getPersonnelByRoleLists(roleIds);

        //两时间之间的时间集合
        List<Date> dateList = startDateAndEndDate(startDate, endDate);

        //工时求和数据集合
        List<FdWorkingHoursItems> sumHours=fdWorkingHoursItemsMapper.getWorkingItemsSumHours(startDate,endDate);

        //全部工时记录数据
        List<FdWorkingHoursItems> personnelItemsList = fdWorkingHoursItemsMapper.getWorkingReportPersonnel(startDate, endDate,null);

        //存取异常工时数据集合
        List<FdWorkingHoursItems> fdWorkingHoursItemsList=new ArrayList<>();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        //筛选人员集合
        for(FdPersonnel fdPersonnel:fdPersonnelList){
            String perName=fdPersonnel.getName();//条件人员名称
            //循环区间时间集合
            for(Date date:dateList){
                String whereDate=fmt.format(date);//条件区间时间
                boolean isWorking=true;//当天是否没做工时
                //循环求和工时集合
                for(FdWorkingHoursItems sumHour:sumHours){
                    String sumPerName=sumHour.getPersonnelName();//求和中的人员名称
                    String sumHourDate=fmt.format(sumHour.getActualHours());//求和工时时间
                    double sumHourNumber=0.0;
                    if(StringUtils.isNotBlank(sumHour.getWorkingHoursNumber())){
                        sumHourNumber=Double.parseDouble(sumHour.getWorkingHoursNumber());//求和工时
                    }
                    //判断获取人员相等，时间相等，工时小于8
                    if(perName.equals(sumPerName)&&whereDate.equals(sumHourDate)&&sumHourNumber<8){
                        for(FdWorkingHoursItems allItems:personnelItemsList){
                            String allPerName=allItems.getPersonnelName();//全部工时的人员名称
                            String allHourDate=fmt.format(allItems.getActualHours());//全部数据的工时时间
                            if(allPerName.equals(perName)&&sumHourDate.equals(allHourDate)){
                                fdWorkingHoursItemsList.add(allItems);
                            }
                        }
                    }
                    //判断时间区间内是否有做工时
                    if(perName.equals(sumPerName)&&whereDate.equals(sumHourDate)){
                        isWorking=false;
                    }
                }
                //当天没做则添加一条空数据
                if(isWorking){
                    FdWorkingHoursItems fdWorkingHoursItems=new FdWorkingHoursItems();
                    fdWorkingHoursItems.setPersonnelName(perName);
                    fdWorkingHoursItems.setActualHours(date);
                    fdWorkingHoursItemsList.add(fdWorkingHoursItems);
                }
            }
        }

        return fdWorkingHoursItemsList;
    }


    @Override
    public List<FdWorkingHoursItems> getWorkingItemsExport(FdWorkingHoursItems fdWorkingHoursItems) {
        return fdWorkingHoursItemsMapper.getWorkingItemsExport(fdWorkingHoursItems);
    }

    @Override
    public FdWorkingHours getDateExport(FdWorkingHoursItems fdWorkingHoursItems) {
        List<String> perIdsAdd=new ArrayList<>();//存储需要去数据库筛选得人员id
        getPerIdsAdd(fdWorkingHoursItems,perIdsAdd);//获取需要去数据库筛选的人员id;
        //统计合同号工时
        List<FdWorkingHoursItems> fdWorkingHoursItemsList=fdWorkingHoursItemsMapper.getDateExport(fdWorkingHoursItems,perIdsAdd);
        //统计非项目工时
        List<FdWorkingHoursItems> fdWorkingHoursItemsList1=fdWorkingHoursItemsMapper.getDateExport2(fdWorkingHoursItems,perIdsAdd);
        if(fdWorkingHoursItemsList1!=null&&fdWorkingHoursItemsList1.size()>0){
            fdWorkingHoursItemsList.addAll(fdWorkingHoursItemsList1);
        }
        FdWorkingHours fdWorkingHours=new FdWorkingHours();
        fdWorkingHours.setFdWorkingHoursItemsList(fdWorkingHoursItemsList);
        fdWorkingHours.setPerIdList(perIdsAdd);

        return fdWorkingHours;
    }


    public void getPerIdsAdd(FdWorkingHoursItems fdWorkingHoursItems,List<String> perIdsAdd){
        //根据选择的用户编号查询用户信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag,"0");
        lambdaQueryWrapper.in(SysUser::getUsername,fdWorkingHoursItems.getFdPersonnelIdsList());
        List<SysUser> sysUserList=sysUserMapper.selectList(lambdaQueryWrapper);
        List<String> priIdSelect=new ArrayList<>();//获取人员id
        if(sysUserList!=null&&sysUserList.size()>0){
            for(SysUser sysUser:sysUserList ){
                priIdSelect.add(sysUser.getPersonnelId());
            }
        }

        //获取人员信息
//        List<String> status=new ArrayList<>();
//        status.add("1");
//        status.add("2")
        LambdaQueryWrapper<FdPersonnel> fdPersonnelLambdaQueryWrapper=new LambdaQueryWrapper<>();
        fdPersonnelLambdaQueryWrapper.eq(FdPersonnel::getDelFlag,"0");
        fdPersonnelLambdaQueryWrapper.ne(FdPersonnel::getPkOrg,"fe33687fb0a645ccb71a2873460a3d7d");
        fdPersonnelLambdaQueryWrapper.in(FdPersonnel::getStatus,"1","3");
        List<FdPersonnel> fdPersonnelList=fdPersonnelMapper.selectList(fdPersonnelLambdaQueryWrapper);

        //获取下级人员
        getChild(priIdSelect,fdPersonnelList,perIdsAdd);
        //获取下级人员的下级人员
        final List<String> perIdsChild=new ArrayList<>();
        perIdsChild.addAll(perIdsAdd);
        getChild(perIdsChild,fdPersonnelList,perIdsAdd);
        //获取主级id
        perIdsAdd.addAll(priIdSelect);
        //去重
//        HashSet h = new HashSet(perIdsAdd);
//        perIdsAdd.clear();
//        perIdsAdd.addAll(h);
        removeDuplicate(perIdsAdd);
    }

    //获取下级人员ids
    public void getChild(List<String> perIdList,List<FdPersonnel> fdPersonnelList,List<String> perIdAdd){
        if(perIdList!=null&&perIdList.size()>0){
            //循环筛选的人员
            for(String perId:perIdList){
                //判断全部人员是否为空
                if(fdPersonnelList!=null&&fdPersonnelList.size()>0){
                    //循环全部人员
                    for(FdPersonnel fdPersonnelAll:fdPersonnelList){
                        if(StringUtils.isNotBlank(fdPersonnelAll.getPkPersonnel())&&fdPersonnelAll.getPkPersonnel().equals(perId)){
                            perIdAdd.add(fdPersonnelAll.getId());//添加
                        }
                    }
                }
                int aa=0;
            }
        }
    }


    public   static   List  removeDuplicate(List list)  {
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).equals(list.get(i)))  {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    @Override
    public FdWorkingHours getDayDateExport(FdWorkingHoursItems fdWorkingHoursItems) {
        List<String> perIdsAdd=new ArrayList<>();//存储需要去数据库筛选得人员id
        getPerIdsAdd(fdWorkingHoursItems,perIdsAdd);//获取需要去数据库筛选的人员id;
        //统计合同号工时
        List<FdWorkingHoursItems> fdWorkingHoursItemsList=fdWorkingHoursItemsMapper.getProjectDayExport(fdWorkingHoursItems,perIdsAdd);
        if(!StringUtils.isNotBlank(fdWorkingHoursItems.getContractCode())){
            //统计非项目工时
            List<FdWorkingHoursItems> fdWorkingHoursItemsList1=fdWorkingHoursItemsMapper.getNotProjectDayExport(fdWorkingHoursItems,perIdsAdd);
            if(fdWorkingHoursItemsList1!=null&&fdWorkingHoursItemsList1.size()>0){
                fdWorkingHoursItemsList.addAll(fdWorkingHoursItemsList1);
            }
        }
        FdWorkingHours fdWorkingHours=new FdWorkingHours();
        fdWorkingHours.setFdWorkingHoursItemsList(fdWorkingHoursItemsList);
        fdWorkingHours.setPerIdList(perIdsAdd);
        if(fdWorkingHours.getFdWorkingHoursItemsList()!=null){
            //获取导出格式数据
            getData(fdWorkingHours,fdWorkingHoursItems);
        }

        return fdWorkingHours;
    }



    //获取导出的格式数据
    public void getData(FdWorkingHours fdWorkingHours,FdWorkingHoursItems fdWorkingHoursItemsSelect) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String start =fdWorkingHoursItemsSelect.getStartDate();//开始时间
        String end =fdWorkingHoursItemsSelect.getEndDate();//结束时间
        //获取两时间之间的所有时间
        List<String> lists = getBetweenTime(start, end);
        //获取导出的xlsx标题头
        List<String> title = new ArrayList<>();
        title(title, lists);
        //获取合同号并去重
        List<String> contactCodeList = new ArrayList<>();
        List<FdWorkingHoursItems> fdWorkingHoursItemsList=new ArrayList<>();
        getCode(contactCodeList, fdWorkingHours,fdWorkingHoursItemsList);
        //设置导出的sheet
        List<Map<String, Object>> sheet = new ArrayList<>();
        //获取所有人员
        LambdaQueryWrapper<FdPersonnel> fdPersonnelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fdPersonnelLambdaQueryWrapper.eq(FdPersonnel::getDelFlag, "0");
        List<FdPersonnel> fdPersonnelList = fdPersonnelMapper.selectList(fdPersonnelLambdaQueryWrapper);

        if (fdPersonnelList != null && fdPersonnelList.size() > 0) {
            //循环所有人员根据id找到对应对象
            for (FdPersonnel fdPersonnel : fdPersonnelList) {
                for (String perId : fdWorkingHours.getPerIdList()) {
                    //找到对应人员
                    if (fdPersonnel.getId().equals(perId)) {

                        //设置导出data
                        List<List<String>> data = new ArrayList<>();
                        data.add(title);//添加标题表头
                        //循环合同号
                        for (FdWorkingHoursItems code : fdWorkingHoursItemsList) {
                            //创捷行对象集合
                            List<String> row = new ArrayList<>();
                            row.add(code.getContractCode());//添加第一列为合同号
                            row.add(code.getCustomerName());//添加第二列为申办方
                            Double total = 0.0;//当列总计
                            //循环时间段
                            for (String date : lists) {
                                boolean isDate = false;//当前时间是否存在项目工时
                                //循环项目工时条目
                                for (FdWorkingHoursItems fdWorkingHoursItems : fdWorkingHours.getFdWorkingHoursItemsList()) {
                                    //根据合同号、时间、人员找到对应的工时
                                    if (fdWorkingHoursItems.getContractCode().equals(code.getContractCode()) && isEquale(date, formatter.format(fdWorkingHoursItems.getActualHours())) && perId.equals(fdWorkingHoursItems.getPersonnelId())) {
                                        row.add(fdWorkingHoursItems.getWorkingHoursNumber());
                                        //获取当列 总工时累加
                                        if (isNumber(fdWorkingHoursItems.getWorkingHoursNumber())) {
                                            BigDecimal totalDecimal = new BigDecimal(total);
                                            BigDecimal hours = new BigDecimal(Double.parseDouble(fdWorkingHoursItems.getWorkingHoursNumber()));
                                            total = totalDecimal.add(hours).doubleValue();
                                        }
                                        isDate = true;
                                    }
                                }
                                //是否找到
                                if (!isDate) {
                                    row.add("");
                                }
                            }
                            row.add(total + "");
                            //合计为0的不需要导出
                            if(total!=0.0){
                                data.add(row);
                            }
                        }
                        //设置sheet格式
                        Map<String, Object> map = new HashMap<>();
                        map.put("data", data);
                        map.put("name", fdPersonnel.getName());
                        sheet.add(map);
                    }
                }
                fdWorkingHours.setSheet(sheet);
            }
        }
    }

    //获取导出的data标题表头
    public void title(List<String> title,List<String> list){

        try {
            //获取第一个的单元格标题为年份
            String aa=list.get(0);
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(aa);
            Calendar ca = Calendar.getInstance();
            ca.setTime(date);
            int year = ca.get(Calendar.YEAR);//年份数值
            title.add(year+"");
            title.add("申办方");
            //获取其他单元格为月份-日期
            for(String titleDate:list){
                Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(titleDate);
                Calendar ca2 = Calendar.getInstance();
                ca2.setTime(date2);
                int month = ca2.get(Calendar.MONTH)+1;//第几个月
                int day = ca2.get(Calendar.DAY_OF_MONTH);//一年中的第几天
                title.add(month+"-"+day);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        title.add("合计");
    }

    //获取两个时间的时间段
    public static List<String> getBetweenTime(String starttime,String endtime)
    {
        List<String> betweenTime = new ArrayList<String>();
        try
        {
            Date sdate= new SimpleDateFormat("yyyy-MM-dd").parse(starttime);
            Date edate= new SimpleDateFormat("yyyy-MM-dd").parse(endtime);

            SimpleDateFormat outformat = new SimpleDateFormat("yyyy-MM-dd");

            Calendar sCalendar = Calendar.getInstance();
            sCalendar.setTime(sdate);
            int year = sCalendar.get(Calendar.YEAR);
            int month = sCalendar.get(Calendar.MONTH);
            int day = sCalendar.get(Calendar.DATE);
            sCalendar.set(year, month, day, 0, 0, 0);

            Calendar eCalendar = Calendar.getInstance();
            eCalendar.setTime(edate);
            year = eCalendar.get(Calendar.YEAR);
            month = eCalendar.get(Calendar.MONTH);
            day = eCalendar.get(Calendar.DATE);
            eCalendar.set(year, month, day, 0, 0, 0);

            while (sCalendar.before(eCalendar))
            {
                betweenTime.add(outformat.format(sCalendar.getTime()));
                sCalendar.add(Calendar.DAY_OF_YEAR, 1);
            }
            betweenTime.add(outformat.format(eCalendar.getTime()));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return betweenTime;
    }

    //获取查询出的合同号并去重
    public void getCode(List<String> codeList,FdWorkingHours fdWorkingHours,List<FdWorkingHoursItems> fdWorkingHoursItemsList){
        for(FdWorkingHoursItems fdWorkingHoursItems:fdWorkingHours.getFdWorkingHoursItemsList()){
            codeList.add(fdWorkingHoursItems.getContractCode());
        }
        //去重
        removeDuplicate(codeList);
        //获取对应的申办方组装数据
        for (String code:codeList){
            FdWorkingHoursItems fdWorkingHoursItems1=new FdWorkingHoursItems();
            for(FdWorkingHoursItems fdWorkingHoursItems:fdWorkingHours.getFdWorkingHoursItemsList()){
                if(code.equals(fdWorkingHoursItems.getContractCode())){
                    fdWorkingHoursItems1.setContractCode(code);
                    fdWorkingHoursItems1.setCustomerName(fdWorkingHoursItems.getCustomerName());
                    break;
                }
            }
            fdWorkingHoursItemsList.add(fdWorkingHoursItems1);
        }
    }

    //判断两个时间是否相等
    public boolean isEquale(String date1,String date2){
        boolean isQ=false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date11 = sdf.parse(date1);
            Date date22 = sdf.parse(date2);

            if(date11.equals(date22)) {
                //相等
                isQ=true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isQ;
    }

    //是否为数字
    private boolean isNumber(String str){
        if(isEmpty(str)){
            return false;
        }
        String reg = "\\d+(\\.\\d+)?";
        return str.matches(reg);

    }


    @Override
    public IPage<FdWorkingHoursItems> getViewPage(Page<FdWorkingHoursItems> page, QueryWrapper<FdWorkingHoursItems> queryWrapper) {
        return fdWorkingHoursItemsMapper.getViewPage(page,queryWrapper);
    }
}
