package com.microservices.wiki.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microservices.wiki.domain.sys.Token;
import com.microservices.wiki.domain.sys.User;
import com.microservices.wiki.domain.sys.UserExtension;
import com.microservices.wiki.domain.sys.UserVo;
import com.microservices.wiki.mapper.sys.UserMapper;
import com.microservices.wiki.refactoring.constant.Constants;
import com.microservices.wiki.refactoring.response.HttpClientResult;
import com.microservices.wiki.refactoring.utils.CookieUtil;
import com.microservices.wiki.refactoring.utils.FastJsonUtils;
import com.microservices.wiki.refactoring.utils.HttpClientUtils;
import com.microservices.wiki.service.sys.TokenService;
import com.microservices.wiki.service.sys.UserExtentionService;
import com.microservices.wiki.service.sys.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${military-server-static-path}")
    private String militaryServerStaticPath;

    @Value("${military-server-user-logo-path}")
    private String militaryServerUserLogoPath;

    @Value("${trustie_or_military_host}")
    private  String trustieOrMilitaryHost;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenService tokenService;


    @Autowired
    private UserExtentionService extentionService;

    @Override
    public UserVo getCurrentUser(HttpServletRequest request) {
        String key = CookieUtil.getToken(Constants.COOKIE_NAME, request);
        if (key == null) {
            key = request.getParameter("token");
        }
        if(key == null){
            return getVisitor();
        }
        logger.info("==token:{}", key);

        return this.getUserByToken(key);
    }

    public UserVo getUserByToken(String key) {
        Token token = tokenService.getToken(Constants.TOKEN_ACTION, key);
        if(token == null){
            return getVisitor();
        }
        User user = baseMapper.selectByPrimaryKey(token.getUserId());
        if(user != null){
            UserVo vo = getUserVo(user);
            vo.setToken(key);
            return vo;
        }
        return getVisitor();
    }

    @Override
    public User getUserByLogin(String login) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login", login);
        List<User> users = baseMapper.selectList(wrapper);
        return CollectionUtils.isEmpty(users)?null : users.get(0);
    }

    @Override
    public String getUserImages(String login) {
        User user = getUserByLogin(login);
        if(user == null){
            return "images/avatars/User/b";
        }
        UserExtension extension = extentionService.getUserExtensionByUserId(user.getId());
        String img = extension.getGender().intValue() == 0 ? "b" : "g";
        return "images/avatars/User/" + img;
    }

    private UserVo getUserVo(User user) {
        UserExtension extension = extentionService.getUserExtensionByUserId(user.getId());
        UserVo userVo = new UserVo();
        String name = user.getFirstname()+user.getLastname();
        userVo.setUsername(StringUtils.isEmpty(name)? user.getNickname() : name);
        userVo.setAdmin(user.getAdmin());
        userVo.setLogin(user.getLogin());
        userVo.setReal_name(StringUtils.isEmpty(name)? user.getNickname() : name);
        userVo.setUser_id(user.getId().toString());
        String img = extension == null || extension.getGender() == null || extension.getGender() == 0 ? "boy.jpg" : "girl.jpg";
        userVo.setImage_url("avatars/User/"+img);
        userVo.setImage_url(this.getRemoteUserLogoByUserLogin(user.getLogin()));
        userVo.setGiteaToken(user.getGiteaToken());
        return userVo;
    }

    private UserVo getVisitor(){
        UserVo user = new UserVo();
        user.setUsername("游客");
        user.setLogin("");
        return user;
    }

    public String getUserLogoByUserId(Integer userId) {
        UserExtension extension = extentionService.getUserExtensionByUserId(userId);
        String userLogo = militaryServerUserLogoPath + userId.toString();
        File file = new File(militaryServerStaticPath + userLogo);
        if (file.exists()) {
            return userLogo;
        }
        String img = extension.getGender() == null || extension.getGender() == 0 ? "boy.jpg" : "girl.jpg";
        return militaryServerUserLogoPath + img;
    }

    @Override
    public String getRemoteUserLogoByUserLogin(String login) {
        Map map = this.getRemoteUserInfoByLogin(login);
        return null == map ? "" : (null == map.get("image_url") ? "" : map.get("image_url").toString());
    }

    private Map getRemoteUserInfoByLogin(String login) {
        try {
            String url = MessageFormat.format("{0}/api/users/{1}.json", trustieOrMilitaryHost, login);
            HttpClientResult result = HttpClientUtils.doGet(url);
            Map map = FastJsonUtils.stringToCollect(result.getContent());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
