package com.bonus.system.att.service;

import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.att.dao.AttendanceDetailsDao;
import com.bonus.system.att.entity.*;
import com.bonus.system.att.tasks.AttTasks;
import com.bonus.system.att.tasks.WechatTasks;
import com.bonus.system.basic.domain.SysNotice;
import com.bonus.system.basic.service.SysNoticeService;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.file.service.FileUploadService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考勤明细-业务层
 *
 * @author zys
 */
@Service("attendanceDetailsService")
@Log4j2
public class AttendanceDetailsServiceImpl implements AttendanceDetailsService {

    @Resource(name = "attendanceDetailsDao")
    private AttendanceDetailsDao attendanceDetailsDao;

    @Resource(name = "ProDeptRoleDao")
    private ProDeptRoleDao proDeptRoleDao;

    @Resource
    private AttTasks attTasks;

    /**
     * 消息推送库表
     */
    @Resource
    private SysNoticeService noticeService;

    @Resource(name = "FileUploadService")
    private FileUploadService fileUploadService;

    @Override
    public List<AttDataDetailsBean> selectAttDetailsList(AttDataDetailsBean bean) {
        List<AttDataDetailsBean> list = attendanceDetailsDao.selectAttDetailsList(bean);
        for (AttDataDetailsBean vo : list) {
            List<AttDataDetailsBean.FilesVo> filesVoList = fileUploadService.getFiles(vo);
            vo.setFilesVoList(filesVoList);
        }
        return list;
    }

