package com.zhongshu.card.server.core.service.user;

import com.github.microservice.auth.client.content.ResultState;
import com.github.microservice.auth.client.model.UserAuthModel;
import com.github.microservice.auth.client.model.UserModel;
import com.github.microservice.auth.client.service.UserService;
import com.github.microservice.auth.client.type.LoginType;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.google.common.collect.Lists;
import com.zhongshu.card.client.model.base.AuthTypeParam;
import com.zhongshu.card.client.model.base.UserIdModel;
import com.zhongshu.card.client.model.org.*;
import com.zhongshu.card.client.model.org.role.RoleModel;
import com.zhongshu.card.client.model.orgModel.OrgBindUserAllParam;
import com.zhongshu.card.client.model.school.DictInfoSimpleModel;
import com.zhongshu.card.client.service.org.UserAccountService;
import com.zhongshu.card.client.type.Sex;
import com.zhongshu.card.client.type.UserLoginType;
import com.zhongshu.card.client.type.UserState;
import com.zhongshu.card.client.type.UserType;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.org.OrganizationUserDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.dataConfig.CardSystemDefault;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.OrganizationUser;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.service.base.CommonService;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.org.OrganizationServiceImpl;
import com.zhongshu.card.server.core.service.org.OrganizationUserServiceImpl;
import com.zhongshu.card.server.core.service.orgManager.OrganizationManagerServiceImpl;
import com.zhongshu.card.server.core.service.school.DictInfoServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.server.core.util.CommonUtil;
import com.zhongshu.card.server.core.util.ValidateResult;
import com.zhongshu.card.server.core.util.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/5/31
 */
@Slf4j
@Service
@Primary
public class UserAccountServiceImpl extends SuperService implements UserAccountService, Serializable {

    @Autowired
    UserCountDao userCountDao;

    @Autowired
    OrganizationServiceImpl organizationService;

    @Autowired
    OrganizationManagerServiceImpl organizationManagerService;

    @Autowired
    UserService userService;

    @Autowired
    OrganizationDao organizationDao;

    @Autowired
    OrganizationUserDao organizationUserDao;

    @Autowired
    RoleServiceImpl roleServiceImpl;

    @Autowired
    DepartmentServiceImpl departmentService;

    @Autowired
    DictInfoServiceImpl dictInfoService;

    @Autowired
    private OrganizationUserServiceImpl organizationUserService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private UserAboutInfoService userAboutInfoService;

