package com.qy.worksheetsystem.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.qy.worksheetsystem.entity.AppProJect;
import com.qy.worksheetsystem.entity.JobBook;
import com.qy.worksheetsystem.entity.JobBooking;
import com.qy.worksheetsystem.entity.Poject;
import com.qy.worksheetsystem.model.MessageResult;

import com.qy.worksheetsystem.model.MessageResultV2;
import com.qy.worksheetsystem.model.mapper.EmployeeReportingMapper;
import com.qy.worksheetsystem.model.mapper.ProjectMapper;
import com.qy.worksheetsystem.model.mapper.THRATSWorkCalendarItemMapper;
import com.qy.worksheetsystem.model.mapper.WorkSheetMapper;
import com.qy.worksheetsystem.service.CTWORAttendanceTypeService;
import com.qy.worksheetsystem.util.HutoolCacheUtils;
import com.qy.worksheetsystem.vo.InsertJobBookingEnteyVO;
import com.qy.worksheetsystem.vo.InsertJobBookingVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * description: EmployeeReportingServiceImpl <br>
 * date: 2022/3/10 15:01 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
@Slf4j
@Service
public class EmployeeReportingServiceImpl {
    @Resource
    private ProjectServiceImpl projectService;
    @Resource
    private EmployeeReportingMapper mapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private WeiXinAuthorizeServiceImpl wXService;
    @Resource
    private THRATSWorkCalendarItemMapper HRWorkmapper;
    @Resource
    private CTWORAttendanceTypeService attendanceTypeService;
    @Resource
    private WorkSheetMapper workSheetMapper;
    @Value("${HR.EmployeeType}")
    private String EmployeeType;
    @Value("${HR.LeaveType}")
    private String LeaveType;
    @Value("${HR.AttendanceType}")
    private String AttendanceType;
    @Value("${HR.tripType}")
    private String tripType;
    @Value("${HR.OrgNumber}")
    private String OrgNumber;
    @Value("${weixin.url}")
    private String WXUrl;


    public boolean checkAvailableDate(LocalDate date){
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime localDateTime8 = LocalDateTime.of(nowTime.getYear(), nowTime.getMonth(), 8, 0, 0);
        //默认可填报日期
        LocalDateTime startDate =  LocalDateTime.of(nowTime.getYear(), nowTime.getMonth(), 1, 0, 0);

        if(nowTime.compareTo(localDateTime8)<0){
            startDate=startDate.plusMonths(-1);
        }
        LocalDate begin1 = date;
        LocalDateTime begin = begin1.atTime(0,0);
        return (startDate.compareTo(begin)<=0) ? true : false;
    }

    public boolean checkAvailableDate(String dateStr){
        LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
       return this.checkAvailableDate(date);
    }
    public List<Map<String, Object>> getCacheProjectByPNumberV3(String number,String OrgNumber){
        String key ="getCacheProjectByPNumberV3_"+number;
        List<Map<String, Object>> listMap = (List<Map<String, Object>>) HutoolCacheUtils.get(key);
        if(null==listMap){
            listMap =  projectMapper.getProjectByPNumberV3(number,OrgNumber);
            HutoolCacheUtils.put(key,listMap);
        }
        return listMap;
    }
    public Map<String, Object> getShrPersonInfo(String number){
        List<Map<String, Object>> listMap = this.getCacheProjectByPNumberV3(number,OrgNumber);
        Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
        if(!listMap.isEmpty()){
            personInfo.put("isAuditor","1");
        }
        return personInfo;
    }

    public synchronized void insert(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>();
        String number = (String) map.get("number");
        String beginTime = (String) map.get("beginTime");
        String endTime = (String) map.get("endTime");
        Date beginDate = (Date) map.get("beginDate");
        Date endDate = (Date) map.get("endDate");
        String attendanceType = (String) map.get("attendanceType");
        String workingHours = (String) map.get("workingHours");
        String projectId = (String) map.get("projectId");
        String state = (String) map.get("state");
        Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
        Map<String, Object> adminInfo = mapper.getShrAdminInfo(projectId);
        String personId = (String) personInfo.get("personId");

        String userid = (String) personInfo.get("userid");
        String name = (String) personInfo.get("personName");
        String CFOrgID = (String) adminInfo.get("orgId");
        String managerId = (String) personInfo.get("managerId");
        String managerName = (String) personInfo.get("managerName");
        String managerNumber = (String) personInfo.get("managerNumber");
        Map<String, String> billMap = new HashMap<>();
        billMap.put("FCreatorID", userid);
        billMap.put("CFauditorAndNumber", managerName + "-" + managerNumber);

        billMap.put("FLastUpdateUserID", userid);
        billMap.put("FDescription", "");
        billMap.put("CFPersonID", personId);
        billMap.put("CFOrgID", CFOrgID);
        String yearAndMonth = beginTime.substring(0, 7);
        billMap.put("CFYearAndMonth", yearAndMonth);
        billMap.put("CFAttendanceID", attendanceType);

        billMap.put("CFStatus", state);

        int begin = Integer.parseInt(beginTime.substring(8, 10));
        int end = Integer.parseInt(endTime.substring(8, 10));
        if(begin == end){
            billMap.put("CFTitle", begin + "号");
        }else{
            billMap.put("CFTitle", begin + "-" + end + "号");
        }

        billMap.put("CFBeginDate", beginTime);
        billMap.put("CFEndDate", endTime);
        billMap.put("CFPersonNumber", number);
        billMap.put("CFNameAndNumber", name + "-" + number);
        Map<String, String> sDateMap = new HashMap<>();
        sDateMap.put("startDate", beginTime);
        sDateMap.put("endDate", endTime);
        List<Map<String, String>> dateTypeList = HRWorkmapper.selectWorkCalendar(sDateMap);
        log.info(JSONUtil.toJsonStr(dateTypeList));
        List<Map<String, String>> entryList = new ArrayList<>();
        BigDecimal decimal = BigDecimal.ZERO;
        int j = 0;
        for (int i = begin; i <= end; i++) {
            j += 1;
            Map<String, String> entryMap = new HashMap<>();
            entryMap.put("Fseq", j + "");
            entryMap.put("FParentID", "");
            entryMap.put("CFauditorAndNumber", managerName + "-" + managerNumber);
            entryMap.put("CFPersonID", personId);
            entryMap.put("CFApproverID", managerId);
            entryMap.put("CFOrgID", CFOrgID);
            String iday = "01";
            if (i < 10) {
                iday = "0" + i;
            } else {
                iday = i + "";
            }
            String CFReportDate = beginTime.substring(0, 8) + iday;
            entryMap.put("CFReportDate", CFReportDate);
            entryMap.put("CFYearAndMonth", yearAndMonth);
            entryMap.put("CFAttendanceID", attendanceType);
            entryMap.put("CFStatus", state);
            for (Map<String, String> temp : dateTypeList) {
                String FDate = temp.get("FDate").substring(0, 10);
                String dateType = temp.get("dateType");
                if (CFReportDate.equals(FDate)) {
                    switch (dateType) {
                        case "0":
                            decimal = decimal.add(new BigDecimal(workingHours));
                            entryMap.put("CFWorkingHours", workingHours);
                            entryMap.put("CFCalendarType", "0");
                            break;
                        case "1":
                            entryMap.put("CFWorkingHours", "0");
                            entryMap.put("CFCalendarType", "1");
                            break;
                        case "2":
                            decimal = decimal.add(new BigDecimal(workingHours));
                            entryMap.put("CFWorkingHours", workingHours);
                            entryMap.put("CFCalendarType", "2");
                            break;
                        default:
                            break;
                    }
                    break;
                }
            }
            entryMap.put("CFPersonNumber", number);
            entryMap.put("CFNameAndNumber", name + "-" + number);
            entryMap.put("CFPersonDeptID", CFOrgID);
            entryMap.put("CFYsName", (String) adminInfo.get("orgName"));

            entryList.add(entryMap);
        }
        String billId = mapper.selectKey();
        billMap.put("CFWorkingHours", decimal.toPlainString());
        billMap.put("billId", billId);
        int bill = mapper.insertBill(billMap);

        for (Map<String, String> temp : entryList) {
            temp.put("FParentID", billId);
        }
        mapper.insertEntry(entryList);
    }

