package com.dcsoft.system.kq.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;

import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.system.domain.SysPeople;
import com.dcsoft.system.kq.domain.*;
import com.dcsoft.system.kq.mapper.*;
import com.dcsoft.system.mapper.SysPeopleMapper;
import com.dcsoft.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dcsoft.system.kq.service.IKqGatherMonthService;

import javax.annotation.Resource;

/**
 * 月汇总Service业务层处理
 *
 * @author dcsoft
 * @date 2023-08-01
 */
@Service
public class KqGatherMonthServiceImpl implements IKqGatherMonthService
{
    @Autowired
    private KqGatherMonthMapper kqGatherMonthMapper;

    @Autowired
    private KqGroupMapper kqGroupMapper;

    @Autowired
    private KqGroupUserMapper kqGroupUserMapper;

    @Autowired
    private KqClassesMapper kqClassesMapper;

    @Autowired
    private SysPeopleMapper peopleMapper;

    @Autowired
    private KqHolidayGroupMapper holidayGroupMapper;

    @Autowired
    private KqGatherMapper gatherMapper;

    @Autowired
    private KqAdjustMapper adjustMapper;

    @Resource
    private KqHolidayMapper kqHolidayMapper;

    @Autowired
    private ISysConfigService configService;


    /**
     * 查询月汇总
     *
     * @param id 月汇总主键
     * @return 月汇总
     */
    @Override
    public KqGatherMonth selectKqGatherMonthById(Long id)
    {
        return kqGatherMonthMapper.selectKqGatherMonthById(id);
    }