    /**
     * 注册基本用户 (没有就注册，有就修改)
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<String> registerUserAccount(RegisterUserAccountParam param) {
        if (StringUtils.isEmpty(param.getLoginName())) {
            return ResultContent.buildFail(String.format("loginName不能为空"));
        }
        // 电话号码为登录名
        String loginName = param.getLoginName();
        UserAccount userAccount = userCountDao.findTopByLoginName(loginName);
        if (ObjectUtils.isEmpty(userAccount)) {
            String cardNumber = param.getCardNumber();
            String passWord = param.getPassword();
            if (StringUtils.isEmpty(passWord)) {
                passWord = CardSystemDefault.DEFAULT_PASSWORD;
            }
            if (ValidateUtils.isIDCard(cardNumber)) {
                passWord = cardNumber.substring(12, 18);
                passWord = passWord.toLowerCase().replace("x", "0");
            }

            String userId = "";
            // 检查权限中心有这用户不
            com.github.microservice.auth.client.content.ResultContent<UserModel> queryContent = userService.queryFromLoginType(LoginType.Phone, loginName);
            if (queryContent.getState() == ResultState.Success) {
                UserModel userModel = queryContent.getContent();
                if (ObjectUtils.isNotEmpty(userModel)) {
                    userId = userModel.getUserId();
                }
            }

            if (StringUtils.isEmpty(userId)) {
                // 权限中心：添加用户
                com.github.microservice.auth.client.content.ResultContent<String> addModelResult = userService.add(UserAuthModel.builder().loginType(LoginType.Phone).loginValue(loginName).passWord(passWord).build());
                if (addModelResult.getState() != ResultState.Success) {
                    return ResultContent.buildFail(String.format("权限中心添加用户出错：%s", addModelResult.getMsg()));
                }
                userId = addModelResult.getContent();
            }

            // 本地用户
            userAccount = new UserAccount();
            BeanUtils.copyProperties(param, userAccount);

            String realName = param.getRealName();
            if (StringUtils.isEmpty(realName)) {
                realName = param.getName();
            }
            userAccount.setRealName(realName);
            userAccount.setUserId(userId);
            userAccount.setLoginType(UserLoginType.All);

            userAccount.setOid(null);
            userAccount.setLoginName(loginName);
            userAccount.setIsLogined(Boolean.FALSE);
            userAccount.setSpellCode(CommonUtil.getPinyin(param.getName()));
            userAccount.setIsUpdatedPsw(Boolean.FALSE);
            userAccount.setUserType(UserType.Consumer);
            userCountDao.save(userAccount);
        } else {
            // 编辑
             BeanUtils.copyPropertiesWithoutNull(param, userAccount);
            String realName = param.getRealName();
            if (StringUtils.isEmpty(realName)) {
                realName = param.getName();
            }
            userAccount.setRealName(realName);
            userAccount.setSpellCode(CommonUtil.getPinyin(param.getName()));
            userCountDao.save(userAccount);

            userAboutInfoService.updateUserAboutEntityInfo(userAccount);
        }
        return ResultContent.buildSuccess(userAccount.getUserId());
    }

    /**
     * @param oid               机构oid
     * @param userId            用户userId
     * @param isContentUserInfo 在没找到用户在结构的信息时，返回组装用户的基本信息
     * @return
     */
    @Override
    public OrganizationUserModel getOrgUserDetail(String oid, String userId, boolean isContentUserInfo) {
        OrgUserDetailParam param = new OrgUserDetailParam();
        param.setOid(oid);
        param.setUserId(userId);
        ResultContent<OrganizationUserModel> content = getOrgUserDetail(param);
        if (content.isSuccess()) {
            return content.getContent();
        }
        if (isContentUserInfo && StringUtils.isNotEmpty(userId)) {
            UserAccount userAccount = userCountDao.findTopByUserId(userId);
            if (ObjectUtils.isEmpty(userAccount)) {
                return null;
            }
            OrganizationUserModel organizationUser = new OrganizationUserModel();
            organizationUser.setUser(toSimpleModel(userAccount));
            return organizationUser;
        }
        return null;
    }

