package com.dgtis.dorm.manager.wx.web;

import com.dgtis.dorm.manager.db.domain.AlumniUser;
import com.dgtis.dorm.manager.wx.dao.UserInfo;
import com.dgtis.dorm.manager.wx.dao.UserToken;
import com.dgtis.dorm.manager.wx.service.UserTokenManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dgtis.dorm.manager.db.service.UserService;
import com.dgtis.dorm.manager.db.util.JacksonUtil;
import com.dgtis.dorm.manager.db.util.PYIndexStrUtil;
import com.dgtis.dorm.manager.db.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/auth")
public class WxAuthController {
    private final Log logger = LogFactory.getLog(WxAuthController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private WxMaService wxService;
    /**
     * 微信登录
     */
    @RequestMapping("login_by_weixin")
    public Object loginByWeixin(@RequestBody String body, HttpServletRequest request) {
    	try {
    		String code = JacksonUtil.parseString(body, "code");
    		UserInfo userInfo = JacksonUtil.parseObject(body, "userInfo", UserInfo.class);
    		if(code == null || userInfo == null) {
    			return ResponseUtil.fail402();
    		}
    		String sessionKey = null;
    		String openId = null;
    		WxMaJscode2SessionResult resultData = this.wxService.getUserService().getSessionInfo(code);
			sessionKey = resultData.getSessionKey();
			openId = resultData.getOpenid();
    		if(sessionKey == null || openId == null){
    			return ResponseUtil.fail();
    		}
    		AlumniUser user = userService.queryByOid(openId);
    		if(user == null){
    			user = new AlumniUser();
    			user.setOpenId(openId);
    			user.setLoginId(null);
    			user.setPassword(null);
    			user.setEnUserName(null);
    			user.setUserName(userInfo.getNickName());
    			user.setlUsername(userInfo.getNickName());
    			user.setRoleType("游客");
    			user.setPhoto(userInfo.getAvatarUrl());
    			user.setGender(userInfo.getGender() == 1 ? "男" : "女");
    			user.setWorking(null);
    			user.setPosition(null);
    			user.setPlace(null);
    			user.setSign(null);
    			user.setEmail(null);
    			user.setPhone(null);
    			user.setHiddenGender(false);
    			user.setHiddenEmail(false);
    			user.setHiddenPosi(false);
    			user.setHiddenPlace(false);
    			user.setHiddenPhone(false);
    			user.setAuditStatus(0);
    			user.setMajor(null);
    			user.setReason(null);
    			user.setCreateDate(new Date());
    			user.setLastLoginTime(new Date());
    			user.setAuditDataTime(null);
				user.setAddress(null);
				user.setPostcode(null);
				user.setIsRealname("2");
				user.setIdentity(userInfo.getIdentity());
    			userService.addUser(user);
    		} else {
    			//名称不为null,设置首字母
    			String userName = user.getUserName();
    	    	if(StringUtils.isNoneBlank(userName)) {
    	    		String strFirst = userName.substring(0, 1).toUpperCase();
    	    		String pinyin = "";
    				if(PYIndexStrUtil.isChinese(strFirst)) {
    					pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
    				} else if(strFirst.matches("[a-zA-Z]+")) {
    					pinyin = strFirst.toUpperCase();
    				} else {
    					pinyin = strFirst;
    				}
    				user.setEnUserName(pinyin);
    	    	}
    			user.setPhoto(userInfo.getAvatarUrl());
    			user.setLastLoginTime(new Date());
    			user.setIdentity(userInfo.getIdentity());
    			userService.updateUser(user);
    		}


    		// token
    		UserToken userToken = UserTokenManager.generateToken(user.getId());
    		
    		Map<Object, Object> result = new HashMap<Object, Object>();
    		result.put("userId", user.getId());
    		result.put("token", userToken.getToken());
//    		result.put("userInfo", user);
    		return ResponseUtil.ok(result);
    	}  catch (Exception e) {
    		e.printStackTrace();
    		logger.error(e);
		}
		return ResponseUtil.fail();
    }
}
