package com.zjty.tynotes.attendance.service.impl;

import com.zjty.tynotes.attendance.dao.AttendanceDetailsDao;
import com.zjty.tynotes.attendance.entity.AttendanceDetails;
import com.zjty.tynotes.attendance.entity.vo.UserAttenVo;
import com.zjty.tynotes.attendance.entity.vo.request.AttenRequest;
import com.zjty.tynotes.attendance.service.AttendanceDetailsService;
import com.zjty.tynotes.pas.dao.*;
import com.zjty.tynotes.pas.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author gwj
 * @create 2020/3/24 14:56
 */
@Service
public class AttendanceDetailsServiceImpl implements AttendanceDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(AttendanceDetailsServiceImpl.class);

    @Autowired
    private AttendanceDetailsDao attendanceDetailsDao;
    @Autowired
    private DayDao dayDao;
    @Autowired
    private PasUserDao pasUserDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleAuthorityDao roleAuthorityDao;
    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private DepartmentDao departmentDao;

    @Override
    public UserAttenVo findPersonnel(AttenRequest request) {
        UserAttenVo userAttenVo = new UserAttenVo();
        SimpleDateFormat sdf = null;
        String searchType = request.getSearchType();
        if(("0").equals(searchType)){
            sdf = new SimpleDateFormat("yyyy-MM");
            Calendar calendar = Calendar.getInstance();
            String date = request.getDate();
            try {
                Date parse = sdf.parse(date);
                calendar.setTime(parse);
                calendar.set(Calendar.DAY_OF_MONTH,1);
                Date startTime = calendar.getTime();
                calendar.add(Calendar.MONTH,1);
                calendar.set(Calendar.DAY_OF_MONTH,0);
                Date endTime = calendar.getTime();
                List<Day> days = dayDao.findAllByStatusAndDateBetween("0", startTime, endTime);
                List<AttendanceDetails> attendanceDetailsList = attendanceDetailsDao.findAllByUserIdAndDateBetween(request.getId(), startTime, endTime);
                userAttenVo = new UserAttenVo();
                userAttenVo.setUserId(request.getId());
                Optional<User> optional = pasUserDao.findById(request.getId());
                if(optional.isPresent()){
                    User user = optional.get();
                    userAttenVo.setName(user.getUsername());
                }
                if(attendanceDetailsList!=null){
                    if(days!=null){
                        userAttenVo.setAttendanceDay(days.size());
                    }
                    for (AttendanceDetails attendanceDetails : attendanceDetailsList) {
                        if(attendanceDetails.getOutSideBusinessDay()!=null){
                            userAttenVo.setOutSideBusinessDay(attendanceDetails.getOutSideBusinessDay()+userAttenVo.getOutSideBusinessDay());
                        }
                        if(attendanceDetails.getOutWorkDay()!=null){
                            userAttenVo.setOutWorkDay(userAttenVo.getOutWorkDay()+attendanceDetails.getOutWorkDay());
                        }
                        if(attendanceDetails.getSickLeaveDay()!=null){
                            userAttenVo.setSickLeaveDay(userAttenVo.getSickLeaveDay()+attendanceDetails.getSickLeaveDay());
                        }
                        if(("0").equals(attendanceDetails.getIsLateDay())){
                            userAttenVo.setLateDay(userAttenVo.getLateDay()+1);
                        }
                        if("0".equals(attendanceDetails.getIsLeaveEarlyDay())){
                            userAttenVo.setLeaveEarlyDay(userAttenVo.getLeaveEarlyDay()+1);
                        }
                        if(attendanceDetails.getWorkOverHours()!=null){
                            userAttenVo.setOverWorkHours(userAttenVo.getOverWorkHours()+attendanceDetails.getWorkOverHours());
                        }

                        if(attendanceDetails.getAbsenteeismDay()!=null){
                            userAttenVo.setAbsenteeismDay(attendanceDetails.getAbsenteeismDay()+userAttenVo.getAbsenteeismDay());
                        }
                    }
                    userAttenVo.computerRealAttendanceDay();
                }
                return userAttenVo;
            } catch (ParseException e) {
                logger.error("时间转换格式错误");
            }
        }else{
            sdf = new SimpleDateFormat("yyyy");
            Calendar calendar = Calendar.getInstance();
            String date = request.getDate();
            try {
                Date parse = sdf.parse(date);
                calendar.setTime(parse);
                calendar.set(Calendar.DAY_OF_YEAR,1);
                Date startTime = calendar.getTime();
                calendar.add(Calendar.YEAR,1);
                calendar.set(Calendar.DAY_OF_YEAR,0);
                Date endTime = calendar.getTime();
                List<Day> days = dayDao.findAllByStatusAndDateBetween("0", startTime, endTime);
                List<AttendanceDetails> attendanceDetailsList = attendanceDetailsDao.findAllByUserIdAndDateBetween(request.getId(), startTime, endTime);
                userAttenVo = new UserAttenVo();
                userAttenVo.setUserId(request.getId());
                Optional<User> optional = pasUserDao.findById(request.getId());
                if(optional.isPresent()){
                    User user = optional.get();
                    userAttenVo.setName(user.getUsername());
                }
                if(attendanceDetailsList!=null){
                    if(days!=null){
                        userAttenVo.setAttendanceDay(days.size());
                    }
                    for (AttendanceDetails attendanceDetails : attendanceDetailsList) {
                        if(attendanceDetails.getOutSideBusinessDay()!=null){
                            userAttenVo.setOutSideBusinessDay(attendanceDetails.getOutSideBusinessDay()+userAttenVo.getOutSideBusinessDay());
                        }
                        if(attendanceDetails.getOutWorkDay()!=null){
                            userAttenVo.setOutWorkDay(userAttenVo.getOutWorkDay()+attendanceDetails.getOutWorkDay());
                        }
                        if(attendanceDetails.getSickLeaveDay()!=null){
                            userAttenVo.setSickLeaveDay(userAttenVo.getSickLeaveDay()+attendanceDetails.getSickLeaveDay());
                        }
                        if(("0").equals(attendanceDetails.getIsLateDay())){
                            userAttenVo.setLateDay(userAttenVo.getLateDay()+1);
                        }
                        if("0".equals(attendanceDetails.getIsLeaveEarlyDay())){
                            userAttenVo.setLeaveEarlyDay(userAttenVo.getLeaveEarlyDay()+1);
                        }
                        if(attendanceDetails.getWorkOverHours()!=null){
                            userAttenVo.setOverWorkHours(userAttenVo.getOverWorkHours()+attendanceDetails.getWorkOverHours());
                        }

                        if(attendanceDetails.getAbsenteeismDay()!=null){
                            userAttenVo.setAbsenteeismDay(attendanceDetails.getAbsenteeismDay()+userAttenVo.getAbsenteeismDay());
                        }
                    }
                    userAttenVo.computerRealAttendanceDay();
                }
                return userAttenVo;
            } catch (ParseException e) {
                logger.error("时间转换格式错误");
            }
        }
        return userAttenVo;
    }

    @Override
    public List<UserAttenVo> findDepartment(AttenRequest request) {
        List<UserAttenVo> userAttenVos = new ArrayList<>();
        String id = request.getId();//部门id
        List<User> users = pasUserDao.findAll();
        List<User> userList = new ArrayList<>();
        if(users!=null){
            users.forEach(user -> {
                List<String> departmentIds = user.getDepartmentIds();
                if(departmentIds!=null){
                    departmentIds.contains(id);
                    userList.add(user);
                }
            });
        }
        List<AttenRequest> attenRequests = new ArrayList<>();
        userList.forEach(user -> {
            attenRequests.add(new AttenRequest(user.getId(),request.getDate(),request.getSearchType()));
        });
        if(attenRequests!=null){
            attenRequests.forEach(attenRequest1->{
                UserAttenVo userAttenVo = findPersonnel(attenRequest1);
                userAttenVos.add(userAttenVo);
            });
        }
        return userAttenVos;
    }


    /**
     * 查询可查看的部门列表
     * @param id
     * @return
     */
    @Override
    public List<Department> findDepartmentList(String id) {
        List<UserRole> userRoles = userRoleDao.findAllByUserId(id);
        List<String> roleIds = new ArrayList<>();
        List<String> departmentIds = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
        }
        List<Role> roles = roleDao.findAllByIdIn(roleIds);
        for (Role role : roles) {
            List<RoleAuthority> roleAuthorities = roleAuthorityDao.findAllByRoleId(role.getId());
            List<String> authorityIds = new ArrayList<>();
            for (RoleAuthority roleAuthority : roleAuthorities) {
                authorityIds.add(roleAuthority.getAuthorityId());
            }
            Authority authority = authorityDao.findByIdInAndName(authorityIds, "部门考勤");
            if(authority!=null){
                String departmentId = role.getDepartmentId();
                departmentIds.add(departmentId);
            }
        }
        List<Department> departmentList = departmentDao.findAllByIdIn(departmentIds);
        getDepartments(departmentList);
//        getDepartments(departmentIdList,departmentIds);
//        List<Department> departments = departmentDao.findAllByIdIn(departmentIdList);

        return departmentList;
    }

    /**
     * 递归获得部门树
     * @param departments
     */
    public void getDepartments(List<Department> departments) {
        for (Department department : departments) {
            List<Department> departmentList = departmentDao.findAllByParentId(department.getId());
            getDepartments(departmentList);
            department.setDepartments(departmentList);
        }
    }

}
