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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.K;
import com.dcsoft.common.core.exception.ServiceException;
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.kq.service.IKqGatherService;
import com.dcsoft.system.mapper.SysPeopleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


/**
 * 考勤汇总Service业务层处理
 *
 * @author dcsoft
 * @date 2023-06-12
 */
@Service
public class KqGatherServiceImpl implements IKqGatherService
{
    @Autowired
    private KqGatherMapper kqGatherMapper;

    @Autowired
    private SysPeopleMapper peopleMapper;

    @Resource
    private KqAdjustMapper kqAdjustMapper;

    @Resource
    private KqHolidayGroupMapper kqHolidayGroupMapper;


    /**
     * 查询考勤汇总
     *
     * @param id 考勤汇总主键
     * @return 考勤汇总
     */
    @Override
    public KqGather selectKqGatherById(Long id)
    {
        return kqGatherMapper.selectKqGatherById(id);
    }

    /**
     * 查询考勤汇总列表
     *
     * @param kqGather 考勤汇总
     * @return 考勤汇总
     */
    @Override
    public List<KqGather> selectKqGatherList(KqGather kqGather)
    {
        return kqGatherMapper.selectKqGatherList(kqGather);
    }

    /**
     * 新增考勤汇总
     *
     * @param kqGather 考勤汇总
     * @return 结果
     */
    @Override
    public int insertKqGather(KqGather kqGather)
    {
        kqGather.setCreateTime(DateUtils.getNowDate());
        return kqGatherMapper.insertKqGather(kqGather);
    }

    /**
     * 修改考勤汇总
     *
     * @param kqGather 考勤汇总
     * @return 结果
     */
    @Override
    public int updateKqGather(KqGather kqGather)
    {
        kqGather.setUpdateTime(DateUtils.getNowDate());
        return kqGatherMapper.updateKqGather(kqGather);
    }

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

    /**
     * 删除考勤汇总信息
     *
     * @param id 考勤汇总主键
     * @return 结果
     */
    @Override
    public int deleteKqGatherById(Long id)
    {
        return kqGatherMapper.deleteKqGatherById(id);
    }

