package org.cs.mgr.user.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.cs.core.dao.IDicDao;
import org.cs.core.model.Dic;
import org.cs.core.service.impl.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import org.cs.util.DateUtil;
import org.cs.util.FastDFSClient;
import org.cs.util.IdcardValidator;
import org.cs.util.Md5;
import org.cs.util.Pager;
import org.cs.util.PropUtil;
import org.cs.util.StringUtil;
import org.cs.mgr.user.service.IMgmUserService;
import org.cs.mgr.user.service.IMsgService;
import org.cs.mgr.user.service.ISmsService;
import org.cs.qrcode.QRCode;
import org.cs.mgr.order.dao.IMgmOrderCommissionDao;
import org.cs.mgr.user.dao.IMgmInviteRecordDao;
import org.cs.mgr.user.dao.IMgmMessageDao;
import org.cs.mgr.user.dao.IMgmUserDao;
import org.cs.mgr.user.dao.ISmsDao;
import org.cs.mgr.user.model.MgmInviteRecord;
import org.cs.mgr.user.model.MgmMessage;
import org.cs.mgr.user.model.MgmUser;

/**
 * 
 * @ClassName: IMgmUserService
 * @Description:  
 * @author: sunny_shi
 * @date: 2018-06-09 13:28:55
 */
@Service("mgmUserService")
public class MgmUserService extends BaseService<MgmUser> implements IMgmUserService{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
	@Autowired
	private IMgmUserDao mgmUserDao;
	
	@Autowired
	public ISmsService smsService;  
	
	@Autowired
	private IMgmOrderCommissionDao mgmOrderCommissionDao;
	
	@Autowired
	private ISmsDao smsDao;
	
	@Autowired
	private IMgmMessageDao mgmMessageDao;
	
	@Autowired
	private  IMsgService msgService;
	
	@Autowired
	private IMgmInviteRecordDao mgmInviteRecord;
	@Autowired
	private IDicDao	 dicDao;
	@Override
	@Transactional(readOnly = true)
	public Pager getMgmUsers(Pager page){
		return this.mgmUserDao.queryMgmUsers(page);
	}
	
	@Override
	public Pager findMgmUser(Pager page, Map<String, String> map){
	
		return this.mgmUserDao.findMgmUser(page, map);
	}
	
