package com.zjty.tynotes.address.server.service.impl;

import com.zjty.tynotes.address.server.dao.NoticeDao;
import com.zjty.tynotes.address.server.entity.Notice;
import com.zjty.tynotes.address.server.service.NoticeService;
import com.zjty.tynotes.pas.dao.*;
import com.zjty.tynotes.pas.entity.*;
import com.zjty.tynotes.sms.service.MessageTemplateService;
import com.zjty.tynotes.sms.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.util.*;

/**
 * @Author gwj
 * @create 2020/5/13 14:40
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private PasUserDao pasUserDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleAuthorityDao roleAuthorityDao;
    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private MessageTemplateService messageTemplateService;

    /**
     * 查询同级别人员
     * @param level
     * @return
     */
    @Override
    public List<User> findUser(String level) {
        List<Department> departments = departmentDao.findAllByLevel(level);
        List<String> departIds = new ArrayList<>();
        List<String> roleIds = new ArrayList<>();
        List<String> userIds = new ArrayList<>();
        if(departments!=null){
            departments.forEach(department -> {
                departIds.add(department.getId());
            });
        }
        List<Role> roles = roleDao.findAllByDepartmentIdInAndIsLeader(departIds, "0");
        if(roles!=null){
            roles.forEach(role -> {
                roleIds.add(role.getId());
            });
        }
        List<UserRole> userRoles = userRoleDao.findAllByRoleIdIn(roleIds);
        if(userRoles!=null){
            userRoles.forEach(userRole -> {
                if(!userIds.contains(userRole.getUserId())){
                    userIds.add(userRole.getUserId());
                }
            });
        }
        List<User> users = pasUserDao.findAllByIdIn(userIds);
        for (User user: users) {
            System.out.println("leader:"+user.getUsername());
        }
        return users;
    }


    @Override
    public List<Department> findDepart(String id) {
        String departLevel = findDepartLevel(id);
        List<Department> departments = departmentDao.findAllByLevel(departLevel);
        return departments;
    }

    /**
     * 查找需要通知人的id集合
     * @param users 相同等级的用户
     * @param otherIds 需要借的人的id集合
     * @return
     */
    @Override
    public Map<String,List<String>> findLeadUser(List<User> users, List<String> otherIds,String level) {
        Map<String,List<String>> map = new HashMap<>();
        if(otherIds!=null){
            otherIds.forEach(s -> {
                if(users!=null){
                    for (User user : users) {
                        String id = user.getId();
                        List<String> userIdList = findUserIdList(id,level);
                        if(userIdList.contains(s)){
                            System.out.println(userIdList);
                            if(map.containsKey(user.getId())){
                                List<String> strings = map.get(user.getId());
                                if(strings!=null){
                                    strings.add(s);
                                    map.put(user.getId(),strings);
                                    break;
                                }
                            }else{
                                List<String> idList = new ArrayList<>();
                                idList.add(s);
                                map.put(user.getId(),idList);
                                break;
                            }
                        }
                    }
                }
            });
        }

        return map;
    }

    /**
     * 提交通知
     * @return
     */
    @Override
    public List<Notice> submitNotice(String publishId,Map<String,List<String>> map,String workId,String workName) {
        List<Notice> notices = new ArrayList<>();
        if(map!=null){
            for (Map.Entry<String,List<String>> entry : map.entrySet()) {
                String applyName = null;
                String responseName = null;
                Optional<User> op = pasUserDao.findById(publishId);

                Optional<User> optional = pasUserDao.findById(entry.getKey());
                if(optional.isPresent()){
                    responseName = optional.get().getUsername();
                }
                if(op.isPresent()){
                    applyName = op.get().getUsername();
                }
                List<String> value = entry.getValue();
                if(value!=null){
                    for (String s : value) {
                        Notice notice = new Notice();
                        notice.setUpdateTime(new Date());
                        notice.setWorkId(workId);
                        notice.setWorkName(workName);
                        notice.setApplyId(publishId);
                        notice.setApplyName(applyName);
                        notice.setResponseId(entry.getKey());
                        notice.setResponseName(responseName);
                        notice.setDes("因为"+workName+"向"+responseName+"借人员一用");
                        notice.setBorrowUserId(s);
                        notice.setIsRead("0");
                        notices.add(notice);
                    }
                }
            }
        }

        List<Notice> noticeList = noticeDao.saveAll(notices);
        return noticeList;
    }

    /**
     * 回应通知
     * @param notice
     * @return
     */
    @Override
    public Notice replyNotice(Notice notice) {
        notice.setUpdateTime(new Date());
        notice.setIsRead("1");
        return noticeDao.save(notice);
    }

    /**
     * 获取某部门下的所有用户(包括同级)
     * @return
     */
    @Override
    public List<User> findUnderUser(String departId) {
        List<User> userList = new ArrayList<>();
        List<String> departIds = new ArrayList<>();
        departIds = getDepartIds(departIds, departId);
        if(departIds!=null){
            departIds.forEach(s -> {
                List<User> users = pasUserDao.findAllByDepartmentIdsContains(s);
                if(users!=null){
                    users.forEach(user -> {
                        if(!userList.contains(user)){
                            userList.add(user);
                        }
                    });
                }
            });
        }
        return userList;
    }

    /**
     * 查询所有未读通知
     */
    @Override
    public List<Notice> findNotReadNotice(String id) {
        List<Notice> notices = noticeDao.findAllByResponseIdAndIsRead(id, "0");
        return notices;
//        messageTemplateService.noticePushed(id, JacksonUtil.toJSon(notices));
    }

    /**
     * 查询所有我请求的通知
     * @param id
     * @return
     */
    @Override
    public List<Notice> findReadNotice(String id) {
        return noticeDao.findAllByApplyId(id);
    }

    /**
     * 递归获得某个部门下的所有部门id集合
     * @param ids
     * @param departId
     * @return
     */
    public List<String> getDepartIds(List<String> ids,String departId){
        ids.add(departId);
        List<Department> departments = departmentDao.findAllByParentId(departId);
        if(departments!=null){
            departments.forEach(department -> {
                getDepartIds(ids,department.getId());
            });
        }
        return ids;
    }

    /**
     * 查看发布者下的所有人员id集合
     */
    @Override
    public List<String> findUserIdList(String userId){
        List<String> userIds = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        Optional<User> optional = pasUserDao.findById(userId);
        List<String> departmentIds = new ArrayList<>();
        List<String> departIds = new ArrayList<>();//所有部门id集合
        if(optional.isPresent()){
            User user = optional.get();
            List<String> roleIds = new ArrayList<>();
            List<UserRole> userRoles = userRoleDao.findAllByUserId(user.getId());
            if(userRoles!=null){
                userRoles.forEach(userRole -> {
                    roleIds.add(userRole.getRoleId());
                });
            }
            List<Role> roles = roleDao.findAllByIdIn(roleIds);
            if(roles!=null){
                roles.forEach(role -> {
                    if(role.getIsLeader().equals("0")){
                        departmentIds.add(role.getDepartmentId());
                    }
                });
            }
        }
        if(departmentIds!=null){
            departmentIds.forEach(s -> {
                List<String> deIds = new ArrayList<>();
                deIds = getDepartIds(deIds,s);
                if(deIds!=null){
                    deIds.forEach(s1 -> {
                        if(!departIds.contains(s1)){
                            departIds.add(s1);
                        }
                    });
                }
            });
        }

        if(departIds!=null){
            departIds.forEach(s -> {
                List<User> users = pasUserDao.findAllByDepartmentIdsContains(s);
                if(users!=null){
                    users.forEach(user -> {
                        if(!userList.contains(user)){
                            userList.add(user);
                        }
                    });
                }

            });
        }

        if(userList!=null){
            userList.forEach(user -> {
                userIds.add(user.getId());
            });
        }

        return userIds;
    }


    /**
     * 查看发布者下的所有人员id集合
     */
    public List<String> findUserIdList(String userId,String level){
        List<String> userIds = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        Optional<User> optional = pasUserDao.findById(userId);
        List<String> departmentIds = new ArrayList<>();
        List<String> departIds = new ArrayList<>();//所有部门id集合
        if(optional.isPresent()){
            User user = optional.get();
            List<String> roleIds = new ArrayList<>();
            List<UserRole> userRoles = userRoleDao.findAllByUserId(user.getId());
            if(userRoles!=null){
                userRoles.forEach(userRole -> {
                    roleIds.add(userRole.getRoleId());
                });
            }
            List<Role> roles = roleDao.findAllByIdIn(roleIds);
            if(roles!=null){
                roles.forEach(role -> {
                    if(role.getIsLeader().equals("0")){
                        String departmentId = role.getDepartmentId();
                        Optional<Department> op = departmentDao.findById(departmentId);
                        if(op.isPresent()){
                            Department department = op.get();
                            if(department.getLevel().equals(level)){
                                departmentIds.add(role.getDepartmentId());
                            }
                        }
                    }
                });
            }
        }
        if(departmentIds!=null){
            departmentIds.forEach(s -> {
                List<String> deIds = new ArrayList<>();
                deIds = getDepartIds(deIds,s);
                if(deIds!=null){
                    deIds.forEach(s1 -> {
                        if(!departIds.contains(s1)){
                            departIds.add(s1);
                        }
                    });
                }
            });
        }

        if(departIds!=null){
            departIds.forEach(s -> {
                List<User> users = pasUserDao.findAllByDepartmentIdsContains(s);
                if(users!=null){
                    users.forEach(user -> {
                        if(!userList.contains(user)){
                            userList.add(user);
                        }
                    });
                }

            });
        }

        if(userList!=null){
            userList.forEach(user -> {
                userIds.add(user.getId());
            });
        }

        return userIds;
    }


    /**
     * 查找发布者的部门等级
     * @param publisher
     * @return
     */
    @Override
    public String findDepartLevel(String publisher) {
        Integer level = null;
        Optional<User> optional = pasUserDao.findById(publisher);
        List<String> departmentIds = new ArrayList<>();
        if(optional.isPresent()){
            User user = optional.get();
            List<String> roleIds = new ArrayList<>();
            List<UserRole> userRoles = userRoleDao.findAllByUserId(user.getId());
            if(userRoles!=null){
                userRoles.forEach(userRole -> {
                    roleIds.add(userRole.getRoleId());
                });
            }
            List<Role> roles = roleDao.findAllByIdIn(roleIds);
            if(roles!=null){
                roles.forEach(role -> {
                    if(role.getIsLeader().equals("0")){
                        List<String> authorities = new ArrayList<>();
                        List<RoleAuthority> roleAuthorities = roleAuthorityDao.findAllByRoleId(role.getId());
                        if(roleAuthorities!=null){
                            roleAuthorities.forEach(roleAuthority -> {
                                authorities.add(roleAuthority.getAuthorityId());
                            });
                        }
                        if(authorities!=null){
                            List<Authority> authorityList = authorityDao.findAllByIdIn(authorities);
                            if(authorityList!=null){
                                authorityList.forEach(authority -> {
                                    if(authority.getName().equals("发布任务")){
                                        departmentIds.add(role.getDepartmentId());
                                    }
                                });
                            }
                        }

                    }
                });
            }
        }
        if(departmentIds!=null){
            List<Department> departments = departmentDao.findAllByIdIn(departmentIds);
            if(departments!=null){
                for (Department department : departments) {
                    if(level==null){
                        level = Integer.parseInt( department.getLevel());
                    }else{
                        int i = Integer.parseInt(department.getLevel());
                        if(i<level){
                            level = i;
                        }
                    }
                }
            }
        }
        return level+"";
    }


}