    @Override
    public List<AttDataDetailsBean> exportAttDetailsList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.exportAttDetailsList(bean);
    }


    @Override
    public List<AttDataDetailsBean> selectAttOriginalList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.selectAttOriginalList(bean);
    }

    @Override
    public List<AttDataDetailsBean> exportAttOriginalsList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.exportAttOriginalsList(bean);
    }

    @Override
    public int updateAttDetailsData(List<AttDataDetailsBean> list) {
        // 判断考勤修改的数据是否有处于人资审核中，如果只是处于部门领导审核中则可以修改

        int i = attendanceDetailsDao.updateAttDetailsData(list);
        fileUploadService.saveAttUpdateFileSource(list);
        if (i > 0) {
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            List<Long> orgList = new ArrayList<>();
            list.forEach(o -> {
                //获取当前用户id
                orgList.add(o.getOrgId());
            });
            //获取部门考勤员
            List<Long> userList = noticeService.getAttUserIdByOrgId(orgList);
            // 将 List 转换为数组
            if (!userList.isEmpty()) {
                Long[] userIds = userList.toArray(new Long[0]);
                //发送审批消息
                SysNotice bean = new SysNotice();
                bean.setUserIds(userIds);
                bean.setUserId(userId);
                bean.setTitle("考勤明细修改申请");
                bean.setContent("考勤明细修改申请");
                bean.setType("71");
                bean.setValue("");
                //推送消息
                noticeService.insertNotice(bean);
            }
        }
        return i;
    }

    @Override
    public int updateAttDetailsDataExamine(List<AttDataDetailsBean> list) {
        long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        String time = DateUtils.getTime();
        list.forEach(c -> {
            c.setReviewerUserId(userId);
            c.setReviewerTime(time);
        });
        int i = attendanceDetailsDao.updateAttDetailsDataExamine(list);
        if(i>0){
            Set<String> keys = new HashSet<>();
            for (AttDataDetailsBean attDataDetailsBean : list) {
                keys.add(attDataDetailsBean.getAttCurrentDay());
            }
            // 使用增强的 for 循环遍历 Set
            for (String item : keys) {
                List<AttGroupBean> groupList = attTasks.getGroupData(item);
                attTasks.createReportData(groupList, item, 2);
            }
        }
        return i;
    }

    @Override
    public List<AttDataDetailsBean> selectAttUpdateList(AttDataDetailsBean bean) {
        //只能查自己分公司的人
//        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
//        List<String> roleId = sysUser.getRoleList();
//        if(roleId !=null && !roleId.isEmpty() ){
//        if (Collections.frequency(roleId, "1")==0) {
//            List<MapVo> orgList = SecurityUtils.getLoginUser().getSysUser().getOrgList();
//            if (!orgList.isEmpty()) {
//                ArrayList<String> ids = new ArrayList<>();
//                for (MapVo mapVo : orgList) {
//                    ids.add(String.valueOf(mapVo.getId()));
//                }
//                bean.setOrgList(ids);
//            }
//        }
//        }
        return attendanceDetailsDao.selectAttUpdateList(bean);
    }

    @Override
    public List<AttDayReportBean> getAttDayReportList(AttDayReportBean bean) {
        return selectAttDayReportList(bean);
    }

    public List<AttDayReportBean> selectAttDayReportList(AttDayReportBean bean) {
        List<AttDayReportBean> list = attendanceDetailsDao.getAttDayReportList(bean);
        if (bean.getOrgId() != null) {
            return list.stream().filter(c -> Objects.equals(c.getOrgId(), bean.getOrgId()))
                    .collect(Collectors.toList());
        } else {
            return getAttDayReportListAll(list);
        }
    }

    @Override
    public List<AttMonthReportBean> getAttMonthReportList(AttMonthReportBean bean) {
        List<AttMonthReportBean> attMonthReportList = attendanceDetailsDao.getAttMonthReportList(bean);
        // 查询打卡记录
        attMonthReportList.forEach(c -> {
            int clockingRecordNum = attendanceDetailsDao.getClockingRecordNum(c);
            c.setClockingRecordNum(clockingRecordNum);
        });
        return attMonthReportList;
    }

    @Override
    public void exportAttDayReportData(HttpServletResponse response, AttDayReportBean o) {
        String title = o.getStartDate() + "~" + o.getEndDate() + "-日报表";
        List<AttDayReportBean> list = selectAttDayReportList(o);
        ExcelUtil<AttDayReportBean> util = new ExcelUtil<>(AttDayReportBean.class);
        util.exportExcel(response, list, title, title);
    }

    @Override
    public void exportAttMonthReportData(HttpServletResponse response, AttMonthReportBean o) {
        String title = o.getMonth() + "-月报表";
        List<AttMonthReportBean> list = attendanceDetailsDao.getAttMonthReportList(o);
        ExcelUtil<AttMonthReportBean> util = new ExcelUtil<>(AttMonthReportBean.class);
        util.exportExcel(response, list, title, title);
    }

    @Override
    public List<AttDataDetailsBean> getAttDayReportDetailsList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getAttDayReportDetailsList(bean);
    }

    @Override
    public List<AttDataDetailsBean> getAttDayReportDetailsListData(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getAttDayReportDetailsListData(bean);
    }

    @Override
    public List<AttDataDetailsBean> getOutCountList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getOutCountList(bean);
    }

    @Override
    public AjaxResult synchronous(AttDataDetailsBean bean) {
        try {
            List<String> dateList = AttTasks.getStrDateListBetween(bean.getStartDate(), bean.getEndDate());
            //只执行今天之前的时间（包含今天）
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            dateList = dateList.stream()
                    .map(date -> LocalDate.parse(date, formatter)) // 将字符串转换为LocalDate
                    .filter(date -> !date.isAfter(today)) // 筛选出今天及之前的日期
                    .sorted() // 按日期排序（可选）
                    .map(formatter::format) // 将LocalDate转回为字符串
                    .collect(Collectors.toList());
            attTasks.hisAttPush(dateList);
            return AjaxResult.success("数据同步成功");
        }catch (Exception e){
            log.error(e.toString(),e);
            return AjaxResult.error("数据同步失败");
        }
    }

    @Override
    public List<AttDataDetailsBean> getAttDayList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getAttDayList(bean);
    }

    @Override
    public List<AttDataDetailsBean> getAttCountList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getAttCountList(bean);
    }

    @Override
    public List<AttDataDetailsBean> getOrgUserOutCountList(AttDataDetailsBean bean) {
        return attendanceDetailsDao.getOrgUserOutCountList(bean);
    }

    @Override
    public List<MapVo> getAttStatusList() {
        return attendanceDetailsDao.getAttStatusList();
    }

    public List<AttDayReportBean> getAttDayReportListAll(List<AttDayReportBean> list) {
        List<AttDayReportBean> allList = new ArrayList<>();
        Map<String, AttDayReportBean> map = list.stream()
                .collect(Collectors.toMap(
                        AttDayReportBean::getAttCurrentDay,
                        obj -> new AttDayReportBean(obj.getAttCurrentDay(), obj.getNormalNum(), obj.getLateNum(),
                                obj.getEarlyNum(), obj.getSkippingNum(), obj.getLeaveNum(), obj.getAddressErrorNum(),
                                obj.getEinErrorNum(), obj.getRestNum(), obj.getOutNum(), obj.getOutCount()),
                        (existing, replacement) -> new AttDayReportBean(
                                existing.getAttCurrentDay(),
                                existing.getNormalNum() + replacement.getNormalNum(),
                                existing.getLateNum() + replacement.getLateNum(),
                                existing.getEarlyNum() + replacement.getEarlyNum(),
                                existing.getSkippingNum() + replacement.getSkippingNum(),
                                existing.getLeaveNum() + replacement.getLeaveNum(),
                                existing.getAddressErrorNum() + replacement.getAddressErrorNum(),
                                existing.getEinErrorNum() + replacement.getEinErrorNum(),
                                existing.getRestNum() + replacement.getRestNum(),
                                existing.getOutNum() + replacement.getOutNum(),
                                existing.getOutCount() + replacement.getOutCount()
                        )
                ));
        map.forEach((k, v) -> {
            allList.add(v);
        });
        return allList;
    }

    @Override
    public List<AttClockingRecordVo> getClockingRecordListByUserId(AttMonthReportBean bean) {
        List<AttClockingRecordVo> list = new ArrayList<>();
        try {
            list = attendanceDetailsDao.getClockingRecordListByUserId(bean);
        } catch (Exception e) {
            log.error(e.toString(),e);
        }
        return list;
    }
}