	/**
	 * 自动生成
	 * @Title: delMgmUser 
	 * @Description: TODO
	 * @param id 主键id
	 * @return
	 * @return: boolean
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean delMgmUser(Integer id){
	
		MgmUser mgmUser = this.mgmUserDao.findById(id);
		if(mgmUser != null){
			mgmUser.setIsDelete(true);				
			this.mgmUserDao.update(mgmUser);
		}
		return true;
	}
	
	
	/**
	 * 自动生成
	 * @Title: addMgmUser 
	 * @Description: TODO
	 * @param mgmUser						对象
	 * @return
	 * @return: boolean
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean addMgmUser(MgmUser mgmUser){
	
		if(mgmUser != null){
			this.mgmUserDao.insert(mgmUser);
		}
		return true;
	}
	
	
	/**
	 *  自动生成
	 * @Title: updateMgmUser 
	 * @Description: TODO
	 * @param mgmUser						对象
	 * @return
	 * @return: boolean
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean updateMgmUser(MgmUser mgmUser){
	
		MgmUser mgmUser2 = this.mgmUserDao.findById(mgmUser.getId());
		if(mgmUser2 != null){
			mgmUser.mergeTo(mgmUser2);
			this.mgmUserDao.update(mgmUser2);
		}
		
		return true;
	}
	/**   
	 * @Title: login   
	 * @Description: 首页-用户登录-首次登录绑定  
	 * @param: @param admin
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#login(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject login(Map<String, String> admin) {
		String phone = admin.get("phone");
		try {
			String pwd =admin.get("pwd");
			String clientId = admin.get("clientId");
			Map<String, Object> user = mgmUserDao.loginNamePwd(phone);
			
			if(user == null){
				return  getJson(0, "", "账户信息不存在");
			}else if(!user.get("pwd").equals(Md5.getMd5(pwd.trim() + user.get("personnelcode")))){
				return  getJson(0, "", "密码错误");
			}else{
				
				// 更新设备ID
				if(StringUtil.isNotBlank(clientId) && !clientId.equals("0"))
				{
					MgmUser mgmUser=mgmUserDao.findById(Integer.parseInt(user.get("id").toString()));
					mgmUser.setClientId(clientId);
					mgmUserDao.update(mgmUser);
				}
				
				user.remove("pwd");
				//佣金总和
				BigDecimal sum=this.mgmOrderCommissionDao.getMgmOrderCommissionNum(Integer.parseInt(user.get("id").toString()));
				user.put("sum", sum);
				return getJson(1, user, "登录成功");
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getJson(0, null, "登录失败");
	}
	/**
	 * @Title: phoneBinding   
	 * @Description: 首次登录成功,绑定手机号并重置密码  
	 * @param: @param admin
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#phoneBinding(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject phoneBinding(Map<String, String> admin){
		String phone = admin.get("phone");  //手机号
		try {
			String pwd = admin.get("pwd");    //密码
			String code = admin.get("code");//验证码 借用用户代码属性赋值
			String userId = admin.get("userId");//验证码 借用用户代码属性赋值
			//String clientId = admin.get("clientId");//推送ID
			MgmUser user=mgmUserDao.findById(Integer.parseInt(userId));
			user.setCode("");//code清空 按正常业务处理
			
			//验证码校验
			JSONObject checkCode = smsService.checkCode(phone, 3, code);
			int checkRet = checkCode.getIntValue("ret");
			if (checkRet == 0)
				return checkCode;
			
			//已有该手机
			MgmUser appuser = mgmUserDao.getByPropertie(phone,"phone");
			if (null != appuser) {
				return getJson(0, "", "手机已绑定");
			}
			
			//密码加密
			if(StringUtil.isNotBlank(pwd)){
				String md5Pass = Md5.getMd5(pwd.trim() + user.getPersonnelcode().toString());
				user.setPwd(md5Pass);
			}else{
				return getJson(0, "", "密码错误");
			}
			
			/*if(StringUtil.isNotBlank(clientId)){
				user.setClientId(clientId);
			}*/
			
