package com.ruoyi.api.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.domain.APKVersion;
import com.ruoyi.api.domain.ApiUser;
import com.ruoyi.api.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by wangh on 2021/4/26-9:27。
 */
@Service
public class LoginService {

    @Autowired
    LoginMapper mapper;

    public String login(String name, String pass) {
        try {
            String salt = mapper.login_findSalt(name);
            Integer userID = mapper.login_getUser(name, getMD5Str(name + pass + salt));
            if (userID != null) {
                List<String> menuNameList=name.equals("admin")?
                        mapper.selectMenuName():
                        mapper.selectMenuNameByUserID(userID);
                if (menuNameList==null||menuNameList.isEmpty()){
                    return "isEmpty";
                }
                return JSONObject.toJSONString(menuNameList);
            } else {
                return "Error";
            }
        }catch (Exception e){
            return "Error";
        }

    }

    private static String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {


                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {


                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }

        return md5StrBuff.toString();
    }

    public APKVersion getVersion() {
        return mapper.getVersion();
    }


}