    public List<Map<String,String>> getReportDateWorkHoursByPerson(String personId,String reportDate){
        return mapper.getReportDateWorkHoursByPerson(personId,reportDate);
    }

    /**
     *
     * @param number
     * @param beginTime
     * @param endTime
     * @param workingHour
     * @return
     */
    public MessageResult checkAttWinter(String number,String beginTime,String endTime,int workingHour){
        try {
            String[] dateArr = beginTime.split("-");
            String[] dateEndArr = endTime.split("-");
            Month month = Month.of(Integer.parseInt(dateArr[1]));
            LocalDate localDate = LocalDate.of(Integer.parseInt(dateArr[0]), month, 1);
            LocalDate stratLocalDate = localDate.plusMonths(-2);
            Month monthEnd = Month.of(Integer.parseInt(dateEndArr[1]));
            LocalDate endLocalDate = LocalDate.of(Integer.parseInt(dateEndArr[0]),
                    monthEnd,
                    monthEnd.length(stratLocalDate.isLeapYear()));
            //获取shr年假额度
            Map<String, Object> holidayLimit = attendanceTypeService.getHolidayLimit(number);
            //获取在途的年假
            Map<String, Object> map = mapper.getJobDayByPerson(number, null,
                    stratLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
                    endLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE), AttendanceType, "2");
            int transit = 0;
            if (null != map) {
                transit = (int) map.get("workinghours");
            }
            //获取已用的年假
            Map<String, Object> map1 = mapper.getJobDayByPerson(number, null,
                    stratLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
                    , endLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
                    AttendanceType, "3");
            int used = 0;
            if (null != map1) {
                used = (int) map1.get("workinghours");
            }
            BigDecimal remainLimit = BigDecimal.ZERO;
            if (null != holidayLimit) {
                remainLimit = (BigDecimal) holidayLimit.get("remainLimit");
            }

            int workingHours = 0;
            List<Map<String, String>> listDay = HRWorkmapper.selectWorkCalendarV2(beginTime, endTime);
            for (Map<String, String> stringMap : listDay) {
                String dateType = stringMap.get("dateType");
                //是工作日则增加
                if ("0".equals(dateType)) {
                    workingHours += workingHour;
                }
            }

            //加上在途的
            workingHours = workingHours+transit+used;
            if(remainLimit.intValue()<=0){
                MessageResult result = new MessageResult();
                result.setCode(403);
                result.setMsg("剩余年假额度不足");
                return result;
            }else if (workingHours > remainLimit.intValue()) {
                MessageResult result = new MessageResult();
                result.setCode(403);
                result.setMsg("剩余年假额度不足");
                return result;
            } else {
                return MessageResult.success();
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            MessageResult result = new MessageResult();
            result.setCode(500);
            result.setMsg("校验异常，请联系管理员");
            return result;
        }finally {

        }
    }

