package org.matrix.remote.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.matrix.local.entity.Project;
import org.matrix.local.entity.User;
import org.matrix.local.entity.UserProject;
import org.matrix.local.mapper.KsUserMapper;
import org.matrix.remote.entity.ZtProject;
import org.matrix.remote.entity.ZtUser;
import org.matrix.remote.entity.ZtUserView;
import org.matrix.remote.mapper.ZtProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.util.Objects.nonNull;

/**
 * 数据类型转换器
 */
@Service
public class TransHelper {

    @Autowired
    private ZtProjectMapper ztProjectMapper;
    @Autowired
    private KsUserMapper ksUserMapper;

    public User user(ZtUser ztUser) {
        return new User(Long.valueOf(ztUser.getId()), ztUser.getRealname(), ztUser.getAccount(), ztUser.getPassword());
    }

    public Project project(ZtProject ztProject) {
        return new Project(Long.valueOf(ztProject.getId()), ztProject.getName());
    }

    List<UserProject> userProjects(ZtUserView ztUserView) {
        User user = ksUserMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, ztUserView.getAccount()));
        if (nonNull(user)) {
            Long userId = user.getId();
            return toList(ztUserView.getProjects()).stream()
                    .map(Integer::parseInt)
                    .map(id -> ztProjectMapper.selectById(id))
                    .filter(ztProject -> Objects.equals("0", ztProject.getDeleted()))
                    .map(this::findProjectId)
                    .map(projectId -> new UserProject(null, userId, projectId))
                    .collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    //private---------------------------------------------------------------------------

    private Long findProjectId(ZtProject ztProject) {
        if (nonNull(ztProject.getProject()) && ztProject.getProject() > 0) {
            return Long.valueOf(ztProject.getProject());
        } else {
            return Long.valueOf(ztProject.getId());
        }
    }

    private List<String> toList(String content) {
        List<String> result = Arrays.stream(content.split(",")).collect(Collectors.toList());
        result.remove(0);
        return result;
    }

}
