package com.bonus.system.leaveReporting.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.common.core.utils.FastJsonHelper;
import com.bonus.common.core.utils.ImportExcelUtils;
import com.bonus.common.core.utils.UploadCheckUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.common.security.utils.ValidatorsUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysRole;
import com.bonus.system.att.entity.Holiday;
import com.bonus.system.basic.domain.SysNotice;
import com.bonus.system.basic.service.SysNoticeService;
import com.bonus.system.holiday.dao.WorkReportDao;
import com.bonus.system.leaveReporting.dao.LeaveReportingDao;
import com.bonus.system.leaveReporting.entity.LeaveReportingBean;
import com.bonus.system.leaveReporting.entity.LeaveReportingImportBean;
import com.bonus.system.leaveReporting.entity.LeaveReportingKeyBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 休假报备-业务层
 *
 * @author lsun
 */
@Service("LeaveReportingService")
@Log4j2
public class LeaveReportingServiceImpl implements LeaveReportingService {

    @Resource(name = "LeaveReportingDao")
    private LeaveReportingDao leaveReportingDao;



    @Override
    public List<LeaveReportingBean> getLeaveReportingList(LeaveReportingBean bean) {
        return leaveReportingDao.getLeaveReportingList(bean);
    }

    @Override
    public int insertLeaveReporting(LeaveReportingBean o) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();

        String cadre = SecurityUtils.getLoginUser().getSysUser().getIsCadre();
        o.setCreateUserId(userId);
        o.setSource("1");
//        o.setIsCadre(cadre);
        int i = leaveReportingDao.insertLeaveReporting(o);
        return i;
    }

    @Override
    public int updateLeaveReporting(LeaveReportingBean o) {
        o.setUpdateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        return leaveReportingDao.updateLeaveReporting(o);
    }

    @Override
    public int deleteLeaveReportingById(Long id) {
        return leaveReportingDao.deleteLeaveReportingById(id);
    }

    @Override
    public LeaveReportingBean selectLeaveReportingById(Long id) {
        return leaveReportingDao.selectLeaveReportingById(id);
    }

    @Override
    public LeaveReportingBean getPostName(Long id) {
        return leaveReportingDao.getPostName(id);
    }

    @Override
    public AjaxResult getUserList(Long id) {
        try {
            LeaveReportingBean bean = new LeaveReportingBean();
            //只能查自己部门的人
            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);
            }
            bean.setId(id);
            List<LeaveReportingBean> list = leaveReportingDao.getUserList(bean);
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    @Override
    public LeaveReportingBean getDays(LeaveReportingBean bean) {
        try {
            //只能查自己部门的人
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            //1 公司机关 2 项目部
            String attType= leaveReportingDao.getAttTypeByUserId(userId);
            // 查询出所有周末以及节假日的日期
            List<LeaveReportingBean>  holidays = leaveReportingDao.getFestivalAndHoliday(bean);
            if("2".equals(attType)){
                holidays.clear();
            }
            // 将节假日转换为 Set<String>，提高查找效率
            Set<String> holidaySet = new HashSet<>();
            for (LeaveReportingBean holiday : holidays) {
                holidaySet.add(holiday.getDate());
            }
            Date startDate = null;
            startDate = parseDate(String.valueOf(bean.getLeaveStartDate()));
            Date endDate = parseDate(String.valueOf(bean.getLeaveEndDate()));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            int totalDays = 0;
            while (!calendar.getTime().after(endDate)) {
                String currentDate = formatDate(calendar.getTime());
                if (!holidaySet.contains(currentDate)) {
                    totalDays++;
                }
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            bean.setDate(String.valueOf(totalDays));
            return bean;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AjaxResult getUserListCheck(Long id) {
        try {
            LeaveReportingBean bean = new LeaveReportingBean();
            bean.setId(id);
            List<LeaveReportingBean> list = leaveReportingDao.getUserList(bean);
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    // 辅助方法：将字符串解析为Date对象
    private Date parseDate(String dateStr) throws ParseException {
        return DATE_FORMAT.get().parse(dateStr);
    }

    // 辅助方法：将Date对象格式化为字符串
    private String formatDate(Date date) {
        return DATE_FORMAT.get().format(date);
    }

    @Override
    public Integer isCheck(Long id) {
        try {
            LeaveReportingBean leaveReportingBean = leaveReportingDao.selectLeaveReportingById(id);
            List<Integer> list = leaveReportingDao.isCheck(leaveReportingBean);
            if(CollectionUtils.isNotEmpty(list)){
                for (Integer status : list) {
                    if(!Objects.equals(status,0)){
                        return status;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.toString(),e);
        }
        return 0;
    }
}