    @Transactional
    public synchronized MessageResult insertV3(String number, InsertJobBookingVO param) {
        try {

            String beginTime = param.getBeginTime();
            String endTime = param.getEndTime();
            String yearAndMonth = beginTime.substring(0, 7);
            String projectId = param.getProjectId();
            String state = param.getState();
            Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
            Map<String, Object> adminInfo = mapper.getShrAdminInfo(projectId);
            List<Map<String, String>> pList = projectService.getProjectList(number,projectId,yearAndMonth);
            String personId = (String) personInfo.get("personId");
            String type = (String) personInfo.get("btypeFid");
            int workingHour = Integer.parseInt(param.getWorkingHours());
            if(AttendanceType.equals(param.getAttendanceType())) {

                if (!EmployeeType.equals(type)) {
                    if (!LeaveType.equals(type)) {
                        MessageResult result = new MessageResult();
                        result.setCode(403);
                        result.setMsg("只有正式工可以申请年假");
                        return result;
                    }
//                    MessageResult result = new MessageResult();
//                    result.setCode(403);
//                    result.setMsg("只有正式工可以申请年假");
//                    return result;
                }
            }

            String userid = (String) personInfo.get("userid");
            String name = (String) personInfo.get("personName");
            String CFOrgID = (String) adminInfo.get("orgId");
            String managerId = (String) personInfo.get("managerId");
            String managerName = (String) personInfo.get("managerName");
            String managerNumber = (String) personInfo.get("managerNumber");
            String manager = managerName+"-"+managerNumber;
            if((!pList.isEmpty())){
                Map<String,String> pMap = pList.get(0);
                manager = pMap.get("manager");
                managerId=pMap.get("id");
            }
//            if (!this.checkAvailableDate(beginTime)) {
//                return MessageResult.error("已过7号，不能填报上个月！");
//            }
            List<InsertJobBookingEnteyVO> attendanceList = param.getTimes();
            for (InsertJobBookingEnteyVO enteyVO : attendanceList) {
                String attendanceType = enteyVO.getAttendanceType();
                String workingHours = enteyVO.getWorkingHours();
                Integer Hour = Integer.parseInt(workingHours);
                if(AttendanceType.equals(attendanceType)){
                    MessageResult result = this.checkAttWinter(number,beginTime,endTime,Hour);
                    if(result.getCode()!=200){
                        return result;
                    }
                }
                Map<String, String> billMap = new HashMap<>();
                billMap.put("FCreatorID", userid);
                billMap.put("CFAuditorAndNumber", manager);

                billMap.put("FLastUpdateUserID", userid);
                billMap.put("FDescription", "");
                billMap.put("CFPersonID", personId);
                billMap.put("CFOrgID", CFOrgID);

                billMap.put("CFYearAndMonth", yearAndMonth);
                billMap.put("CFAttendanceID", attendanceType);

                billMap.put("CFStatus", state);
                //
                //        Calendar beginCalendar = Calendar.getInstance();
                //        beginCalendar.setTime(beginDate);
                //        Calendar endCalendar = Calendar.getInstance();
                //        endCalendar.setTime(endDate);
                int begin = Integer.parseInt(beginTime.substring(8, 10));
                int end = Integer.parseInt(endTime.substring(8, 10));
                if(begin == end ){
                    billMap.put("CFTitle", begin + "号");
                }else{
                    billMap.put("CFTitle", begin + "-" + end + "号");

                }
                billMap.put("CFBeginDate", beginTime);
                billMap.put("CFEndDate", endTime);
                billMap.put("CFPersonNumber", number);
                billMap.put("CFNameAndNumber", name + "-" + number);
                Map<String, String> sDateMap = new HashMap<>();
                sDateMap.put("startDate", beginTime);
                sDateMap.put("endDate", endTime);
                List<Map<String, String>> dateTypeList = HRWorkmapper.selectWorkCalendar(sDateMap);
                log.info(JSONUtil.toJsonStr(dateTypeList));
                List<Map<String, String>> entryList = new ArrayList<>();
                BigDecimal decimal = BigDecimal.ZERO;

                int j = 0;
                for (int i = begin; i <= end; i++) {
                    j += 1;
                    Map<String, String> entryMap = new HashMap<>();
                    entryMap.put("Fseq", j + "");
                    entryMap.put("FParentID", "");
                    entryMap.put("CFAuditorAndNumber", manager);
                    entryMap.put("CFPersonID", personId);
                    entryMap.put("CFApproverID", managerId);
                    entryMap.put("CFOrgID", CFOrgID);
                    String iday = "01";
                    if (i < 10) {
                        iday = "0" + i;
                    } else {
                        iday = i + "";
                    }
                    String CFReportDate = beginTime.substring(0, 8) + iday;

                    List<Map<String, String>> reportDateWorkHoursByPerson = mapper.getReportDateWorkHoursByPerson(personId, CFReportDate);
                    int hours = Integer.parseInt(workingHours);
                    if(null != reportDateWorkHoursByPerson && reportDateWorkHoursByPerson.size() >0){
                        for(int k = 0; k<reportDateWorkHoursByPerson.size();k++){
                            Map temp_map = reportDateWorkHoursByPerson.get(k);
                            int temp = Integer.parseInt(temp_map.get("CFWorkingHours").toString());
                            hours= hours+temp;
                        }
                    }
                    if(hours>8){
                        return MessageResult.error(CFReportDate+"日报工已超过8小时，请修正！");
                    }

                    entryMap.put("CFReportDate", CFReportDate);
                    entryMap.put("CFYearAndMonth", yearAndMonth);
                    entryMap.put("CFAttendanceID", attendanceType);
                    entryMap.put("CFStatus", state);
                    for (Map<String, String> temp : dateTypeList) {
                        String FDate = temp.get("FDate").substring(0, 10);
                        String dateType = temp.get("dateType");
                        if (CFReportDate.equals(FDate)) {
                            switch (dateType) {
                                case "0":
                                    decimal = decimal.add(new BigDecimal(workingHours));
                                    entryMap.put("CFWorkingHours", workingHours);
                                    entryMap.put("CFCalendarType", "0");
                                    break;
                                case "1":
                                    entryMap.put("CFWorkingHours", "0");
                                    entryMap.put("CFCalendarType", "1");
                                    break;
                                case "2":
                                    //decimal = decimal.add(new BigDecimal(workingHours));
                                    entryMap.put("CFWorkingHours", "0");
                                    entryMap.put("CFCalendarType", "2");
                                    break;
                                default:
                                    break;
                            }
                            break;
                        }
                    }
                    entryMap.put("CFPersonNumber", number);
                    entryMap.put("CFNameAndNumber", name + "-" + number);
                    entryMap.put("CFPersonDeptID", CFOrgID);
                    entryMap.put("CFYsName", (String) adminInfo.get("orgName"));

                    entryList.add(entryMap);
                }

                String billId = mapper.selectKey();
                billMap.put("CFWorkingHours", decimal.toPlainString());
                billMap.put("billId", billId);
                int bill = mapper.insertBill(billMap);

                for (Map<String, String> temp : entryList) {
                    temp.put("FParentID", billId);
                }
                mapper.insertEntry(entryList);
                if("2".equals(state)){
                    List<Map<String, String>> listMap = projectMapper.getProjectListV2(number, "",OrgNumber);
                    for(Map<String, String> stringMap : listMap){
                        String orgid = stringMap.get("orgId");
                        if(CFOrgID.equals(orgid)){
                            sendWX(stringMap.get("wxUserId"),billMap.get("CFTitle"), (String) personInfo.get("personName"));
                            break;
                        }
                    }
                }
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }
    @Transactional
    public synchronized MessageResult insertV2(String number, InsertJobBookingVO param) {
        try {

            String beginTime = param.getBeginTime();
            String endTime = param.getEndTime();
            String yearAndMonth = beginTime.substring(0, 7);
            String projectId = param.getProjectId();
            String state = param.getState();
            Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
            Map<String, Object> adminInfo = mapper.getShrAdminInfo(projectId);
            List<Map<String, String>> pList = projectService.getProjectList(number,projectId,yearAndMonth);
            String personId = (String) personInfo.get("personId");
            String type = (String) personInfo.get("btypeFid");
            int workingHour = Integer.parseInt(param.getWorkingHours());
            if(AttendanceType.equals(param.getAttendanceType())) {

                if (!EmployeeType.equals(type)) {
                    if (!LeaveType.equals(type)) {
                        MessageResult result = new MessageResult();
                        result.setCode(403);
                        result.setMsg("只有正式工可以申请年假");
                        return result;
                    }
//                    MessageResult result = new MessageResult();
//                    result.setCode(403);
//                    result.setMsg("只有正式工可以申请年假");
//                    return result;
                }
            }

            String userid = (String) personInfo.get("userid");
            String name = (String) personInfo.get("personName");
            String CFOrgID = (String) adminInfo.get("orgId");
            String managerId = (String) personInfo.get("managerId");
            String managerName = (String) personInfo.get("managerName");
            String managerNumber = (String) personInfo.get("managerNumber");
            String manager = managerName+"-"+managerNumber;
            if((!pList.isEmpty())){
                Map<String,String> pMap = pList.get(0);
                manager = pMap.get("manager");
                managerId=pMap.get("id");
            }
            if (!this.checkAvailableDate(beginTime)) {
                return MessageResult.error("已过7号，不能填报上个月！");
            }
            List<InsertJobBookingEnteyVO> attendanceList = param.getTimes();
            for (InsertJobBookingEnteyVO enteyVO : attendanceList) {
                String attendanceType = enteyVO.getAttendanceType();
                String workingHours = enteyVO.getWorkingHours();
                Integer Hour = Integer.parseInt(workingHours);
                if(AttendanceType.equals(attendanceType)){
                    MessageResult result = this.checkAttWinter(number,beginTime,endTime,Hour);
                    if(result.getCode()!=200){
                        return result;
                    }
                }
                Map<String, String> billMap = new HashMap<>();
                billMap.put("FCreatorID", userid);
                billMap.put("CFAuditorAndNumber", manager);

                billMap.put("FLastUpdateUserID", userid);
                billMap.put("FDescription", "");
                billMap.put("CFPersonID", personId);
                billMap.put("CFOrgID", CFOrgID);

                billMap.put("CFYearAndMonth", yearAndMonth);
                billMap.put("CFAttendanceID", attendanceType);

                billMap.put("CFStatus", state);
                //
                //        Calendar beginCalendar = Calendar.getInstance();
                //        beginCalendar.setTime(beginDate);
                //        Calendar endCalendar = Calendar.getInstance();
                //        endCalendar.setTime(endDate);
                int begin = Integer.parseInt(beginTime.substring(8, 10));
                int end = Integer.parseInt(endTime.substring(8, 10));
                if(begin == end ){
                    billMap.put("CFTitle", begin + "号");
                }else{
                    billMap.put("CFTitle", begin + "-" + end + "号");

                }
                billMap.put("CFBeginDate", beginTime);
                billMap.put("CFEndDate", endTime);
                billMap.put("CFPersonNumber", number);
                billMap.put("CFNameAndNumber", name + "-" + number);
                Map<String, String> sDateMap = new HashMap<>();
                sDateMap.put("startDate", beginTime);
                sDateMap.put("endDate", endTime);
                List<Map<String, String>> dateTypeList = HRWorkmapper.selectWorkCalendar(sDateMap);
                log.info(JSONUtil.toJsonStr(dateTypeList));
                List<Map<String, String>> entryList = new ArrayList<>();
                BigDecimal decimal = BigDecimal.ZERO;

                int j = 0;
                for (int i = begin; i <= end; i++) {
                    j += 1;
                    Map<String, String> entryMap = new HashMap<>();
                    entryMap.put("Fseq", j + "");
                    entryMap.put("FParentID", "");
                    entryMap.put("CFAuditorAndNumber", manager);
                    entryMap.put("CFPersonID", personId);
                    entryMap.put("CFApproverID", managerId);
                    entryMap.put("CFOrgID", CFOrgID);
                    String iday = "01";
                    if (i < 10) {
                        iday = "0" + i;
                    } else {
                        iday = i + "";
                    }
                    String CFReportDate = beginTime.substring(0, 8) + iday;

                    List<Map<String, String>> reportDateWorkHoursByPerson = mapper.getReportDateWorkHoursByPerson(personId, CFReportDate);
                    int hours = Integer.parseInt(workingHours);
                    if(null != reportDateWorkHoursByPerson && reportDateWorkHoursByPerson.size() >0){
                        for(int k = 0; k<reportDateWorkHoursByPerson.size();k++){
                            Map temp_map = reportDateWorkHoursByPerson.get(k);
                            int temp = Integer.parseInt(temp_map.get("CFWorkingHours").toString());
                            hours= hours+temp;
                        }
                    }
                    if(hours>8){
                        return MessageResult.error(CFReportDate+"日报工已超过8小时，请修正！");
                    }

                    entryMap.put("CFReportDate", CFReportDate);
                    entryMap.put("CFYearAndMonth", yearAndMonth);
                    entryMap.put("CFAttendanceID", attendanceType);
                    entryMap.put("CFStatus", state);
                    for (Map<String, String> temp : dateTypeList) {
                        String FDate = temp.get("FDate").substring(0, 10);
                        String dateType = temp.get("dateType");
                        if (CFReportDate.equals(FDate)) {
                            switch (dateType) {
                                case "0":
                                    decimal = decimal.add(new BigDecimal(workingHours));
                                    entryMap.put("CFWorkingHours", workingHours);
                                    entryMap.put("CFCalendarType", "0");
                                    break;
                                case "1":
                                    entryMap.put("CFWorkingHours", "0");
                                    entryMap.put("CFCalendarType", "1");
                                    break;
                                case "2":
                                    //decimal = decimal.add(new BigDecimal(workingHours));
                                    entryMap.put("CFWorkingHours", "0");
                                    entryMap.put("CFCalendarType", "2");
                                    break;
                                default:
                                    break;
                            }
                            break;
                        }
                    }
                    entryMap.put("CFPersonNumber", number);
                    entryMap.put("CFNameAndNumber", name + "-" + number);
                    entryMap.put("CFPersonDeptID", CFOrgID);
                    entryMap.put("CFYsName", (String) adminInfo.get("orgName"));

                    entryList.add(entryMap);
                }

                String billId = mapper.selectKey();
                billMap.put("CFWorkingHours", decimal.toPlainString());
                billMap.put("billId", billId);
                int bill = mapper.insertBill(billMap);

                for (Map<String, String> temp : entryList) {
                    temp.put("FParentID", billId);
                }
                mapper.insertEntry(entryList);
                if("2".equals(state)){
                    List<Map<String, String>> listMap = projectMapper.getProjectListV2(number, "",OrgNumber);
                    for(Map<String, String> stringMap : listMap){
                        String orgid = stringMap.get("orgId");
                        if(CFOrgID.equals(orgid)){
                            sendWX(stringMap.get("wxUserId"),billMap.get("CFTitle"), (String) personInfo.get("personName"));
                            break;
                        }
                    }
                }
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }
    private void sendWX(String wxUserId,String CFTitle, String personName) throws Exception {

        Map<String, Object> wwMap = Maps.newHashMap();
        Map<String, Object> valMap = Maps.newHashMap();
        wwMap.put("agentid",wXService.getKs_AgentId());
        wwMap.put("msgtype","textcard");
        wwMap.put("touser", wxUserId);
        wwMap.put("textcard",valMap);
        valMap.put("title", "报工审批提醒");
        StringBuilder content = new StringBuilder();
        content.append("员工"+CFTitle+personName+"报工");
        valMap.put("description", content);
        valMap.put("url", WXUrl);
        valMap.put("btntxt", "详情");
        wXService.sendKSMessage(wwMap);
    }
    public List<Map<String, Object>> getPPWorkDetail(Map<String, Object> map) {
        String number = (String) map.get("number");
        String beginTime = (String) map.get("beginTime");
        String endTime = (String) map.get("endTime");
        String projectId = (String) map.get("projectId");
        Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
        String personId = (String) personInfo.get("personId");
        List<Map<String, Object>> list = mapper.getPPWorkDetail(beginTime, endTime, personId, projectId);
        return list;
    }

    public MessageResult getAuditedOld(String number, String month,  String audited, Integer page, Integer size) {
        try {
            size=5;
            List<Map<String, Object>> listMap = this.getCacheProjectListToChildV2(number,OrgNumber);

            Map<String, List<String>> mapList = new HashMap<>();

            for (Map<String, Object> map : listMap) {
                String orgId= (String) map.get("orgId");
                List<String> list = mapList.get(orgId);
                if(null==list){
                    list = new ArrayList<>();
                    mapList.put(orgId,list);
                }
                list.add((String) map.get("pid"));
            }
            int total=0;
            int records = mapList.size();
            if (records % size == 0) {
                total = records / size;
            } else {
                total = (records / size) + 1;
            }
            int fromIndex = 0; // 开始索引
            int toIndex = 0; // 结束索引
            if (page != total) {
                fromIndex = (page - 1) * size;
                toIndex = (fromIndex + size) > records ? records : (fromIndex + size);
            } else {
                fromIndex = (page - 1) * size;
                toIndex = records;
            }
            List<String> list = new ArrayList<>();
            List<List<String>> lists = new ArrayList<>();
            lists.addAll(mapList.values());
            List<List<String>> listSub = lists.subList(fromIndex,toIndex);
            for(List<String> temp: listSub){
                list.addAll(temp);
            }
            log.info("getAudited1:"+list);
            if(list.size()>0){
                //PageHelper.startPage(page, size);
                List<Map<String, Object>> auditedList = mapper.getAudited(list, audited,month);
                log.info("getAudited2:"+auditedList);
                for(Map<String, Object> map :auditedList){
                    map.put("month",map.get("yearAndMonth"));
                }
                //PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(auditedList);
                MessageResult messageResult = MessageResult.success();
                messageResult.add("list", auditedList);
                messageResult.add("page", page);
                messageResult.add("size", size);
                messageResult.add("total", records);
                return messageResult;
            }else {
                MessageResult messageResult = MessageResult.success();
                messageResult.add("list", new ArrayList<>());
                messageResult.add("page", 1);
                messageResult.add("size", 20);
                messageResult.add("total", 0);
                return messageResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }


    public List<String> getCacheProjectListToChildV2ByPid(String number,String OrgNumber){
        String key = "getCacheProjectListToChildV2ByPid_"+number+"_"+OrgNumber;
        List<String> list = (List<String>) HutoolCacheUtils.get(key);
        if(null==list){
            list = projectMapper.getProjectListToChildV2ByPid(number,null,OrgNumber);
            HutoolCacheUtils.put(key,list);
        }
        return list;
    }
    public MessageResult getAudited(String number, String month,  String audited, Integer page, Integer size) {
        try {
            size=5;
            List<String> list = this.getCacheProjectListToChildV2ByPid(number,OrgNumber);
            if(list.size()>0){
                List<Map<String, String>> jobBookList= mapper.getOrgAndJobBookId(list,audited,month);
                Map<String, List<String>> mapList = new HashMap<>();
                for (Map<String, String> map : jobBookList) {
                    String orgId= map.get("orgId");
                    List<String> orgList = mapList.get(orgId);
                    if(null==orgList){
                        orgList = new ArrayList<>();
                        mapList.put(orgId,orgList);
                    }
                    orgList.add(map.get("jbkId"));
                }
                int total=0;
                int records = mapList.size();
                if (records % size == 0) {
                    total = records / size;
                } else {
                    total = (records / size) + 1;
                }
                int fromIndex = 0; // 开始索引
                int toIndex = 0; // 结束索引
                if (page != total) {
                    fromIndex = (page - 1) * size;
                    toIndex = (fromIndex + size) > records ? records : (fromIndex + size);
                } else {
                    fromIndex = (page - 1) * size;
                    toIndex = records;
                }
                List<String> listIndex = new ArrayList<>();

                List<List<String>> lists = new ArrayList<>();
                lists.addAll(mapList.values());
                List<List<String>> listSub = lists.subList(fromIndex,toIndex);
                for(List<String> temp: listSub){
                    listIndex.addAll(temp);
                }
                if(listIndex.size()>0){

                    List<Map<String, Object> > auditedList = mapper.getAuditedV9(listIndex,list, audited);
                    for(Map<String, Object> map :auditedList){
                        map.put("month",map.get("yearAndMonth"));
                    }
                    MessageResult messageResult = MessageResult.success();
                    messageResult.add("list", auditedList);
                    messageResult.add("page", page);
                    messageResult.add("size", size);
                    messageResult.add("total", lists.size());
                    return messageResult;
                }else{
                    MessageResult messageResult = MessageResult.success();
                    messageResult.add("list", new ArrayList<>());
                    messageResult.add("page", 1);
                    messageResult.add("size", 20);
                    messageResult.add("total", 0);
                    return messageResult;
                }
            }else {
                MessageResult messageResult = MessageResult.success();
                messageResult.add("list", new ArrayList<>());
                messageResult.add("page", 1);
                messageResult.add("size", 20);
                messageResult.add("total", 0);
                return messageResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }
//    public MessageResult getAudited(String number, String month,  String audited, Integer page, Integer size) {
//        try {
//            size=5;
//            List<Map<String, Object>> listMap = this.getCacheProjectListToChildV2(number,OrgNumber)
//            List<String> list = new ArrayList<>();
//            for (Map<String, Object> map : listMap) {
//                list.add((String) map.get("pid"));
//            }
//            if(list.size()>0){
//                PageHelper.startPage(page, size);
//                Page<Map<String, Object>> auditedList = mapper.getAudited(list, audited,month);
//                for(Map<String, Object> map :auditedList){
//                    map.put("month",map.get("yearAndMonth"));
//                }
//                MessageResult messageResult = MessageResult.success();
//                messageResult.add("list", auditedList);
//                messageResult.add("page", page);
//                messageResult.add("size", size);
//                messageResult.add("total", auditedList.getTotal());
//                return messageResult;
//            }else {
//                MessageResult messageResult = MessageResult.success();
//                messageResult.add("list", new ArrayList<>());
//                messageResult.add("page", 1);
//                messageResult.add("size", 20);
//                messageResult.add("total", 0);
//                return messageResult;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return MessageResult.error(e.getMessage());
//        }
//    }
    public MessageResult getAudited(String number, String audited, Integer page, Integer size) {
        try {
            size=5;
            List<Map<String, Object>> listMap = this.getCacheProjectListToChildV2(number,OrgNumber);
            List<String> list = new ArrayList<>();
            for (Map<String, Object> map : listMap) {
                list.add((String) map.get("pid"));
            }
            System.out.println("getAudited:"+list);
            if(list.size()>0){
                PageHelper.startPage(page, size);
                Page<Map<String, Object>> auditedList = mapper.getAudited(new ArrayList<>(list), audited,null);
                System.out.println("getAudited:"+auditedList);
                for(Map<String, Object> map :auditedList){
                    map.put("month",map.get("yearAndMonth"));
                }
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(auditedList);
                MessageResult messageResult = MessageResult.success();
                messageResult.add("list", auditedList);
                messageResult.add("page", page);
                messageResult.add("size", size);
                messageResult.add("total", pageInfo.getTotal());
                return messageResult;
            }else {
                MessageResult messageResult = MessageResult.success();
                messageResult.add("list", new ArrayList<>());
                messageResult.add("page", page);
                messageResult.add("size", size);
                messageResult.add("total", 0);
                return messageResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }
    public List<Map<String, Object>> getCacheProjectListToChildV2(String number,String OrgNumber){
        String key = "ProjectListToChildV2_"+number+"_"+OrgNumber;
        List<Map<String, Object>> list = (List<Map<String, Object>>) HutoolCacheUtils.get(key);
        if(null==list){
            list = projectMapper.getProjectListToChildV2(number,null,OrgNumber);
            HutoolCacheUtils.put(key,list);
        }
        return list;
    }
    public MessageResult getEmpAudited(String number,String empNumber, String audited, String month, Integer page, Integer size) {
        try {

            if(StringUtils.isNotBlank(empNumber)) {
                List<Map<String, Object>> listMap = this.getCacheProjectListToChildV2(number,OrgNumber);
                List<String> list = new ArrayList<>();
                String personId="";
                for (Map<String, Object> map : listMap) {
                    String pNumber = (String) map.get("pNumber");

                    if (pNumber.equals(empNumber)) {
                        personId = (String) map.get("pid");
                    }
                }
                System.out.println("getEmpAudited:"+personId);
                if(StringUtils.isNotBlank(personId)){
                    PageHelper.startPage(page, size);
                    Page<JobBooking> auditedList = mapper.getEmpAuditedV2(personId, audited,month);
                    for(JobBooking job : auditedList){
                        String id =job.getTimeSheetId();
                        List<Map<String, Object>> list2 = mapper.getHourTotalAll(id);
                        StringBuilder hourTotal = new StringBuilder();
                        for (Map<String, Object> map2 : list2) {
                            String hour = (String) map2.get("hourTotal");
                            hourTotal.append("," + hour);
                        }
                        hourTotal.delete(0, 1);
                        job.setWorkingHours(hourTotal.toString());
                        job.setHourTotal(hourTotal.toString());
                    }

                    PageInfo<JobBooking> pageInfo = new PageInfo<>(auditedList);
                    MessageResult messageResult = MessageResult.success();
                    messageResult.add("list", auditedList);
                    messageResult.add("page", pageInfo.getPageNum());
                    messageResult.add("size", pageInfo.getPageSize());
                    messageResult.add("total", pageInfo.getTotal());
                    return messageResult;
                }else {
                    MessageResult messageResult = MessageResult.success();
                    messageResult.add("list", new ArrayList<>());
                    messageResult.add("page", 1);
                    messageResult.add("size", 20);
                    messageResult.add("total", 0);
                    return messageResult;
                }
            }else {
                return this.getAudited(number,month,audited,page,size);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }

    public MessageResultV2 getEmpList(String number, String audited, String month, Integer page, Integer size) {
        try {
            List<Map<String, Object>> listMap = this.getCacheProjectListToChildV2(number,OrgNumber);
            List<String> list = new ArrayList<>();
            String personId="";
            for (Map<String, Object> map : listMap) {
                list.add((String) map.get("pid"));
            }
            System.out.println("getEmpList:"+list);
            if(list.size()>0){
//                PageHelper.startPage(page, size);
                List<Map<String, Object>> auditedList = mapper.getEmpList(list, audited,month);

//                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(auditedList);
                MessageResultV2 messageResult = MessageResultV2.success();
                messageResult.setData(auditedList);
                return messageResult;
            }else {
                MessageResultV2 messageResult = MessageResultV2.success();
                messageResult.setData( new ArrayList<>());
                return messageResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResultV2.error(e.getMessage());
        }
    }

    public MessageResult getWorkSheetById(String number, String id) {
        try {
            Map<String, Object> map = mapper.getWorkSheetById(id);
            List<Map<String, Object>> list2 = this.getCacheHourTotal(id);
            StringBuilder hourTotal = new StringBuilder();

            for (Map<String, Object> map2 : list2) {
                String hour = (String) map2.get("hourTotal");
                hourTotal.append("," + hour);
            }
            hourTotal.delete(0, 1);
            map.put("hourTotal", hourTotal.toString());
            List<Map<String, String>> listEntry = mapper.getMonthWorkSheetEntry(id);
            for(Map<String, String>  mapl : listEntry){
               String cfCalendarType =  mapl.get("workCalendarType");
               if("0".equals(cfCalendarType)){
                   map.put("workingHours",  mapl.get("workingHours"));
                   break;
               }
            }
            map.put("details", listEntry);
            MessageResult messageResult = MessageResult.success();
            messageResult.setData(map);
            return messageResult;
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }

    }

    public List<Map<String, Object>> getMonthWorkSheet(String number, String month, String state) {

        try {
            List<Map<String, Object>> list = mapper.getMonthWorkSheet(number, month, state);
            for (Map<String, Object> map : list) {
                String id = (String) map.get("timeSheetId");
                List<Map<String, Object>> list2 =  this.getCacheHourTotal(id);
                StringBuilder hourTotal = new StringBuilder();

                for (Map<String, Object> map2 : list2) {
                    String hour = (String) map2.get("hourTotal");
                    hourTotal.append("," + hour);
                }
                hourTotal.delete(0, 1);
                map.put("hourTotal", hourTotal.toString());
                map.put("month", month);
                List<Map<String, String>> listEntry = mapper.getMonthWorkSheetEntry(id);
                for(Map<String, String>  mapl : listEntry){
                    String cfCalendarType =  mapl.get("workCalendarType");
                    if("0".equals(cfCalendarType)){
                        map.put("workingHours",  mapl.get("workingHours"));
                    }else{
                        mapl.put("workingHours","8");
                    }

                }
                map.put("details", listEntry);
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * "rejectNum": 1,
     * "noProjectNum": 1,
     * "checkingNum": 3,
     * "passNum": 4
     *
     * @param number
     * @param month
     */
    public Map<String, Object> getPersonWorkDetail(String number, String month) {
        String[] monthArr = month.split("-");
        int year = Integer.parseInt(monthArr[0]);
        Month month1 = Month.of(Integer.parseInt(monthArr[1]));
        LocalDate beginDate = LocalDate.of(year, month1, 1);
        LocalDate endDate = LocalDate.of(Integer.parseInt(monthArr[0]), month1, month1.length(beginDate.isLeapYear()));
        Map<String, Object> personInfo = this.getCacheShrPersonInfo(number);
        String personId = (String) personInfo.get("personId");
        List<Map<String, Object>> list = mapper.getPersonWorkDetail(
                beginDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
                endDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
                personId
        );
        Map<String, Object> result = new HashMap<>();
        result.put("noProjectNum", 0);
        result.put("checkingNum", 0);
        result.put("passNum", 0);
        result.put("rejectNum", 0);
        for (Map<String, Object> map : list) {
            int num = (int) map.get("num");
            String CFStatus = (String) map.get("CFStatus");
            switch (CFStatus) {
                case "1":
                    result.put("noProjectNum", num);
                    break;
                case "2":
                    result.put("checkingNum", num);
                    break;
                case "3":
                    result.put("passNum", num);
                    break;
                case "4":
                    result.put("rejectNum", num);
                    break;
                default:
                    if (null != result.get("noProjectNum")) {
                        result.put("noProjectNum", ((int) result.get("noProjectNum") + num));
                    } else {
                        result.put("noProjectNum", num);
                    }
                    break;
            }
        }
        return result;
    }

    /**
     * for(Map<String,String> map : list){
     * String id = map.get("timeSheetId");
     * List<Map<String,String>> list2 = mapper.getHourTotal(id,null);
     * StringBuilder hourTotal = new StringBuilder();
     * for(Map<String,String> map2  : list2){
     * hourTotal.append(","+map2.get("hourTotal"));
     * }
     * hourTotal.delete(0,1);
     * map.put("hourTotal",hourTotal.toString());
     * }
     *
     * @param number
     * @param projectId
     * @param month
     * @return
     */
    public Poject getTimeSheetDetail(String number, String projectId, String month,String state) {

        try {
            Map<String,Object> person = this.getCacheShrPersonInfo(number);
            String personid= (String) person.get("personId");
            Poject poject = mapper.getTimeJobBooking(projectId,personid);
            LocalDate monthDate = LocalDate.parse(month + "-01", DateTimeFormatter.ISO_LOCAL_DATE);
            int day = monthDate.getMonth().length(monthDate.isLeapYear());
            poject.setMonth(month);
            StringBuilder pojectHourTotal = new StringBuilder();

            int dayTotal0 = 0;
            int dayTotal1 = 0;
            int dayTotal2 = 0;
            List<JobBook> deleteList = new ArrayList<>();
            List<JobBook> detail=  poject.getDetail();
            List<String> idList=  new ArrayList<>();
            for (int i=0;i<detail.size();i++) {
                JobBook jobBook = detail.get(i);
                Double monthRate = 0D;
                List<JobBooking> timeSheetDetail = mapper.getTimeJobBookingEntry(jobBook.getpId(), month,state,poject.getProjectId());
                if(null==timeSheetDetail||timeSheetDetail.isEmpty()){
                    deleteList.add(jobBook);
                }
                int size = 0;
                for (JobBooking jobBooking : timeSheetDetail) {

                    String id = jobBooking.getTimeSheetId();
                    idList.add(id);
                    StringBuilder jobBookingHourTotal = new StringBuilder();
                    List<Map<String, Object>> list2 =  this.getCacheHourTotal(id);
                    for (Map<String, Object> map2 : list2) {
                        jobBookingHourTotal.append("," + map2.get("hourTotal"));
                    }
                    jobBookingHourTotal.delete(0, 1);
                    jobBooking.setHourTotal(jobBookingHourTotal.toString());
                    size += jobBooking.getDetails().size();
                    // hourTotal = hourTotal.add(new BigDecimal(jobBooking.getHourTotal()));
                }
                monthRate = ((double)size / (double)(day)) * 100D;
                jobBook.setMonthRate(String.format("%.2f",monthRate)+ "%");
                jobBook.setTimeSheetDetail(timeSheetDetail);

            }

            for(JobBook i : deleteList){
                detail.remove(i);
            }
            if(!idList.isEmpty()) {
                List<Map<String, Object>> list2 = mapper.getHourTotalSumV2(idList, null);
                for (Map<String, Object> map2 : list2) {
                    String calendarType = (String) map2.get("calendarType");
                    int num = (int) map2.get("num");
                    switch (calendarType) {
                        case "0":
                            dayTotal0 += num;
                            break;
                        case "1":
                            dayTotal1 += num;
                            break;
                        case "2":
                            dayTotal2 += num;
                            break;
                        default:
                            break;
                    }
                }
            }
            pojectHourTotal.append(poject.getDetail().size() + "人、");

            pojectHourTotal.append(dayTotal0 + "人天(工作日)、");
            //pojectHourTotal.append(dayTotal1 + "人天(休息日)、");
            pojectHourTotal.append(dayTotal2 + "人天(节假日)");
            poject.setHourTotal(pojectHourTotal.toString());
            return poject;
        } catch (Exception e) {
            e.printStackTrace();
            //log.error("====detailId==="+cancelOnDateVO.getDetailId()+"==========timeSheetId======"+cancelOnDateVO.getTimeSheetId());
            //Arrays.stream(e.getStackTrace()).forEach(System.out::println);
        }
        return null;
    }

    /**
     * 获取主管信息
     * @param number
     * @return
     */
    public Map<String,Object> getCacheShrPersonInfo(String number){
        String key ="getCacheShrPersonInfo_"+number;
        Map<String,Object> person = (Map<String, Object>) HutoolCacheUtils.get(key);
        if(null==person){
            person =  mapper.getShrPersonInfo(number);
            HutoolCacheUtils.put(key,person);
        }
        return person;
    }

    /**
     * 获取项目信息
     * @param projectId
     * @param personid
     * @return
     */
    public Poject getCacheTimeJobBooking(String projectId, String personid){
        String key = "getCacheTimeJobBooking_"+projectId+"_"+personid;
        Poject poject = (Poject) HutoolCacheUtils.get(key);
        if(null==poject){
            poject =  mapper.getTimeJobBooking(projectId,personid);
            HutoolCacheUtils.put(key,poject);
        }
        return poject;
    }

    /**
     * 获取项目分录信息
     * @param personid
     * @param month
     * @param state
     * @param projectId
     * @return
     */
    public List<JobBooking> getCacheTimeJobBookingEntry(String personid,String month,String state,String projectId){
        String key = "getCacheTimeJobBookingEntry_"+projectId+"_"+personid+"_"+month+"_"+state;
        List<JobBooking> timeSheetDetail = (List<JobBooking>) HutoolCacheUtils.get(key);
        if(null==timeSheetDetail){
            timeSheetDetail =  mapper.getTimeJobBookingEntry(personid,month,state,projectId);
            HutoolCacheUtils.put(key,timeSheetDetail);
        }
        return timeSheetDetail;
    }
    /**
     * 获取项目分录小时数
     * @param id

     * @return
     */
    public  List<Map<String, Object>> getCacheHourTotal(String id){
        String key = id;
        List<Map<String, Object>> detail = (List<Map<String, Object>>) HutoolCacheUtils.get(key);
        if(null==detail){
            detail =  mapper.getHourTotal(id,null);
            HutoolCacheUtils.put(key,detail);
        }
        return detail;
    }

    /**
     * for(Map<String,String> map : list){
     * String id = map.get("timeSheetId");
     * List<Map<String,String>> list2 = mapper.getHourTotal(id,null);
     * StringBuilder hourTotal = new StringBuilder();
     * for(Map<String,String> map2  : list2){
     * hourTotal.append(","+map2.get("hourTotal"));
     * }
     * hourTotal.delete(0,1);
     * map.put("hourTotal",hourTotal.toString());
     * }
     *
     * @param number
     * @param projectId
     * @param month
     * @return
     */
    public Poject getTimeSheetDetailV2(String number, String projectId, String month,String state) {

        try {
            Map<String,Object> person = this.getCacheShrPersonInfo(number);
            String personid= (String) person.get("personId");
            Poject poject = this.getCacheTimeJobBooking(projectId,personid);
            LocalDate monthDate = LocalDate.parse(month + "-01", DateTimeFormatter.ISO_LOCAL_DATE);
            int day = monthDate.getMonth().length(monthDate.isLeapYear());
            poject.setMonth(month);
            StringBuilder pojectHourTotal = new StringBuilder();

            int dayTotal0 = 0;
            int dayTotal1 = 0;
            int dayTotal2 = 0;
            List<JobBook> deleteList = new ArrayList<>();
            List<JobBook> detail=  poject.getDetail();
            List<String> idList=  new ArrayList<>();
            for (int i=0;i<detail.size();i++) {
                JobBook jobBook = detail.get(i);
                Double monthRate = 0D;
                List<JobBooking> timeSheetDetail = this.getCacheTimeJobBookingEntry(jobBook.getpId(), month,state,poject.getProjectId());
                if(null==timeSheetDetail||timeSheetDetail.isEmpty()){
                    deleteList.add(jobBook);
                }
                int size = 0;
                for (JobBooking jobBooking : timeSheetDetail) {

                    String id = jobBooking.getTimeSheetId();
                    idList.add(id);
                    StringBuilder jobBookingHourTotal = new StringBuilder();
                    List<Map<String, Object>> list2 = this.getCacheHourTotal(id);
                    for (Map<String, Object> map2 : list2) {
                        jobBookingHourTotal.append("," + map2.get("hourTotal"));
                    }
                    jobBookingHourTotal.delete(0, 1);
                    jobBooking.setHourTotal(jobBookingHourTotal.toString());
                    size += jobBooking.getDetails().size();
                    // hourTotal = hourTotal.add(new BigDecimal(jobBooking.getHourTotal()));
                }
                monthRate = ((double)size / (double)(day)) * 100D;
                jobBook.setMonthRate(String.format("%.2f",monthRate)+ "%");
                jobBook.setTimeSheetDetail(timeSheetDetail);
            }
            for(JobBook i : deleteList){
                detail.remove(i);
            }
            if(!idList.isEmpty()) {
                List<Map<String, Object>> list2 = mapper.getHourTotalSumV2(idList, null);
                for (Map<String, Object> map2 : list2) {
                    String calendarType = (String) map2.get("calendarType");
                    int num = (int) map2.get("num");
                    switch (calendarType) {
                        case "0":
                            dayTotal0 += num;
                            break;
                        case "1":
                            dayTotal1 += num;
                            break;
                        case "2":
                            dayTotal2 += num;
                            break;
                        default:
                            break;
                    }
                }
            }
            pojectHourTotal.append(poject.getDetail().size() + "人、");

            pojectHourTotal.append(dayTotal0 + "人天(工作日)、");
            //pojectHourTotal.append(dayTotal1 + "人天(休息日)、");
            pojectHourTotal.append(dayTotal2 + "人天(节假日)");
            poject.setHourTotal(pojectHourTotal.toString());
            return poject;
        } catch (Exception e) {
            e.printStackTrace();
            //log.error("====detailId==="+cancelOnDateVO.getDetailId()+"==========timeSheetId======"+cancelOnDateVO.getTimeSheetId());
            //Arrays.stream(e.getStackTrace()).forEach(System.out::println);
        }
        return null;
    }
    public MessageResult approvalProject(String number, AppProJect appProJect) {
        try {
            if (StrUtil.isNotEmpty(appProJect.getTimeSheetIds())) {
                String[] timeSheetIds = appProJect.getTimeSheetIds().split(",");
                for (String id : timeSheetIds) {
                    Map map = workSheetMapper.getJobBookingById(id);

                    if (ObjectUtil.isNull(map.get("FID"))) {
                        return MessageResult.error("未找到报工明细数据！");
                    } else {
                        Date beginDate =  (Date)map.get("CFBeginDate");
                        String attendanceType =  (String)map.get("CFAttendanceID");;

                        Instant instant = beginDate.toInstant();
                        ZoneId zoneId = ZoneId.systemDefault();
                        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
                        LocalDate beginTime = instant.atZone(zoneId).toLocalDate();
                        if (!this.checkAvailableDate(beginTime)) {
                            return MessageResult.error("已过7号，不能(通过,驳回)上个月的报工！");
                        }
//                        if(AttendanceType.equals(attendanceType)){
//                            String workingHours = (String)map.get("CFWorkingHours");
//                            String begin = beginTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
//                            Date endDate = (Date)map.get("CFEndDate");
//                            Instant instantEnd = endDate.toInstant();
//                            ZoneId zoneIdEnd = ZoneId.systemDefault();
//                            // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
//                            LocalDate endTime = instantEnd.atZone(zoneIdEnd).toLocalDate();
//                            String end = endTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
//                            MessageResult result = this.checkAttWinter(number,begin,end,Integer.parseInt(workingHours));
//                            if(result.getCode()!=200){
//                                return result;
//                            }
//                        }

                        //if ("2".equals(map.get("CFStatus").toString())) {
                           Map<String,Object> person = this.getCacheShrPersonInfo(number);
                            String auditorAndNumber = person.get("personName")+"-"+person.get("personNumber");
                            workSheetMapper.updateStatusAndAuditorById(appProJect.getStatus(), id, auditorAndNumber);
                            workSheetMapper.updateEntryAudiByParentId(appProJect.getStatus(), id, auditorAndNumber);
                       // } else {
                        //    return MessageResult.error("只能(通过,驳回)待审核的数据！");
                        //}
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
        return MessageResult.success();
    }

    public MessageResult deleteSheet(String number, String id) {
        try {
            if (StrUtil.isNotEmpty(id)) {
                Map map = workSheetMapper.getJobBookingById(id);
                if (null == map || ObjectUtil.isNull(map.get("FID"))) {
                    return MessageResult.error("未找到报工明细数据！");
                } else {
                    if (("1".equals(map.get("CFStatus").toString()))||("4".equals(map.get("CFStatus").toString()))) {
                        mapper.deleteSheet(id);
                    }
                    else {
                        return MessageResult.error("只能删除暂存,驳回的数据！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
        return MessageResult.success();
    }

    public MessageResult getJobDayByPerson(String number,String stratDate,String endDate,String orgid,String type) {
        try {
            if(StringUtils.isBlank(type)){
                type=this.tripType;
            }
            Map<String,Object> result = new HashMap<>();
            result.put("total",0);
            result.put("num",0);
            result.put("workinghours",0);
            result.put("number",number);
            String[] dateArr = stratDate.split("-");
            Month month = Month.of(Integer.parseInt(dateArr[1]));
            LocalDate localDate = LocalDate.of(Integer.parseInt(dateArr[0]),month,1);
            LocalDate stratLocalDate = localDate.plusMonths(-1);
            LocalDate endLocalDate = LocalDate.of(stratLocalDate.getYear(),
                    stratLocalDate.getMonth(),
                    stratLocalDate.getMonth().length(stratLocalDate.isLeapYear()));
            Map<String,Object> map = mapper.getJobDayByPerson(number,orgid,
                    stratLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
                    endLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE),type,null);
            Map<String,Object> map2 = mapper.getJobDayByPerson(number,orgid,stratDate,endDate,null,null);
            List<Map<String, Object>> list = HRWorkmapper.getWorkDay(stratDate, endDate);
            int total = 0;
            for (Map<String, Object> map1 : list) {
                total = total + (int) map1.get("dayLen");
            }
            result.put("total", total);
            MessageResult messageResult = MessageResult.success();
            if(null!=map) {
                result.putAll(map);
            }
            if(null!=map2) {
                //填报天数
                result.put("num",map2.get("num"));
            }
            messageResult.setData(result);
            return messageResult;
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e.getMessage());
        }
    }
}
