package com.cku.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cab.dao.CabThirdPartyMapper;
import com.cab.dao.UserMapper;
import com.cab.model.CabThirdParty;
import com.cab.model.User;
import com.cku.core.ExecResultModel;
import com.cku.core.ZAErrorCode;
import com.cku.dao.CkuDvUserMapper;
import com.cku.model.CkuDvUserModel;
import com.cku.util.Debugger;
import com.cku.util.MD5Generator;
import com.sys.dao.AreaMapper;
import com.sys.dao.CityMapper;
import com.sys.dao.ProvinceMapper;
import com.sys.service.TokenService;

@Service("ckuDvUserService")
public class CkuDvUserServiceImpl {

	@Autowired
	public CkuDvUserMapper ckuDvUserMapper;
	
	@Autowired
	public UserMapper userMapper;
	
	@Autowired
	public CabThirdPartyMapper cabThirdPartyMapper;
	
	@Autowired
	public ProvinceMapper provinceMapper;
	
	@Autowired
	public CityMapper cityMapper;
	
	@Autowired
	public AreaMapper areaMapper;
	
	/**
	 * 
	 * @Description：验证CKU会员登录
	 * @author: zhuoHeng
	 * @version: 2016年4月11日 上午9:31:53
	 * @throws Exception 
	 */
	public User ckuMemberLogin(String userName,String passWord,String ip,String flag,String dynamic) throws Exception{
		
		
		//查询CKU用户信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.ckuMemberLogin(userName);
		Debugger.doAssert(ckuDvUserModel != null, ZAErrorCode.ZA_ERC_KEY_NOT_FOUND, "账户名或密码错误");
		String md5 = MD5Generator.generate(ckuDvUserModel.getPassWord() + dynamic);
		User user = new User();
		//验证CKU用户密码
		Debugger.doAssert(md5.equals(passWord), ZAErrorCode.ZA_ERC_KEY_NOT_FOUND, "账户名或密码错误");
		if(md5.equals(passWord)){
			//是否为绑定验证（绑定CKU会员账号只在验证账号密码通过后返回CKU会员用户id）
			if(!"flag".equals(flag)){
				CabThirdParty obj = cabThirdPartyMapper.selectByPrimaryKey(ckuDvUserModel.getUserId());
				//若不存在CKU用户的对应数据，生成宠爱王国账户记录
				if("".equals(obj)||obj==null){
					user.setUsername("");
					user.setPassword("");
					user.setPhone("");
					user.setRegistIp(ip);
					user.setName(ckuDvUserModel.getUserName());
					//注册宠爱王国用户
					userMapper.insertSelective(user);
					CabThirdParty cabThirdParty = new CabThirdParty();
					cabThirdParty.setCabUserId(new Long(user.getId()).intValue());
					cabThirdParty.setCkuUserId(ckuDvUserModel.getUserId());
					//第三方表中添加cku会员关联
					cabThirdPartyMapper.insertSelective(cabThirdParty);
					user.setAge("0");
				}else{
					user = userMapper.selectByPrimaryId(obj.getCabUserId());
					String provinceName = "";
					if(user.getProvinceId()!=null){
						provinceName = provinceMapper.getProvince(user.getProvinceId().toString());
					}
					String cityName = "";
					if(user.getCityId()!=null){
						cityName = cityMapper.getCity(user.getCityId().toString());
					}
					String areaName = "";
					if(user.getAreaId()!=null){
						areaName = areaMapper.getArea(user.getAreaId().toString());
					}
					//控制省市区展示
					if(provinceName==null){
						user.setAddAess("");
					}else if(cityName==null){
						user.setAddAess(provinceName);
					}else if(areaName==null){
						user.setAddAess(provinceName+" "+cityName);
					}else {
						user.setAddAess(provinceName+" "+cityName+" "+areaName);
					}
					if(user.getPayPassWord()!=null &&"".equals(user.getPayPassWord())){
						user.setHasPpsw(true);
					}
				}
				String token = TokenService.instance().registerToken(user.getId());
				user.setToken(token);
				user.setPassword("");
				
				user.setUsername("");
				user.setThreeLoginType("cku");
				user.setId(null);
				user.setRegistIp("");
				user.setVipNum(ckuDvUserModel.getCkuId());
				user.setCodeTime(null);
				user.setRandomCode(null);
				user.setCardId(null);
				//返回是否存在支付密码
				if(user.getPayPassWord()!=null&&!"".equals(user.getPayPassWord())){
					user.setHasPpsw(true);
				}
				user.setPayPassWord(null);
			}else {
				user.setVipNum(ckuDvUserModel.getUserId());
			}
		}
		return user;
	}
	
	/**
	 * 
	 * @Description：MD5加密
	 * @author: 
	 * @version: 2016年4月11日 下午6:35:54
	 */
	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().substring(8, 24);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result;
	}
}
