package com.fs.company.service.impl;

import com.fs.common.annotation.DataScope;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.*;
import com.fs.company.mapper.*;
import com.fs.company.param.CompanyUserAreaParam;
import com.fs.company.param.CompanyUserQwParam;
import com.fs.company.param.CompanyVoiceCallerParam;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.*;
import com.fs.his.vo.CitysAreaVO;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.his.vo.OptionsVO;
import com.fs.store.service.IFsCityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 物业公司管理员信息Service业务层处理
 *
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyUserServiceImpl implements ICompanyUserService
{
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private CompanyRoleMapper roleMapper;

    @Autowired
    private CompanyPostMapper postMapper;

    @Autowired
    private CompanyUserRoleMapper userRoleMapper;

    @Autowired
    private CompanyUserPostMapper userPostMapper;

    @Autowired
    private CompanyVoiceCallerMapper callerMapper;

    @Autowired
    public IFsCityService iFsCityService;

    /**
     * 查询物业公司管理员信息
     *
     * @param userId 物业公司管理员信息ID
     * @return 物业公司管理员信息
     */
    @Override
    public CompanyUser selectCompanyUserById(Long userId)
    {
        return companyUserMapper.selectCompanyUserById(userId);
    }

    /**
     * 查询物业公司管理员信息列表
     *
     * @param companyUser 物业公司管理员信息
     * @return 物业公司管理员信息
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUser> selectCompanyUserList(CompanyUser companyUser)
    {
        return companyUserMapper.selectCompanyUserList(companyUser);
    }

    /**
     * 新增物业公司管理员信息
     *
     * @param companyUser 物业公司管理员信息
     * @return 结果
     */
    @Override
    public int insertCompanyUser(CompanyUser companyUser)
    {
        companyUser.setCreateTime(DateUtils.getNowDate());
        return companyUserMapper.insertCompanyUser(companyUser);
    }

    /**
     * 修改物业公司管理员信息
     *
     * @param companyUser 物业公司管理员信息
     * @return 结果
     */
    @Override
    public int updateCompanyUser(CompanyUser companyUser)
    {
        companyUser.setUpdateTime(DateUtils.getNowDate());
//        if (companyUser.getStatus().equals("1")){
//            CompanyVoiceCaller caller = callerMapper.selectCompanyVoiceCallerByUserId(companyUser.getCompanyId(),companyUser.getUserId());
//            caller.setCompanyId(0l);
//            caller.setCompanyUserId(0l);
//            caller.setMobile("");
//            caller.setStatus(1);
//            callerMapper.updateCompanyVoiceCaller(caller);
//        }
        return companyUserMapper.updateCompanyUser(companyUser);
    }

    @Override
    public int updateAllCompanyUser(CompanyUser companyUser) {
        return companyUserMapper.updateAllCompanyUser(companyUser);
    }


    /**
     * 批量删除物业公司管理员信息
     *
     * @param userIds 需要删除的物业公司管理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserByIds(Long[] userIds)
    {
        return companyUserMapper.deleteCompanyUserByIds(userIds);
    }

    /**
     * 删除物业公司管理员信息信息
     *
     * @param userId 物业公司管理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserById(Long userId)
    {
        return companyUserMapper.deleteCompanyUserById(userId);
    }

    @Override
    public CompanyUser selectUserByUserName(String account) {
        return companyUserMapper.selectUserByUserName(account);
    }

    @Override
    public String selectUserRoleGroup(String username) {
        List<CompanyRole> list = roleMapper.selectRolesByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserPostGroup(String username) {
        List<CompanyPost> list = postMapper.selectPostsByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public int updateUserAvatar(String username, String avatar) {
        return companyUserMapper.updateUserAvatar(username, avatar) ;
    }

    @Override
    public int resetUserPwd(String userName, String encryptPassword) {
        return companyUserMapper.resetUserPwd(userName, encryptPassword);
    }

    @Override
    public int updateUserProfile(CompanyUser user) {
        return companyUserMapper.updateCompanyUser(user);
    }

    @Override
    public int checkUserName(String userName) {
        return companyUserMapper.checkUserName(userName);
    }


    @Override
    @Transactional
    public int insertUser(CompanyUser user)
    {
        // 新增用户信息
        int rows = companyUserMapper.insertCompanyUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(CompanyUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return companyUserMapper.updateCompanyUser(user);
    }

    @Override
    public int resetUserPwdByUserId(Long userId, String encryptPassword) {
        return companyUserMapper.resetUserPwdByUserId(userId,encryptPassword);
    }

    @Override
    public List<Map<String, Object>> selectAllUsersList(CompanyUser user) {
        List<CompanyUser> users = companyUserMapper.selectAllUsersList(user);
        Set<String> firstChar = new HashSet<String>();
        for (CompanyUser u: users){
            firstChar.add(u.getFirstchar());
        }
        List<Map<String,Object>> userlist = new ArrayList<>();
        for(String n:firstChar){
            Map<String,Object> map = new HashMap<>();
            List<CompanyUser> subMenuIds = users.stream().filter(s->s.getFirstchar().equals(n)).collect(Collectors.toList());
            map.put("letter",n);
            map.put("data",subMenuIds);
            userlist.add(map);
        }
        return userlist;
    }

    @Override
    public List<CompanyUserVO> selectMyUserList(CompanyUser user) {
        return companyUserMapper.selectMyUserList(user);
    }

    @Override
    @DataScope(deptAlias = "u",userAlias = "u")
    public List<CompanyUser> getUserListByDeptId(CompanyUser user) {
        return companyUserMapper.getUserListByDeptId(user);
    }

    @Override
    public List<CompanyUser> selectCompanyNoQwUserList(Long companyId) {
//        return companyUserMapper.selectCompanyNoQwUserList(companyId);
        return Collections.emptyList();
    }

    @Override
    public List<QwUserVO> selectCompanyQwUserList(String corpId, Long companyId) {
        return companyUserMapper.selectCompanyQwUserList(corpId,companyId);
    }

    @Override
    public Integer selectCompanyUserCountByCompanyId(Long companyId) {
        return companyUserMapper.selectCompanyUserCountByCompanyId(companyId);
    }

    @Override
    public String checkUserNameUnique(String userName) {
        return companyUserMapper.checkUserNameUnique(userName)>0?"1":"0";
    }

    @Override
    public List<DocCompanyUserVO> selectDocCompanyUserListByIds(String companyUserIds) {
        return companyUserMapper.selectDocCompanyUserListByIds(companyUserIds);
    }

    @Override
    public CompanyUser selectCompanyUserByCompanyIdAndNickName(long companyId, String nickName) {
        return companyUserMapper.selectCompanyUserByCompanyIdAndNickName(companyId,nickName);
    }

    @Override
    public List<CompanyUserVO> selecCompanyAllUsersList(CompanyUser map) {
        return companyUserMapper.selecCompanyAllUsersList(map);
    }


    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(CompanyUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<CompanyUserPost> list = new ArrayList<CompanyUserPost>();
            for (Long postId : posts)
            {
                CompanyUserPost up = new CompanyUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }
    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(CompanyUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<CompanyUserRole> list = new ArrayList<CompanyUserRole>();
            for (Long roleId : roles)
            {
                CompanyUserRole ur = new CompanyUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    @Override
    public CompanyUser selectCompanyUserAdminByCompanyId(Long companyId) {
        return companyUserMapper.selectCompanyUserAdminByCompanyId(companyId);
    }
    /**
     * 根据部门的id获取到企业微信的qwuserid
     */
    @Override
    public List<CompanyUserQwVO> getUserListByDeptIdToQwUserid(CompanyUser user) {

        return companyUserMapper.getUserListByDeptIdToQwUserid(user);
    }


    /**
     * 根据部门id+公司id查询下面的企业微信用户列表
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUserQwListVO> selectCompanyUserQwListVO(CompanyUserQwParam user) {
        return companyUserMapper.selectCompanyUserQwListVO(user);
    }

    @Override
    public List<OptionsVO> selectCompanyUserBySalesman() {
//        return companyUserMapper.selectCompanyUserBySalesman();
        return Collections.emptyList();
    }

    @Override
    public List<CompanyQwUserByIdsVo> selectCompanyQwUserByIds(List<Long> ids) {
        return companyUserMapper.selectCompanyQwUserByIds(ids);
    }

    @Override
    public CompanyUser selectCompanyUserByUserId(Long userId) {
        return companyUserMapper.selectCompanyUserByUserId(userId);
    }

    /**
     * 查询公司销售列表
     * @param ids 销售ID集合
     * @return  list
     */
    @Override
    public List<CompanyUser> selectCompanyUserByIds(Set<Long> ids) {
        return companyUserMapper.selectCompanyUserByIds(ids);
    }

    @Override
    public  List<CompanyUser> selectAllCompanyUserByParentId(Long parentId) {
        return companyUserMapper.selectAllCompanyUserByParentId(parentId);
    }

    @Override
    public List<CompanyUser> selectAllCompanyUserAndSelf(Long userId) {
        return companyUserMapper.selectAllCompanyUserAndSelf(userId);
    }

    @Override
    public List<CompanyUser> getAllUserListLimit(Long companyId, String keywords) {

        return companyUserMapper.getAllUserListLimit(companyId,keywords);
    }

    @Override
    public List<CitysAreaVO> getCitysAreaList() {
        return iFsCityService.getCitysArea();
    }

    @Override
    public R updateCompanyUserAreaList(CompanyUserAreaParam param) {
        int i = companyUserMapper.updateCompanyUserAreaList(param);
        if (i > 0) {
            return R.ok("操作成功");
        }else {
            return R.error("操作失败");
        }
    }

    @Override
    public CompanyUser getCompanyUserByOpenId(String openId) {
        return companyUserMapper.getCompanyUserByOpenId(openId);
    }

    @Override
    public CompanyUser getCompanyUserByPhone(String phoneNumber) {
        return companyUserMapper.getCompanyUserByPhone(phoneNumber);
    }

    /**
     * 批量审核用户
     * @param userIds 用户ID集合
     */
    @Override
    public void auditUsers(List<Long> userIds) {
        if (userIds.isEmpty()) {
            return;
        }
        companyUserMapper.auditUsers(userIds);
    }

    /**
     * 查询下级销售列表
     * @param companyUserId 销售ID
     * @return list
     */
    @Override
    public List<CompanyUser> selectCompanySubUserList(Long companyUserId) {
        return companyUserMapper.selectAllCompanyUserByParentId(companyUserId);
    }

}
