package com.fs.company.service.impl;

import com.fs.common.annotation.DataScope;
import com.fs.common.core.domain.R;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
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.service.ICompanyUserService;
import com.fs.company.vo.CompanyQwUserByIdsVo;
import com.fs.company.vo.CompanyUserQwListVO;
import com.fs.company.vo.CompanyUserVO;
import com.fs.company.vo.DocCompanyUserVO;
import com.fs.his.service.IFsCityService;
import com.fs.his.vo.CitysAreaVO;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.system.service.ISysConfigService;
import com.fs.wxUser.domain.CompanyWxUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @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 结果
     */

    @Autowired
    QwUserMapper qwUserMapper;
    @Override
    public int deleteCompanyUserByIds(Long[] userIds)
    {
        for (int i = 0; i <userIds.length ; i++) {
            //清除企微的销售的绑定关系
            qwUserMapper.updateUserByUserId(userIds[i]);
        }
        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();
        // 删除用户与角色关联
        logger.info("wc \n 【删除角色】:{}", user.getUserName());
        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 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);
    }

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

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

    @Override
    public List<QwUserVO> selectCompanyQwUserList(String corpId,Long companyId) {
        return companyUserMapper.selectCompanyQwUserList(corpId,companyId);
    }
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUserQwListVO> selectCompanyUserQwListVO(CompanyUserQwParam user) {
        return companyUserMapper.selectCompanyUserQwListVO(user);
    }

    @Override
    public R updateCompanyUserAreaList(CompanyUserAreaParam param) {

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

    }

    @Override
    public CompanyWxUser selectCompanyUserByNickName(Long companyUserId, String nickName) {
        return companyUserMapper.selectCompanyUserByNickName(companyUserId, nickName);
    }

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

    /**
     * 新增用户岗位信息
     *
     * @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);
                logger.info("wc \n 【完成角色更新】:{}", user.getUserName());
            }
        }
    }

    @Override
    public List<CompanyUser> selectCompanyUserByIds(Set<Long> ids) {
        return companyUserMapper.selectCompanyUserByIds(ids);
    }

    @Override
    public String importUserInfoService(List<CompanyUser> userList,Long deptId,Long companyId) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (CompanyUser user : userList) {
            if (user.getUserName() == null || "".equals(user.getUserName()))
            {
                throw new ServiceException("用户账号不能为空！");
            }
            if (user.getNickName() == null || "".equals(user.getNickName()))
            {
                throw new ServiceException("用户昵称不能为空！");
            }
            if (user.getPhonenumber() == null || "".equals(user.getPhonenumber()))
            {
                throw new ServiceException("手机号码不能为空！");
            }
            if (user.getSex() == null || "".equals(user.getSex()))
            {
                throw new ServiceException("用户性别不能为空！");
            }
            if (user.getPassword() == null || "".equals(user.getPassword()))
            {
                throw new ServiceException("密码不能为空！");
            }
            //通过账号校验账号是否存在
            String userName = companyUserMapper.selectCompanyUserByUserName(user.getUserName());
            if(userName != null){
                throw new ServiceException(userName + ",账号已存在！");
            }
        }

        for (CompanyUser user : userList)
        {

            try
            {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
                user.setToken("".equals(user.getToken())?null:user.getToken());
                user.setIdCard("".equals(user.getIdCard())?null:user.getIdCard());
                user.setCompanyId(companyId);
                user.setDeptId(deptId);
                user.setStatus("0");
                user.setUserType("01");
                user.setCreateTime(new Date());
                this.insertUser(user);
                successNum++;
                successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