    @Override
    public ResultContent<OrganizationUserModel> getOrgUserDetail(OrgUserDetailParam param) {
        String userId = param.getUserId();
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        Assert.hasText(oid, "oid不能为空");
        Assert.hasText(userId, "userId不能为空");

        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, oid));
        }
        UserAccount temp = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(temp)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, userId));
        }
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, temp);
        OrganizationUserModel model = toOrgUserModel(organizationUser);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 删除机构用户
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent deleteOrgUser(DelUserCountParam param) {
        String userId = param.getUserId();
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        Assert.hasText(oid, "oid不能为空");
        Assert.hasText(userId, "userId不能为空");

        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, oid));
        }
        UserAccount temp = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(temp)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, userId));
        }
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, temp);
        if (ObjectUtils.isEmpty(organizationUser)) {
            return ResultContent.buildFail(String.format("企业没有改用户：%s", oid));
        }
        if (organizationUser.getIsAdmin() != null && organizationUser.getIsAdmin()) {
            return ResultContent.buildFail(String.format("管理员用户不能删除"));
        }
        organizationUserDao.delete(organizationUser);
        return ResultContent.buildSuccess();
    }

    /**
     * 修改用户状态
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent updateOrgUserState(UpdateUserStateParam param) {
        String userId = "";

        // 初始基本用户信息
        RegisterUserAccountParam userAccountParam = new RegisterUserAccountParam();
        if (StringUtils.isEmpty(param.getUserId())) {
            // 新增加
            if (StringUtils.isEmpty(param.getName())) {
                return ResultContent.buildFail("name不能为空");
            }
            if (StringUtils.isEmpty(param.getPhone())) {
                return ResultContent.buildFail("phone不能为空");
            }
            if (StringUtils.isEmpty(param.getPassword())) {
                return ResultContent.buildFail("password不能为空");
            }
            ValidateResult validateResult = ValidateUtils.validatePassWord(param.getPassword());
            if (!validateResult.isSuccess()) {
                return ResultContent.buildFail(validateResult.getMsg());
            }
            userAccountParam.setLoginName(param.getPhone());
            userAccountParam.setPassword(param.getPassword());
            userAccountParam.setPhone(param.getPhone());
        } else {
            userId = param.getUserId();
            UserAccount temp = userCountDao.findTopByUserId(userId);
            userAccountParam.setLoginName(temp.getLoginName());
            userAccountParam.setPhone(temp.getPhone());
            userAccountParam.setUserType(temp.getUserType());
        }
        userAccountParam.setName(param.getName());
        userAccountParam.setState(param.getState());

        // 基础用户信息维护
        ResultContent<String> userAccountContent = registerUserAccount(userAccountParam);
        if (userAccountContent.isFailed()) {
            return ResultContent.buildFail(userAccountContent.getMsg());
        }
        userId = userAccountContent.getContent();


        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        if (StringUtils.isEmpty(oid)) {
            return ResultContent.buildFail("oid不能为空");
        }
        Assert.hasText(userId, "userId不能为空");

        // 机构信息
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, oid));
        }
        // 用户数据
        UserAccount temp = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(temp)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, userId));
        }

        OrgBindUserAllParam orgBindUserAllParam = new OrgBindUserAllParam();
        orgBindUserAllParam.setUserId(userId);
        // 要绑定的机构
        orgBindUserAllParam.setOrgOid(organization.getOid());
        orgBindUserAllParam.setRoleIds(param.getRoleIds());
        orgBindUserAllParam.setState(param.getState());
        orgBindUserAllParam.setRemark(param.getRemark());
        orgBindUserAllParam.setProjectOid(organization.getOid());
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, temp);
        if (ObjectUtils.isNotEmpty(organizationUser)) {
            orgBindUserAllParam.setId(organizationUser.getId());
            orgBindUserAllParam.setCode(organizationUser.getCode());
            if (organizationUser.getPosition() != null) {
                orgBindUserAllParam.setPositionId(organizationUser.getPosition().getId());
            }
            if (organizationUser.getDepartment() != null) {
                orgBindUserAllParam.setDepartmentId(organizationUser.getDepartment().getId());
            }
        } else {
            orgBindUserAllParam.setIsAdmin(Boolean.FALSE);
        }
        // 绑定用户到机构
        ResultContent<OrganizationUser> bindUserContent = organizationUserService.orgBindUser(orgBindUserAllParam);
        if (bindUserContent.isFailed()) {
            return ResultContent.buildFail(bindUserContent.getMsg());
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 当前用户修改密码
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent updatePassWord(PassWordModel param) {
        Assert.hasText(param.getOldPass(), "密码不能为空");
        Assert.hasText(param.getPassWord(), "新密码不能为空");
        Assert.hasText(param.getConfirmPass(), "验证密码不能为空");
        if (!param.getPassWord().equals(param.getConfirmPass())) {
            return ResultContent.buildFail(String.format("密码和验证密码不一致"));
        }
        if (param.getOldPass().equals(param.getPassWord())) {
            return ResultContent.buildFail(String.format("原密码和新证密码不能一致"));
        }

        String userId = param.getUserId();
        com.github.microservice.auth.client.content.ResultContent<Void> resultContent = userService.checkLoginPassword(userId, param.getOldPass());
        if (resultContent.getState() == ResultState.Success) {
            com.github.microservice.auth.client.content.ResultContent<Void> resultContent1 = userService.updateLoginPassword(param.getUserId(), param.getPassWord());
            if (resultContent1.getState() != ResultState.Success) {
                return ResultContent.buildFail(resultContent1.getMsg());
            }
        } else {
            return ResultContent.buildFail(resultContent.getMsg());
        }
        // 标记已修改过密码
        UserAccount temp = userCountDao.findTopByUserId(userId);
        temp.setIsUpdatedPsw(Boolean.TRUE);
        userCountDao.save(temp);
        return ResultContent.buildSuccess();
    }


    /**
     * 编辑当前用户头像
     *
     * @param url
     * @return
     */
    public ResultContent updateUserHead(String url) {
        String userId = getCurrentUserId();
        Assert.hasText(userId, "当前用户userId为空");
        UserAccount account = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(account)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, userId));
        }
        account.setProfilePic(url);
        userCountDao.save(account);
        return ResultContent.buildSuccess();
    }

    /**
     * 编辑当前用户的基本信息
     *
     * @param param
     * @return
     */
    public ResultContent updateUserInfo(UserCountUpdateParam param) {
        String userId = getCurrentUserId();
        Assert.hasText(userId, "当前用户userId为空");
        UserAccount account = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(account)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, userId));
        }
        BeanUtils.copyProperties(param, account);
        account.setSpellCode(CommonUtil.getPinyin(account.getName()));
        userCountDao.save(account);

        String projectOid = getCurrentProjectOid();
        organizationUserService.changeUserBaseInfo(account.getUserId(), projectOid);
        return ResultContent.buildSuccess();
    }

    /**
     * 重置密码
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent resetPassWord(UserIdModel param) {
        UserAccount userCount = userCountDao.findTopByUserId(param.getUserId());
        if (ObjectUtils.isEmpty(userCount)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getUserId()));
        }
        com.github.microservice.auth.client.content.ResultContent<Void> resultContent = userService.updateLoginPassword(param.getUserId(), CardSystemDefault.DEFAULT_PASSWORD);
        if (resultContent.getState() != ResultState.Success) {
            return ResultContent.buildFail(resultContent.getMsg());
        }
        return ResultContent.buildSuccess();
    }

    @Override
    public ResultContent<Page<OrganizationUserModel>> projectUserPage(OrganizationUserSearch param, Pageable pageable) {
        initSearchParam(param);
        Page<OrganizationUser> page = organizationUserDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toOrgUserModel));
    }

    /**
     * 查询机构用户列表
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<OrganizationUserModel>> pageOrgUser(OrganizationUserSearch param, Pageable pageable) {
        initSearchParam(param);
        Page<OrganizationUser> page = organizationUserDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toOrgUserModel));
    }

    /**
     * 初始化一个 账号信息 （创建机构时用）
     *
     * @return
     */
    public UserAccount initUserAccountOrg(String uid, Organization entity) {
        UserAccount userAccount = userCountDao.findTopByUserId(uid);
        if (ObjectUtils.isEmpty(userAccount)) {
            userAccount = new UserAccount();
            userAccount.setUserId(uid);
            userAccount.setPhone(entity.getContactPhone());
            userAccount.setLoginName(entity.getContactPhone());
            if (!StringUtils.isNotEmpty(entity.getContactPhone())) {
                userAccount.setName("用户" + CommonUtil.getPhoneLast4(entity.getContactPhone()));
            } else {
                userAccount.setName("用户");
            }
            userAccount.setIsLogined(false);
            userAccount.setIsUpdatedPsw(false);
            userAccount.setState(UserState.Normal);
            userAccount.setSex(Sex.Male);
            userCountDao.save(userAccount);
        }
        return userAccount;
    }

    /**
     * 得到当前的用户信息 (包含机构信息)
     *
     * @param param
     * @return
     */
    public ResultContent<UserCountDetailsModel> getCurrentDetail(AuthTypeParam param) {
        UserCountDetailsModel model = new UserCountDetailsModel();
        UserAccount userAccount = userCountDao.findTopByUserId(getCurrentUserId());
        if (ObjectUtils.isNotEmpty(userAccount)) {
            UserCountModel model1 = toModel(userAccount);
            BeanUtils.copyProperties(model1, model, "oid");
        }
        return ResultContent.buildSuccess(model);
    }

    public ResultContent<UserCountDetailsModel> getBusCurrentDetail(AuthTypeParam param) {
        UserCountDetailsModel model = new UserCountDetailsModel();
        UserAccount userAccount = userCountDao.findTopByUserId(getCurrentUserId());
        if (ObjectUtils.isNotEmpty(userAccount)) {
            UserCountModel model1 = toModel(userAccount);
            BeanUtils.copyProperties(model1, model, "oid");

            // 用户加入的商户列表
            List<UserJoinBusOrgModel> busModels = organizationService.getUserAboutShopList(userAccount.getUserId());
            model.setBusList(busModels);
        }
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到当前的用户信息 (包含机构信息)
     *
     * @param param
     * @return
     */
    public ResultContent<UserCountDetailsModel> getCurrentDetailAndOrgs(AuthTypeParam param) {
        UserCountDetailsModel model = new UserCountDetailsModel();
        UserAccount userAccount = userCountDao.findTopByUserId(getCurrentUserId());
        if (ObjectUtils.isNotEmpty(userAccount)) {
            UserCountModel model1 = toModel(userAccount);
            BeanUtils.copyProperties(model1, model);
            // 查询机构列表
            OrganizationUserSearch search = new OrganizationUserSearch();
            search.setState(UserState.Normal);
            search.setAuthType(param.getLoginFromType());
            search.setUserId(getCurrentUserId());
            ResultContent<List<OrganizationModel>> resultContent = organizationService.getUserOrgList(search);
            if (resultContent.isSuccess()) {
                model.setList(resultContent.getContent());
            }
        }
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到用户信息 (基本信息)
     *
     * @param userId
     * @return
     */
    public ResultContent<UserCountModel> getUserDetail(String userId) {
        UserCountModel model = new UserCountModel();
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isNotEmpty(userAccount)) {
            model = toModel(userAccount);
        }
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到当前用户在当前机构的信息
     *
     * @return
     */
    @Override
    public ResultContent<OrganizationUserModel> getCurrentUserOrg() {
        OrgUserDetailParam param = new OrgUserDetailParam();
        param.setUserId(getCurrentUserId());
        param.setOid(getCurrentOid());
        return getOrgUserDetail(param);
    }

    /**
     * 分页查询所有用户
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<UserCountModel>> list(UserCountSearchParam param, Pageable pageable) {
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        Page<UserAccount> page = userCountDao.page(pageable, param);
        List<UserCountAboutRoleModel> models = new ArrayList<>();
        List<UserAccount> list = page.getContent();
        if (ObjectUtils.isNotEmpty(list)) {
            String finalOid = oid;
            models = list.parallelStream().map(it -> {
                return toAboutRoleModel(it, finalOid);
            }).collect(Collectors.toUnmodifiableList());
        }
        Page<UserCountAboutRoleModel> page1 = new PageImpl<>(models, PageRequest.of(page.getNumber(), page.getSize(), page.getSort()), page.getTotalElements());
        return ResultContent.buildSuccess(page1);
    }

    /**
     * 查询用户列表
     *
     * @param userIds
     * @return
     */
    public List<UserAccount> getUserAccounts(List<String> userIds) {
        List<UserAccount> list = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(userIds)) {
            list = userCountDao.findByUserIdIn(userIds);
        }
        return list;
    }

    /**
     * 转换数据模型
     *
     * @param list
     * @return
     */
    public List<UserCountSimpleModel> toListSimpleModel(List<UserAccount> list) {
        if (ObjectUtils.isNotEmpty(list)) {
            return list.stream().map(this::toSimpleModel).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * 所有数据字段
     *
     * @param entity
     * @return
     */
    public UserCountModel toModel(UserAccount entity) {
        UserCountModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new UserCountModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

    public UserCountAboutRoleModel toAboutRoleModel(UserAccount entity, String oid) {
        UserCountAboutRoleModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new UserCountAboutRoleModel();
            BeanUtils.copyProperties(entity, model);
            // 角色
            if (StringUtils.isNotEmpty(oid)) {
                OrganizationUser organizationUser = organizationUserDao.findTopByUserIdAndOid(entity.getUserId(), oid);
                if (ObjectUtils.isNotEmpty(organizationUser)) {
                    model.setRoles(roleServiceImpl.toModels(organizationUser.getRoles()));
                    model.setRemark(organizationUser.getRemark());
                }
            }
        }
        return model;
    }

    /**
     * 用户的基本信息 （简介模型）
     *
     * @param entity
     * @return
     */
    public UserCountSimpleModel toSimpleModel(UserAccount entity) {
        UserCountSimpleModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new UserCountSimpleModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

    /**
     * 用户在机构的数据模型（用户信息、职位、部门、角色等）
     *
     * @param entity
     * @return
     */
    public OrganizationUserModel toOrgUserModel(OrganizationUser entity) {
        OrganizationUserModel model = new OrganizationUserModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);

            // 机构信息
            OrganizationMiniModel miniModel = organizationManagerService.toMiniModel(entity.getOrganization());
            model.setOrganization(miniModel);

            // 用户信息
            UserCountSimpleModel userCountModel = toSimpleModel(entity.getUser());
            model.setUser(userCountModel);

            // 职务 职位
            DictInfoSimpleModel position = dictInfoService.toSimpleModel(entity.getPosition());
            model.setPosition(position);

            // 角色信息
            if (ObjectUtils.isNotEmpty(entity.getRoles())) {
                List<RoleModel> roleModels = entity.getRoles().stream().map(roleServiceImpl::toModel).collect(Collectors.toList());
                model.setRoles(roleModels);
            }

            // 部门信息
            if (ObjectUtils.isNotEmpty(entity.getDepartment())) {
                DepartmentModel departmentModel = departmentService.toModel(entity.getDepartment());
                model.setDepartment(departmentModel);
                List<DepartmentModel> departmentModels = departmentService.getParents(entity.getDepartment().getId());
                model.setDepartments(departmentModels);
            }
        }
        return model;
    }
}