			user.setPhone(phone);
			user.setFirstLogin("1"); //设置首次登陆
			mgmUserDao.update(user);
			return getJson(1, user, "绑定成功");
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getJson(0, null, "绑定失败");
	}
	
	/**   
	 * @Title: chengePwd   
	 * @Description: 首页-密码修改   
	 * @param: @param admin
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#updatePwd(java.util.Map)
	 */
	@Override
	public JSONObject chengePwd(Map<String, String> admin) {
			String pwd="";
			String oldPwd="";
			String userId="";
			MgmUser mgmUser = mgmUserDao.findById(Integer.parseInt(userId));
			//旧密码相同则修改为新密码
			if(StringUtil.isNotBlank(oldPwd)&&Md5.getMd5(oldPwd.trim() + mgmUser.getPersonnelcode()).equals(mgmUser.getPwd())){
				mgmUser.setPwd(Md5.getMd5(pwd.trim() + mgmUser.getPersonnelcode()));
				mgmUserDao.update(mgmUser);
				return getJson(1, "", "密码修改成功");
			}else{
				return getJson(0, "", "原密码错误，请重新输入");
			}
	}
	
	/**
	 * 
	 * @Title: forgetPwd   
	 * @Description: 忘记密码   
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#forgetPwd(java.util.Map)
	 */
	@Override
	@Transactional(readOnly = false)
	public JSONObject forgetPwd(Map<String, String> map) {
		String phone = map.get("phone");    //手机号
		String code = map.get("code");      //验证码
		JSONObject json = new JSONObject();
		try {
			String userPasswd =map.get("pwd").toString(); //密码
			String oldPwd = map.get("oldPwd").toString();  //密码
			String type = map.get("type");      //1.原密码修改   2.验证码修改

			MgmUser user = mgmUserDao.getByPropertie(phone, "phone");
			if (user != null) {
				String salt = user.getPersonnelcode().toString();
				if ("1".equals(type)) {
					String oldMd5Pass = Md5.getMd5(oldPwd.trim() + salt);  
					if (oldMd5Pass != null && oldMd5Pass.equals(user.getPwd())) {
						String md5Pass = Md5.getMd5(userPasswd.trim() + salt);
						user.setPwd(md5Pass);
						user = update(user);
						json = getJson(1, "", "密码修改成功");
					} else {
						return getJson(0, "", "原密码错误");
					}
				} else if ("2".equals(type)) {
					JSONObject checkCode =  smsService.checkCode(phone, 2, code);
					int checkRet = checkCode.getIntValue("ret");
					if (checkRet == 0)
						return checkCode;
					if(StringUtil.isNotBlank(userPasswd)){
						String md5Pass = Md5.getMd5(userPasswd.trim() + salt);
						user.setPwd(md5Pass);
					}else{
						json = getJson(0, "", "密码修改失败");
					}
					user = update(user);
					json = getJson(1, "", "密码修改成功");
				}
			} else {
				json = getJson(0, "", "用户不存在");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}
	/**
	 * 
	 * @Title: register   
	 * @Description: 用户注册  
	 * @param: @param user
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#register(org.cs.mgr.user.model.MgmUser)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject register(MgmUser user){
		
		String phone = user.getPhone();  //手机号
		try {
			String pwd =user.getPwd();//密码
			String code = user.getCode();    //注册验证码 借用用户代码属性赋值
			String invitecode=null;          //邀请码
			MgmUser userCode=null; 
			//邀请码是否为空
			if(StringUtil.isNotBlank(user.getInvitecode())){
				invitecode=user.getInvitecode(); //邀请码
				userCode = mgmUserDao.getByPropertie(user.getInvitecode(),"invitecode");
				if(userCode==null){
					return getJson(0, "", "邀请码不存在");
				}
			}		
			
			user.setCode("");//code清空 按正常业务处理
			
			//验证码校验
			JSONObject checkCode = smsService.checkCode(phone, 1, code);
			int checkRet = checkCode.getIntValue("ret");
			if (checkRet == 0)
				return checkCode;
			
			MgmUser appuser = mgmUserDao.getByPropertie(user.getPhone(),"phone");
			//已有该手机
			if (null != appuser) {
				return getJson(0, "", "手机已注册");
			}
			if(StringUtil.isNotBlank(pwd)){
				user.setPwd(pwd);
			}else{
				return getJson(0, "", "密码错误");
			}
			user = initUser(user);
			MgmUser mgmUser=mgmUserDao.insert(user);
			
			if(userCode!=null){
				//增加邀请记录
				MgmInviteRecord mir=new MgmInviteRecord();
				mir.setInviteCode(invitecode);
				mir.setName(mgmUser.getName());
				mir.setPhone(mgmUser.getPhone());
				mir.setUserId(mgmUser.getId());
				mir.setInviteDate(new Date());
				mgmInviteRecord.insert(mir);
			}
			
			//推送系统消息
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("type", "0");
			msgService.sendMsg(user.getId(),"东旭通", "欢迎您注册东旭集团，您的注册账号是："+phone, user.getClientId(),param );
			
			return getJson(1, user, "注册成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getJson(0, null, "注册失败");
	}
	
	/**
	 * 
	 * @Title: register   
	 * @Description: 身份认证
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#register(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject register(Map<String, String> map){
		String userId=map.get("userId").trim();
		String name=map.get("name").trim();
		String idnumber=map.get("idnumber").trim();
		//身份证认证
		if(IdcardValidator.isValidatedAllIdcard(idnumber)){
			MgmUser user=mgmUserDao.findById(Integer.parseInt(userId));
			user.setIdnumber(idnumber);
			user.setName(name);
			//根据userId查询 邀请记录,修改邀请记录表
			MgmInviteRecord mir=mgmInviteRecord.getByRecordUserId(user.getId());
			if(mir!=null){
				mir.setName(name);
				mgmInviteRecord.update(mir);
			}
			mgmUserDao.update(user);
			return getJson(1, user, "身份认证成功");
		}
		return getJson(0, "", "身份认证失败");
	}
	/**
	 * 
	 * @Title: initUser   
	 * @Description: 初始化用户
	 * @param: @param user
	 * @param: @return      
	 * @return: MgmUser      
	 * @throws
	 */
	private MgmUser initUser(MgmUser user) {
		Date date = new Date();
		user.setType("1");
		user.setPersonnelcode(null);
		
		Dic dic = dicDao.findAndIncrease("app_user_code");
		String code = dic.getValue();
		user.setPersonnelcode("F"+code);
		user.setInvitecode("F"+code);
		user.setFirstLogin("0");
		System.out.println("---------------------------------"+user.getPwd().trim());
		System.out.println("---------------------------------"+user.getPwd().trim() + "F"+code);
		String md5Pass = Md5.getMd5(user.getPwd().trim() + "F"+code);
		user.setPwd(md5Pass);
		return user;
	}
	
	/**
	 * 
	 * @Title: getUserInfo   
	 * @Description: 根据Id获取数据
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#getUserInfo(java.util.Map)
	 */
	@Override
	public JSONObject getUserInfo(Map<String, String> map){
		MgmUser mgmUser=mgmUserDao.findById(Integer.parseInt(map.get("userId").toString()));
		if(mgmUser!=null){
			BigDecimal sum=this.mgmOrderCommissionDao.getMgmOrderCommissionNum(mgmUser.getId());
			mgmUser.setSum(sum);
			return getJson(1, mgmUser, "获取用户信息成功");	
		}
		return getJson(0, "", "获取用户信息失败");
	} 
	
	/**
	 * @Title: updateUserInfo   
	 * @Description: 修改个人信息
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#updateUserInfo(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject updateUserInfo(MgmUser mgmUser){
		String mail=mgmUser.getMail();
		String qq=mgmUser.getQq();
		String weixin=mgmUser.getWeixin();
		String address=mgmUser.getAddress();
		String province=mgmUser.getProvince();
		String city=mgmUser.getCity();
		String area=mgmUser.getArea();
	      
		MgmUser mgmUsers=mgmUserDao.findById(mgmUser.getId());
		if(StringUtil.isNotBlank(mail)){
			if(isEmail(mail)){
				mgmUsers.setMail(mail);
			}else{
				return getJson(0, "", "输入的邮箱格式不正确");	
			}
		}
		if(StringUtil.isNotBlank(qq)){
			if(isNumeric(qq)){
				mgmUsers.setQq(qq);
			}else{
				return getJson(0, "", "输入的qq号不正确");	
			}
		}
		if(StringUtil.isNotBlank(weixin)){
			mgmUsers.setWeixin(weixin);
		}
		if(StringUtil.isNotBlank(address)){
			mgmUsers.setAddress(address);
		}
		if(StringUtil.isNotBlank(province)){
			mgmUsers.setProvince(province);
		}
		if(StringUtil.isNotBlank(city)){
			mgmUsers.setCity(city);
		}
		if(StringUtil.isNotBlank(area)){
			mgmUsers.setArea(area);
		}
		mgmUserDao.update(mgmUsers);
		return getJson(1, mgmUser, "修改个人信息成功");	
	}
	/**
	 * 
	 * @Title: getUserQRCode   
	 * @Description: 我的二维码   
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#getUserQRCode(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public JSONObject getUserQRCode(HttpServletRequest request,Map<String, String> map){
		MgmUser mgmUser=mgmUserDao.findById(Integer.parseInt(map.get("userId").toString()));
		String imgeUrl=null;
		if(StringUtil.isNotBlank(mgmUser.getImgURL())){
			imgeUrl=PropUtil.getString("file_http")+mgmUser.getImgURL().toString();
		}else{
			
			String path= request.getServletContext().getRealPath("") ;
	   	    String fileName = "/wxQRCode/"+DateUtil.formatYeayMonth(new Date())+"/"+mgmUser.getInvitecode().toString()+".png";
	    	String filePath = QRCode.getQRCodeImgPath(path, fileName);
	    	QRCode qrCode = QRCode.NEW(PropUtil.getString("qrcode_img")+"/app/login/register.jsp?code=" + mgmUser.getInvitecode().toString()).toFile(filePath);
	    	  
	    	File file=qrCode.getQrcodeFile();
	    	String tmUrl=FastDFSClient.uploadFile(file,mgmUser.getInvitecode().toString()+".png");
			//上传资源服务器 后 删除文件
	    	file.delete();
	    	if(StringUtil.isNotBlank(tmUrl)) { 
				if(StringUtil.isBlank(imgeUrl)) {
					imgeUrl=PropUtil.getString("file_http")+tmUrl;
					mgmUser.setImgURL(tmUrl);
					mgmUserDao.update(mgmUser);
				} 
			}
		}
		
    	return getJson(1, imgeUrl, "获取二维码成功");
	}
	
	/**
	 * 
	 * @Title: getUserQRCode   
	 * @Description: 我的二维码   
	 * @param: @param map
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#getUserQRCode(java.util.Map)
	 */
	@Override
	@Transactional(readOnly=false)
	public String getUserQRCode(HttpServletRequest request,String userId){
		MgmUser mgmUser=mgmUserDao.findById(Integer.parseInt(userId));
		String imgeUrl=null;
		if(StringUtil.isNotBlank(mgmUser.getImgURL())){
			imgeUrl=PropUtil.getString("file_http")+mgmUser.getImgURL().toString();
		}else{
			String path= request.getServletContext().getRealPath("") ;
	   	    String fileName = "/wxQRCode/"+DateUtil.formatYeayMonth(new Date())+"/"+mgmUser.getInvitecode().toString()+".png";
	    	String filePath = QRCode.getQRCodeImgPath(path, fileName);
	    	QRCode qrCode = QRCode.NEW(PropUtil.getString("qrcode_img")+"/app/login/register.jsp?code=" + mgmUser.getInvitecode().toString()).toFile(filePath);
	    	
	    	File file=qrCode.getQrcodeFile();
	    	String tmUrl=FastDFSClient.uploadFile(file,mgmUser.getInvitecode().toString()+".png");
			//上传资源服务器 后 删除文件
	    	file.delete();
	    	if(StringUtil.isNotBlank(tmUrl)) {
				if(StringUtil.isBlank(imgeUrl)) {
					imgeUrl=PropUtil.getString("file_http")+tmUrl;
					mgmUser.setImgURL(tmUrl);
					mgmUserDao.update(mgmUser);
				} 
			}
		}
		
    	return imgeUrl;
	}
	
	/**
     * 利用正则表达式判断字符串是否是数字
     * @param str
     * @return
     */
    public boolean isNumeric(String str){
           Pattern pattern = Pattern.compile("[0-9]*");
           Matcher isNum = pattern.matcher(str);
           if( !isNum.matches() ){
               return false;
           }
           return true;
    }
    /**
     * 利用正则表达式判断字符串是否是邮箱
     * @param str
     * @return
     */
    public static boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }

	@Override
	public Pager getMgmUsersBySeach(Pager page, Map<String, String> map) {
		// TODO Auto-generated method stub
		return this.mgmUserDao.getMgmUsersBySeach(page, map);
	}

	/**   
	 * @Title: getByPropertie   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param code
	 * @param: @param string
	 * @param: @return         
	 * @see org.cs.mgr.user.service.IMgmUserService#getByPropertie(java.lang.String, java.lang.String)   
	 */  
	@Override
	public MgmUser getByPropertie(String code, String string) {
		// TODO Auto-generated method stub
		return mgmUserDao.getByPropertie(code, string);
	}

	@Override
	public Map<String, Object> getUserMap(String personnalcode) {
		Map<String, Object> user = mgmUserDao.findByPersonnalcode(personnalcode);
		if(user != null){
			user.remove("pwd");
			//佣金总和
			BigDecimal sum=this.mgmOrderCommissionDao.getMgmOrderCommissionNum(Integer.parseInt(user.get("id").toString()));
			user.put("sum", sum);
		}
		return user;
	}

	public JSONObject checkUser(String phone){
		Map<String, Object> user = mgmUserDao.loginNamePwd(phone);
		if(user != null){
			//佣金总和
			BigDecimal sum=this.mgmOrderCommissionDao.getMgmOrderCommissionNum(Integer.parseInt(user.get("id").toString()));
			user.put("sum", sum);
			return getJson(1, user, "查询成功");
		}
		return getJson(0, null, "查询失败，用户不存在");
	}
	@Override
	public Pager getMgmUsersBySeachTj(Pager page, Map<String, String> map) {
		// TODO Auto-generated method stub
		return mgmUserDao.getMgmUsersBySeachTj(page, map);
	}

	@Override
	public Map<String, Object> getUserByCode(String code) {
		// TODO Auto-generated method stub
		Map<String, Object> user = mgmUserDao.loginNamePwd(code);
		return user;
	}
}
