package com.cku.service;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cku.core.ExecResultModel;
import com.cku.dao.CkuLoginUserMapper;
import com.cku.model.CkuLoginUser;

@Service("ckuLoginUserService")
public class CkuLoginUserServiceImpl {
	@Autowired
	public CkuLoginUserMapper ckuLoginUserMapper;
	
	public String login(HttpServletRequest request,String userName,String pwd){
		ExecResultModel<CkuLoginUser> resultModel = new ExecResultModel<CkuLoginUser>();
		if(userName == null || userName.equals("")){
			resultModel.setRc(1);
			resultModel.setMsg("用户手机号码不能为空");
		}else if(pwd == null || pwd.equals("")){
			resultModel.setRc(1);
			resultModel.setMsg("用户密码不能为空");
		}else{
			String pwdMd5 = madeMD5forPW(pwd).toLowerCase();
			CkuLoginUser ckuLoginUser = ckuLoginUserMapper.seachForNamePwd(userName,pwdMd5);
			if(ckuLoginUser==null){
				resultModel.setRc(1);
				resultModel.setMsg("用户不存在！");
			}
			if( (ckuLoginUser.getUserpassword()).equals(pwdMd5.toLowerCase()) ){
				resultModel.setRc(0);
				List<CkuLoginUser> list = new ArrayList<CkuLoginUser>();
				list.add(ckuLoginUser);
				resultModel.setItems(list);
				request.getSession().setAttribute("userName", ckuLoginUser.getUsername());
				request.getSession().setAttribute("userId", ckuLoginUser.getUserid());
				request.getSession().setAttribute("ckuId", ckuLoginUser.getCkuId());
				request.getSession().setAttribute("ckuNo", ckuLoginUser.getCkuUser().getMemberNum());
				resultModel.setMsg("登陆成功");
			}else{
				resultModel.setRc(1);
				resultModel.setMsg("密码有误");
				return resultModel.getToJson();
			}
		}
		return resultModel.getToJson();
	
	}
		private static String madeMD5forPW(String plainText) {
		  String result = null;
		  try {
		   MessageDigest md = MessageDigest.getInstance("MD5");
		   md.update(plainText.getBytes());
		   byte b[] = md.digest();
		   int i;
		   StringBuffer buf = new StringBuffer("");
		   for (int offset = 0; offset < b.length; offset++) {
		    i = b[offset];
		    if (i < 0)
		     i += 256;
		    if (i < 16)
		     buf.append("0");
		    buf.append(Integer.toHexString(i));
		   }
		   // result = buf.toString();  //md5 32bit
		   // result = buf.toString().substring(8, 24))); //md5 16bit
		   result = buf.toString().substring(8, 24);
		   //System.out.println("mdt 16bit: " + buf.toString().substring(8, 24));
		   //System.out.println("md5 32bit: " + buf.toString() );
		  } catch (NoSuchAlgorithmException e) {
		   e.printStackTrace();
		  }
		  return result;
		}
		
}
