package cd.casic.framework.datapermission.convert;

import cd.casic.framework.commons.util.collection.CollectionUtils;
import cd.casic.framework.commons.util.collection.MapUtils;
import cd.casic.framework.commons.util.object.BeanUtils;
import cd.casic.framework.security.vo.dept.DeptSimpleRespVO;
import cd.casic.framework.security.vo.dept.post.PostSimpleRespVO;
import cd.casic.framework.datapermission.core.vo.role.RoleSimpleRespVO;
import cd.casic.framework.datapermission.service.auth.vo.profile.UserProfileRespVO;
import cd.casic.framework.datapermission.core.vo.UserRespVO;
import cd.casic.framework.datapermission.core.vo.UserSimpleRespVO;
import cd.casic.framework.commons.dataobject.dept.DeptDO;
import cd.casic.framework.commons.dataobject.dept.PostDO;
import cd.casic.framework.security.dal.permission.RoleDO;
import cd.casic.framework.security.dal.user.AdminUserDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserConvert {

    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);

    default List<UserRespVO> convertList(List<AdminUserDO> list, Map<Long, DeptDO> deptMap) {
        return CollectionUtils.convertList(list, user -> convert(user, deptMap.get(user.getDeptId())));
    }

    default UserRespVO convert(AdminUserDO user, DeptDO dept) {
        UserRespVO userVO = BeanUtils.toBean(user, UserRespVO.class);
        if (dept != null) {
            userVO.setDeptName(dept.getName());
        }
        return userVO;
    }

    default List<UserSimpleRespVO> convertSimpleList(List<AdminUserDO> list, Map<Long, DeptDO> deptMap) {
        return CollectionUtils.convertList(list, user -> {
            UserSimpleRespVO userVO = BeanUtils.toBean(user, UserSimpleRespVO.class);
            MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> userVO.setDeptName(dept.getName()));
            return userVO;
        });
    }

    default UserProfileRespVO convert(AdminUserDO user, List<RoleDO> userRoles,
                                      DeptDO dept, List<PostDO> posts) {
        UserProfileRespVO userVO = BeanUtils.toBean(user, UserProfileRespVO.class);
        userVO.setRoles(BeanUtils.toBean(userRoles, RoleSimpleRespVO.class));
        userVO.setDept(BeanUtils.toBean(dept, DeptSimpleRespVO.class));
        userVO.setPosts(BeanUtils.toBean(posts, PostSimpleRespVO.class));
        return userVO;
    }

}
