package com.ruoyi.pda.service;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.pda.domain.APKVersion;
import com.ruoyi.pda.domain.ApiUser;
import com.ruoyi.pda.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;

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

    @Autowired
    LoginMapper mapper;

    public AjaxResult login(String name, String pass) {
        try {
            String salt = mapper.login_findSalt(name);
            SysUser user = mapper.login_getUser(name, getMD5Str(name + pass + salt));
            if (user != null) {
                // List<String> menuNameList=name.equals("admin")?
                //         mapper.selectMenuName():
                //         mapper.selectMenuNameByUserID(user);
                // if (menuNameList==null||menuNameList.isEmpty()){
                //     return "isEmpty";
                // }
                // return JSONObject.toJSONString(menuNameList);
                return AjaxResult.success(user);
            } else {
                return AjaxResult.error();
            }
        }catch (Exception e){
            return AjaxResult.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();
    }

    public ApiUser apiLogin(String name, String pass) {
        String salt = mapper.login_findSalt(name);
        return mapper.apiLogin(name, getMD5Str(name + pass + salt));
    }
}