    @Override
    public int deleteKqGatherByKqGather(KqGather kqGather) {
        return kqGatherMapper.deleteKqGatherByKqGather(kqGather);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importkqGather(List<KqGather> userList, boolean isUpdateSupport, String operName)
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2=new SimpleDateFormat("HH:mm:ss");

        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (KqGather gather : userList)
        {
            try
            {
                gather.setQkcs(0L);
                gather.setWorkTime(null);
                gather.setOutTime(null);
                gather.setWorkTime1(null);
                gather.setOutTime1(null);

                if(gather.getKqTime()==null){
                    failureNum++;
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：未输入考勤日期！");
                }
                if(StringUtils.isEmpty(gather.getPeopleName())){
                    failureNum++;
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：未输入人员！");
                }
                if(gather.getWorkKqTime()!=null){
                    String WorkKqTime=sdf.format(gather.getKqTime())+" "+sdf2.format(gather.getWorkKqTime());
                    gather.setWorkKqTime(sdf1.parse(WorkKqTime));
                }
                if(gather.getWorkKqTime1()!=null){
                    String WorkKqTime1=sdf.format(gather.getKqTime())+" "+sdf2.format(gather.getWorkKqTime1());
                    gather.setWorkKqTime1(sdf1.parse(WorkKqTime1));
                }
                if(gather.getOutKqTime()!=null){
                    String outKqTime=sdf.format(gather.getKqTime())+" "+sdf2.format(gather.getOutKqTime());
                    gather.setOutKqTime(sdf1.parse(outKqTime));
                }
                if(gather.getOutKqTime1()!=null){
                    String outKqTime1=sdf.format(gather.getKqTime())+" "+sdf2.format(gather.getOutKqTime1());
                    gather.setOutKqTime1(sdf1.parse(outKqTime1));
                }

                // 验证是否存在这个用户
                KqGather u = kqGatherMapper.selectKqGatherByGather(gather);
                SysPeople people=peopleMapper.selectSysPeopleByBranchUser(gather.getBranchName(),gather.getPeopleName());
                if(people!=null){
                    gather.setPeopleId(people.getId());
//                    gather.setBranchId(people.getBranchId());
                }
                if (StringUtils.isNull(u))
                {
                    gather.setCreateBy(operName);
                    this.insertKqGather(gather);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员"+sdf.format(gather.getKqTime())+"日汇总 " + gather.getPeopleName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    gather.setId(u.getId());
                    gather.setUpdateBy(operName);
                    this.updateKqGather(gather);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员"+sdf.format(gather.getKqTime())+"日汇总 " + gather.getPeopleName()+  " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、人员"+sdf.format(gather.getKqTime())+"日汇总 " + gather.getPeopleName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、人员"+sdf.format(gather.getKqTime())+"日汇总" + gather.getPeopleName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增请假日汇总数据
     */
    @Override
    public void saveAskForLeave() throws ParseException {
        // 查询今日请假请假人信息
        List<KqAskForLeave> forLeaves = kqAdjustMapper.queryAskForLeaveInfo();

        // 处理请假信息数据
        List<KqGather> list = new ArrayList<>();

        for (KqAskForLeave forLeaf : forLeaves) {
            List<KqGather> time = getTime(forLeaf.getStartTime(), forLeaf.getEndTime());
            for (KqGather gather : time) {
                gather.setGroupName(forLeaf.getGroupName());
                gather.setGroupId(forLeaf.getGroupId());
                gather.setClassesId(forLeaf.getClassesId());
                gather.setPeopleId(forLeaf.getUserId());
                gather.setBranchId(forLeaf.getBranchId());
                gather.setQkcs(0L);
                list.add(gather);
            }
        }
        for (KqGather gather : list) {
            kqGatherMapper.updateGathe(gather);
        }



        // 查询今日没有考勤人员
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<KqGroupUser> leaveList = kqAdjustMapper.queryAskForLeave();
        List<KqHolidayGroup> kqHolidayGroups = kqHolidayGroupMapper.selectKqHolidayGroupList(new KqHolidayGroup());
        // 去除休息人员
        leaveList.removeIf(c -> kqHolidayGroups.stream().anyMatch(n -> n.getGroupId().equals(c.getGroupId()) && sdf.format(date).equals(sdf.format(n.getTime()))));

        // 去除请假人员
        leaveList.removeIf(c -> list.stream().anyMatch(n -> n.getPeopleId().equals(c.getUserId()) && sdf.format(date).equals(sdf.format(n.getKqTime()))));
        List<KqGather> gatherList = kqAdjustMapper.queryGroupUser(leaveList);
        for (KqGather gather : gatherList) {
            gather.setKqTime(date);
        }
        if(!CollectionUtils.isEmpty(gatherList)) {
            kqGatherMapper.saveAskForLeave(gatherList);
        }

        // 处理已补卡还是异常情况
        updateKqGather();

    }

    /**
     * 补卡信息
     */
    @Override
    public void saveCardReplacement(KqAdjust kqAdjust) {
        if(null == kqAdjust.getUserId() || null == kqAdjust.getStartTime()) {
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        kqSummary kqSummary = new kqSummary();
        switch (kqAdjust.getCheckInPoint()) {
            case "1":
                kqSummary.setWorkKqTime(sdf.format(kqAdjust.getStartTime()));
                break;
            case "2":
                kqSummary.setOutKqTime(sdf.format(kqAdjust.getStartTime()));
                break;
            case "3":
                kqSummary.setWorkKqTime1(sdf.format(kqAdjust.getStartTime()));
                break;
            case "4":
                kqSummary.setOutKqTime1(sdf.format(kqAdjust.getStartTime()));
                break;
        }
        kqSummary.setPeopleId(kqAdjust.getUserId());
        kqSummary.setStartTime(sdf.format(kqAdjust.getStartTime()));
        kqSummary.setQkcs("0");
        kqAdjustMapper.updateCardReplacement(kqSummary);

    }


    /**
     * 处理已补卡还是异常情况
     */
    private void updateKqGather() {
        // 查询今日出勤调整时间
        List<KqWorkingHours> hoursList = kqAdjustMapper.queryAttendanceAdjustList();
        String collect = hoursList.stream().map(KqWorkingHours :: getLeaveTime).collect(Collectors.joining());
        // 处理已补卡还是异常情况
        if(!CollectionUtils.isEmpty(hoursList)) {
            kqAdjustMapper.updateKqGather(hoursList, collect);
        }
    }

    /**
     * 获取时间
     * @param startDate
     * @param endDate
     */
    private List<KqGather> getTime(String startDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<KqGather> list = new ArrayList<>();
        while (!start.isAfter(end)) {
            KqGather gather = new KqGather();
            gather.setKqTime(sdf.parse(start.toString()));
            list.add(gather);
            start = start.plusDays(1);
        }
        return list;
    }
}
