package com.bonus.system.att.service;

import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.att.dao.AttDetailByMonthDao;
import com.bonus.system.att.dao.AttExceptionHandleDao;
import com.bonus.system.att.dao.AttGroupDao;
import com.bonus.system.att.entity.*;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.basic.domain.SysOrg;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 轮休临时外出异常数据-业务层
 * @author hongchao
 */
@Service("attExceptionHandle")
@Slf4j
public class AttExceptionHandleServiceImpl implements AttExceptionHandleService{

    @Resource(name = "attExceptionHandleDao")
    private AttExceptionHandleDao attExceptionHandleDao;

    @Resource(name = "attDetailByMonthDao")
    private AttDetailByMonthDao attDetailByMonthDao;

    @Resource
    private SysOrgDao orgDao;

    @Override
    public TableDataInfo selectAttExceptionList(AttExceptionBean data)
    {
        AttExceptionBean attExceptionBean = new AttExceptionBean();
        List<AttExceptionBean> list = new ArrayList<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        try {
            if(!StringUtils.isEmpty(data.getAttCurrentMonth())){
                LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
                LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
                LocalDate nowMonth =date.withDayOfMonth(1);
                data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
                data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                attExceptionBean = attExceptionHandleDao.selectAttExceptionList(data);
                list.add(attExceptionBean);
            }else{
                mapList = attExceptionHandleDao.selectAttExceptionMonth();
                if(mapList.size()!=0){
                    for (int i = 0; i < mapList.size(); i++) {
                        LocalDate date = LocalDate.parse(mapList.get(i).get("month") + "-01");
                        LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
                        LocalDate nowMonth =date.withDayOfMonth(1);
                        data.setAttCurrentMonth(String.valueOf(mapList.get(i).get("month")));
                        data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
                        data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                        attExceptionBean = attExceptionHandleDao.selectAttExceptionList(data);
                        list.add(attExceptionBean);
                    }
                }
            }

        } catch (Exception e) {
            log.error("查询轮休临时外出异常数据", e);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

//    @Override
//    public List<AttExceptionBean> getDetailException(AttExceptionBean data)
//    {
//        List<AttExceptionBean> listPerson = new ArrayList<>();
//        List<AttExceptionBean> list = new ArrayList<>();
//        List<Map<String,Object>> mapList = new ArrayList<>();
//        List<AttDetailByMonthBean> listTemp = new ArrayList<>();
//        List<Map<String,Object>> parentIdList = new ArrayList<>();
//        List<Map<String,Object>> sonsIdList = new ArrayList<>();
//        Map<String,Object> map = new HashMap<>();
//        try {
//            if(!StringUtils.isEmpty(data.getAttCurrentMonth())){
//                LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
//                LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
//                LocalDate nowMonth =date.withDayOfMonth(1);
//                data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
//                data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                if(data.getOrgId()==null){
//                    listTemp  = attDetailByMonthDao.getAllParentId();
//                    for (int i = 0; i < listTemp.size(); i++) {
//                        findSonsIds(listTemp.get(i).getOrgId(),sonsIdList);
//                    }
//                }else {
//                    findSonsIds(data.getOrgId(), sonsIdList);
//                }
//                for (int i = 0; i < sonsIdList.size(); i++) {
//                    map = sonsIdList.get(i);
//                    findParentIds(map,parentIdList);
//                    sonsIdList.get(i).put("orgName",parentIdList.get(i).get("orgName"));
//                }
//                int[] orgIdsTemp = new int[sonsIdList.size()];
//                for (int i = 0; i < sonsIdList.size(); i++){
//                    orgIdsTemp[i] = (int) sonsIdList.get(i).get("id");
//                }
//                data.setOrgIds(orgIdsTemp);
//                list = attExceptionHandleDao.getDetailException(data);
//                for (int i = 0; i < list.size(); i++) {
//                    for (int j = 0; j < sonsIdList.size(); j++) {
//                        if(sonsIdList.get(j).get("id")==list.get(i).getOrgId()){
//                            list.get(i).setOrgName((String) sonsIdList.get(j).get("orgName"));
//                        }
//                    }
//                }
//            }else{
//                mapList = attExceptionHandleDao.selectAttExceptionNoHandleMonth();
//                if(mapList.size()!=0){
//                    String[] monthError = new String[mapList.size()];
//                    for (int i = 0; i < mapList.size(); i++) {
//                        monthError[i] = (String) mapList.get(i).get("month");
//                    }
//                    data.setMonth(monthError);
//                    list = attExceptionHandleDao.getDetailAllException(data);
//                    for (int i = 0; i < list.size(); i++) {
//                        LocalDate date = LocalDate.parse(list.get(i).getAttCurrentMonth());
//
//                        // 格式化日期为 "YYYY-MM"
//                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
//                        String formattedDate = date.format(formatter);
//                        list.get(i).setAttCurrentMonth(formattedDate);
//                    }
//                }
//            }
//
//        } catch (Exception e) {
//            log.error("查询轮休临时外出异常数据详细信息", e);
//        }
//        return list;
//    }

    @Override
    public List<AttExceptionBean> getDetailException(AttExceptionBean data)
    {
        List<AttExceptionBean> listPerson = new ArrayList<>();
        List<AttExceptionBean> list = new ArrayList<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<AttDetailByMonthBean> listTemp = new ArrayList<>();
        List<Map<String,Object>> parentIdList = new ArrayList<>();
        List<Map<String,Object>> sonsIdList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        try {
            if(!StringUtils.isEmpty(data.getAttCurrentMonth())){
                LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
                LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
                LocalDate nowMonth =date.withDayOfMonth(1);
                data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
                data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                list = attExceptionHandleDao.getDetailException(data);

            }else{
                list = attExceptionHandleDao.getDetailException(data);

            }

        } catch (Exception e) {
            log.error("查询轮休临时外出异常数据详细信息", e);
        }
        return list;
    }

    @Override
    public List<AttDetailLeaveBean> getDetailExceptionRest(AttDetailLeaveBean data)
    {
        List<AttDetailLeaveBean> list = new ArrayList<>();
        try {
            LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
            LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
            LocalDate nowMonth =date.withDayOfMonth(1);
            data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
            data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            list = attExceptionHandleDao.getDetailExceptionRest(data);

        } catch (Exception e) {
            log.error("查询轮休异常报表未申请详情", e);
        }
        return list;
    }

    @Override
    public List<AttDetailLeaveBean> getDetailExceptionOut(AttDetailLeaveBean data)
    {
        List<AttDetailLeaveBean> list = new ArrayList<>();
        try {
            LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
            LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
            LocalDate nowMonth =date.withDayOfMonth(1);
            data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
            data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            list = attExceptionHandleDao.getDetailExceptionOut(data);

        } catch (Exception e) {
            log.error("查询临时外出异常报表未申请详情", e);
        }
        return list;
    }

    @Override
    public List<AttDetailLeaveBean> getDetailExceptionAll(AttDetailLeaveBean data)
    {
        List<AttDetailLeaveBean> list = new ArrayList<>();
        try {
//            LocalDate date = LocalDate.parse(data.getAttCurrentMonth() + "-01");
//            LocalDate nextMonth =date.plusMonths(1).withDayOfMonth(1);
//            LocalDate nowMonth =date.withDayOfMonth(1);
//            data.setAttNextMonthFirst(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) ;
//            data.setAttCurrentMonthFirst(nowMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            list = attExceptionHandleDao.getDetailExceptionAll(data);

        } catch (Exception e) {
            log.error("查询轮休和临时外出异常报表未申请详情", e);
        }
        return list;
    }

    /**
     * 审批提醒
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult examineRemind(AttExRemindBean vo) {
        try {
            SysOrg att = orgDao.selectOrgById(vo.getOrgId());
            if(att==null){
                return AjaxResult.error("审批提醒失败");
            }else{
                String orgIds = att.getOrgHeadUserId();
                if(orgIds != null){
                    String[] nameArray = orgIds.split(",");
                    Long[] longArray = new Long[nameArray.length];
                    for (int i = 0; i < nameArray.length; i++) {
                        try {
                            longArray[i] = Long.parseLong(nameArray[i].trim());
                        } catch (NumberFormatException e) {
                            longArray[i] = null; // 处理异常情况
                        }
                    }
                    for (int i = 0; i < longArray.length; i++) {
                        vo.setUserId(longArray[i]);
                        int numTemp = attExceptionHandleDao.examineRemindTemp(vo);
                        if(numTemp!=1){
                            return AjaxResult.error("审批提醒失败");
                        }
                    }
                    vo.setUserUpdate(SecurityUtils.getUserId());
                    if("轮休".equals(vo.getLeaveType())){
                        vo.setType(67L);
                    }else{
                        vo.setType(68L);
                    }
                    int num = attExceptionHandleDao.examineRemind(vo);
                    if (num==1) {
                        return AjaxResult.success();
                    }
                }else{
                    return AjaxResult.error("部门没有负责人，无法提醒");
                }
            }
            return AjaxResult.error("审批提醒失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 从父级补充所属部门名称
     * @param parentMap
     * @param parentIdList
     */
    public  void findParentIds(Map<String,Object> parentMap,List<Map<String,Object>> parentIdList) {
        Map<String, Object> map = attDetailByMonthDao.getDepartmentById(parentMap);
        if (map!=null && map.get("parentId") != null) {
            // 递归查找上级部门
            findParentIds(map,parentIdList);
        }else if(map!=null){
            parentMap.put("orgName",map.get("orgName"));
            parentIdList.add(parentMap);
        }else{
            parentIdList.add(parentMap);
        }
    }

    /**
     * 获取该部门编号下的所有部门编号
     * @param orgId
     * @param sonsIdList
     */
    public  void findSonsIds(int orgId, List<Map<String,Object>> sonsIdList) {
        Map<String, Object> mapFinish = new HashMap<>();
        Map<String, Object> mapTemp = new HashMap<>();
        List<Map<String, Object>> listSon= attDetailByMonthDao.getSonsById(orgId);
        if(listSon.size()!=0){
            for (int i = 0; i < listSon.size(); i++) {
                mapTemp = listSon.get(i);
                if(mapTemp.get("parentId")==null){
                    sonsIdList.add(mapTemp);
                }else{
                    findSonsIds((Integer) mapTemp.get("id"),sonsIdList);
                }
            }
        }else{
            mapFinish = attDetailByMonthDao.getSonsFinish(orgId);
            sonsIdList.add(mapFinish);
        }
    }

}