    /**
     * 查询月汇总列表
     *
     * @param kqGatherMonth 月汇总
     * @return 月汇总
     */
    @Override
    public List<KqGatherMonth> selectKqGatherMonthList(KqGatherMonth kqGatherMonth) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<KqGatherMonth> kqGatherMonths = kqGatherMonthMapper.selectKqGatherMonthList(kqGatherMonth);
        KqTime time = getTime();
        KqTime furloughInfo = kqHolidayMapper.queryHoliday(time);
        for (KqGatherMonth gatherMonth : kqGatherMonths) {
            Date start = sdf.parse(time.getStartTime());
            Date end = sdf.parse(time.getEndTime());
            gatherMonth.setFurloughSum("0");
            if(start.getTime() <= gatherMonth.getStartTime().getTime() &&
                   gatherMonth.getEndTime().getTime() <= end.getTime() &&
                   furloughInfo.getBranchId().equals(gatherMonth.getParentId())) {
                gatherMonth.setFurloughSum(furloughInfo.getTotal());
                gatherMonth.setHz(gatherMonth.getHz() + Integer.parseInt(furloughInfo.getTotal()));
            }
        }
        return kqGatherMonths;
    }

    /**
     * 新增月汇总
     *
     * @param kqGatherMonth 月汇总
     * @return 结果
     */
    @Override
    public int insertKqGatherMonth(KqGatherMonth kqGatherMonth)
    {
        return kqGatherMonthMapper.insertKqGatherMonth(kqGatherMonth);
    }

    /**
     * 修改月汇总
     *
     * @param kqGatherMonth 月汇总
     * @return 结果
     */
    @Override
    public int updateKqGatherMonth(KqGatherMonth kqGatherMonth)
    {
        return kqGatherMonthMapper.updateKqGatherMonth(kqGatherMonth);
    }

    /**
     * 批量删除月汇总
     *
     * @param ids 需要删除的月汇总主键
     * @return 结果
     */
    @Override
    public int deleteKqGatherMonthByIds(Long[] ids)
    {
        return kqGatherMonthMapper.deleteKqGatherMonthByIds(ids);
    }

    /**
     * 删除月汇总信息
     *
     * @param id 月汇总主键
     * @return 结果
     */
    @Override
    public int deleteKqGatherMonthById(Long id)
    {
        return kqGatherMonthMapper.deleteKqGatherMonthById(id);
    }

    @Override
    public int createKqGatherMonth(KqGatherMonth kqGatherMonth) {
        //生成考勤月汇总信息
        //考勤组
        KqGroup group=kqGroupMapper.selectKqGroupByGroupId(kqGatherMonth.getGroupId());
        kqGatherMonth.setClassesId(group.getClassesId());
        KqGroupUser kqGroupUser=new KqGroupUser();
        kqGroupUser.setGroupId(kqGatherMonth.getGroupId());
        List<KqGroupUser> KqGroupUserList= kqGroupUserMapper.selectKqGroupUserList(kqGroupUser);
        String isKq = configService.selectConfigByKey("sys_kq_dk");

        //应出勤天数 时间段的天数-该组的放假天数
        long day=DateUtils.timeTwo(kqGatherMonth.getEndTime(),kqGatherMonth.getStartTime());
        //查询该组放假
        KqHolidayGroup holidayGroup=new KqHolidayGroup();
        holidayGroup.setGroupId(kqGatherMonth.getGroupId());
        holidayGroup.setStartTimeStep(kqGatherMonth.getStartTime().getTime());
        holidayGroup.setEndTimeStep(kqGatherMonth.getEndTime().getTime());
        List<KqHolidayGroup>  list=holidayGroupMapper.selectKqHolidayGroupList(holidayGroup);
        kqGatherMonth.setYcqsj(day+1-list.size());
        //考勤人员
        for(KqGroupUser u:KqGroupUserList){
            //考勤人员数据
            SysPeople people=peopleMapper.selectSysPeopleById(u.getUserId());
            if(people!=null){
//                kqGatherMonth.setBranchId(people.getBranchId());
                kqGatherMonth.setPeopleId(people.getId());
                kqGatherMonth.setGh(people.getGh());
                kqGatherMonth.setName(people.getName());
                kqGatherMonth.setJoinTime(people.getJoinTime());
                //统计数据
                //实际出勤天数
                KqGather kqGather=new KqGather();
                kqGather.setPeopleId(people.getId());
                kqGather.setStartTime(kqGatherMonth.getStartTime());
                kqGather.setEndTime(kqGatherMonth.getEndTime());
                List<KqGather> gatherList= gatherMapper.selectKqGatherList(kqGather);
                long sjcqsj=Long.valueOf(gatherList.size());
                kqGatherMonth.setSjcqsj(sjcqsj);
                //病假
                KqAdjust adjust=new KqAdjust();
                adjust.setUserId(people.getId());
                //8.25-9.26
                adjust.setStartTime(kqGatherMonth.getStartTime());
                adjust.setEndTime(kqGatherMonth.getEndTime());
                adjust.setType("0");
                double bj=0;
                List<KqAdjust>  bjList= adjustMapper.selectKqAdjustList(adjust);
                for(KqAdjust a:bjList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        //8.24-10.1
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        bj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){//8.24-9.15
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        bj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){//8.26-10.1
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        bj+=days;
                    }else{//8.26-9.24
                        bj+=a.getDays();
                    }
                }
                kqGatherMonth.setBj(bj);
                //事假
                adjust.setType("1");
                List<KqAdjust>  sjList= adjustMapper.selectKqAdjustList(adjust);
                double sj=0;
                for(KqAdjust a:sjList){
                    //sj+=a.getDays();
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        sj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        sj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        sj+=days;
                    }else{
                        sj+=a.getDays();
                    }
                }
                kqGatherMonth.setSj(sj);
                //调休
                adjust.setType("2");
                List<KqAdjust>  txList= adjustMapper.selectKqAdjustList(adjust);
                double tx=0;
                for(KqAdjust a:txList){
                    //tx+=a.getDays();
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        tx+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        tx+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        tx+=days;
                    }else{
                        tx+=a.getDays();
                    }
                }
                kqGatherMonth.setTx(tx);
                //年假
                adjust.setType("3");
                List<KqAdjust>  njList= adjustMapper.selectKqAdjustList(adjust);
                double nj=0;
                for(KqAdjust a:njList){
                    //nj+=a.getDays();
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        nj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        nj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        nj+=days;
                    }else{
                        nj+=a.getDays();
                    }
                }
                kqGatherMonth.setNj(nj);
                //婚假
                adjust.setType("4");
                List<KqAdjust>  hjList= adjustMapper.selectKqAdjustList(adjust);
                double hj=0;
                for(KqAdjust a:hjList){
                    //hj+=a.getDays();
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        hj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        hj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        hj+=days;
                    }else{
                        hj+=a.getDays();
                    }
                }
                kqGatherMonth.setHj(hj);
                //陪产假
                adjust.setType("11");
                List<KqAdjust>  pcjList= adjustMapper.selectKqAdjustList(adjust);
                double pcj=0;
                for(KqAdjust a:pcjList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        pcj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        pcj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        pcj+=days;
                    }else{
                        pcj+=a.getDays();
                    }
                }
                kqGatherMonth.setPcj(pcj);
                //产假
                adjust.setType("10");
                List<KqAdjust>  cjList= adjustMapper.selectKqAdjustList(adjust);
                double cj=0;
                for(KqAdjust a:cjList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        cj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        cj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        cj+=days;
                    }else{
                        cj+=a.getDays();
                    }
                }
                kqGatherMonth.setCj(cj);
                //出差
                adjust.setType("9");
                List<KqAdjust>  ccList= adjustMapper.selectKqAdjustList(adjust);
                double cc=0;
                for(KqAdjust a:ccList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        cc+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        cc+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        cc+=days;
                    }else{
                        cc+=a.getDays();
                    }
                }
                kqGatherMonth.setCc(cc);
                //丧假
                adjust.setType("8");
                List<KqAdjust>  sanjList= adjustMapper.selectKqAdjustList(adjust);
                double sanj=0;
                for(KqAdjust a:sanjList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        sanj+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        sanj+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        sanj+=days;
                    }else{
                        sanj+=a.getDays();
                    }
                }
                kqGatherMonth.setSanj(sanj);
                //工伤
                adjust.setType("7");
                List<KqAdjust>  gsList= adjustMapper.selectKqAdjustList(adjust);
                double gs=0;
                for(KqAdjust a:gsList){
                    if(adjust.getStartTime().getTime()>a.getStartTime().getTime()&&adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),adjust.getEndTime());
                        gs+=days;
                    }else if(adjust.getStartTime().getTime()>a.getStartTime().getTime()){
                        double days=this.GetDateDiff(adjust.getStartTime(),a.getEndTime());
                        gs+=days;
                    }else if(adjust.getEndTime().getTime()<a.getEndTime().getTime()){
                        double days=this.GetDateDiff(a.getStartTime(),adjust.getEndTime());
                        gs+=days;
                    }else{
                        gs+=a.getDays();
                    }
                }
                kqGatherMonth.setGs(gs);
                //平时加班（h）
                long psjb=0L;
                long zmjb=0L;
                long jbts=0L;
                long cdfz=0L;
                long ztfz=0L;
                long qkcs=0L;
                for(KqGather g:gatherList){
                    if(StringUtils.isNotEmpty(g.getOverTime())){
                        if(!"3".equals(g.getWorkStatus())){
                            psjb+=Long.parseLong(g.getOverTime())/60;
                        }else{
                            zmjb+=Long.parseLong(g.getOverTime())/60;
                            jbts++;
                        }
                    }
                    if(StringUtils.isNotEmpty(g.getLateTime())){
                        cdfz+=Long.parseLong(g.getLateTime());
                    }
                    if(StringUtils.isNotEmpty(g.getLeaveTime())){
                        ztfz+=Long.parseLong(g.getLeaveTime());
                    }
                    if(!"3".equals(g.getWorkStatus())){//周末加班不计入缺卡数
                        if(g.getClassesNum()==1){
                            if(g.getWorkKqTime()==null){
                                qkcs++;
                            }
                            if(g.getOutKqTime()==null){
                                qkcs++;
                            }
                        }
                        if(g.getClassesNum()==2){
                            if(g.getWorkKqTime()==null){
                                qkcs++;
                            }
                            if(!"true".equals(isKq)){
                                if(g.getOutKqTime()==null){
                                    qkcs++;
                                }
                            }
                            if(g.getWorkKqTime1()==null){
                                qkcs++;
                            }
                            if(g.getOutKqTime1()==null){
                                qkcs++;
                            }
                        }
                    }
                }
                kqGatherMonth.setPsjb(psjb);
                //周末加班（h）
                kqGatherMonth.setZmjb(zmjb);
                //加班天数
                kqGatherMonth.setJbts(jbts);
                //迟到分钟
                kqGatherMonth.setCdfz(cdfz);
                //早退分钟
                kqGatherMonth.setZtfz(ztfz);
                //补卡次数
                adjust.setType("5");
                List<KqAdjust>  bkList= adjustMapper.selectKqAdjustList(adjust);
                kqGatherMonth.setBkcs(Long.valueOf(bkList.size()));
                //缺卡次数
                kqGatherMonth.setQkcs(qkcs);
                //汇总
                kqGatherMonth.setHz(sjcqsj+bj+sj+tx+nj+hj+pcj+cj+cc+sanj+gs);
                kqGatherMonthMapper.deleteKqGatherMonth(kqGatherMonth);
                kqGatherMonthMapper.insertKqGatherMonth(kqGatherMonth);
            }
        }

        return 1;
    }

    private double GetDateDiff(Date startTime, Date endTime) {
        double bj=0;
        double hour=(endTime.getTime()-startTime.getTime())/(1000*3600);
        double days=hour/24;
        double hours=hour%24;
        if(hours>4){
            bj+=days+1;
        }else if(hours==0){
            bj+=days;
        }else{
            bj+=days+0.5;
        }
        return bj;
    }

    @Override
    public int createKqGather() {
        KqGather kqGather=new KqGather();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String isKq = configService.selectConfigByKey("sys_kq_dk");
        try {
            kqGather.setKqTime( sdf1.parse(sdf1.format(new Date())));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        List<KqGather> gatherList= gatherMapper.selectKqGatherList(kqGather);
        for(KqGather g:gatherList){
            long qkcs=0L;
            if(g.getClassesNum()==1){
                if(g.getWorkKqTime()==null){
                    qkcs++;
                }
                if(g.getOutKqTime()==null){
                    qkcs++;
                }
            }
            if(g.getClassesNum()==2){
                if(g.getWorkKqTime()==null){
                    qkcs++;
                }
                if(g.getOutKqTime()==null){
                    qkcs++;
                }
                if(!"true".equals(isKq)){
                    if(g.getWorkKqTime1()==null){
                        qkcs++;
                    }
                }
                if(g.getOutKqTime1()==null){
                    qkcs++;
                }
            }
            g.setQkcs(qkcs);
            gatherMapper.updateKqGather(g);
        }
        return 1;
    }

    /**
     * 获取开始时间和结束时间
     */
    private KqTime getTime() {
        KqTime kqTime = new KqTime();
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 获取本月26号
        LocalDate thisMonth = now.with(TemporalAdjusters.firstDayOfMonth())
                .plusDays(25);
        if(now.isAfter(thisMonth)) {
            // 当前时间加一个月
            LocalDate plusNow = now.plusMonths(1);
            // 获取下个月的第一天
            LocalDate plusMonths = plusNow.with(TemporalAdjusters.firstDayOfMonth());
            // 获取下个月的25号
            LocalDate endTime = plusMonths.with(TemporalAdjusters.firstDayOfMonth())
                    .plusDays(24);
            kqTime.setStartTime(String.valueOf(thisMonth));
            kqTime.setEndTime(String.valueOf(endTime));
        } else {
            // 当前时间减一个月
            LocalDate minusNow = now.minusMonths(1);
            // 获取上个月的第一天
            LocalDate firstDay = minusNow.with(TemporalAdjusters.firstDayOfMonth());
            // 获取上个月的26号
            LocalDate startTime = firstDay.with(TemporalAdjusters.firstDayOfMonth())
                    .plusDays(25);
            // 获取本月的25号
            LocalDate endTime = now.with(TemporalAdjusters.firstDayOfMonth())
                    .plusDays(24);
            kqTime.setStartTime(String.valueOf(startTime));
            kqTime.setEndTime(String.valueOf(endTime));
        }
        return kqTime;
    }
}
