package org.fouram.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.fouram.constants.WebConstants;
import org.fouram.core.base.controller.BaseController;
import org.fouram.core.plugin.weixin.cp.core.WXCpMailList;
import org.fouram.core.util.AppUtil;
import org.fouram.core.util.AppUtil.ResultConstant;
import org.fouram.core.util.ConfConfig;
import org.fouram.core.util.LoggerUtil;
import org.fouram.entity.SapOrg;
import org.fouram.service.SapOrgService;
import org.fouram.service.SapUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;

@Controller
@RequestMapping(value = "/API")
public class ApiController extends BaseController {

	@Autowired
	private SapOrgService sapOrgService;
	@Autowired
	private SapUserService sapUserService;
	@Autowired
	private static final String TOKEN = "UserId";

	/**
	 * 获取授权url
	 *
	 * @return
	 */
	@RequestMapping(value = "/getAuthUrl", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object getAuthUrl(String url) {
		try {
			String redirectUri = ConfConfig.getConfigString("wxCp.redirectUri") + "/API/wxCpLogin";
			String authUri = WXCpMailList.oauth2Service.buildAuthorizationUrl(redirectUri, url);
			System.out.println(authUri);
			return AppUtil.success(authUri, null);
		} catch (Exception e) {
			LoggerUtil.error(e);
			return AppUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	@RequestMapping(value = "/wxCpLogin", produces = "application/json;charset=utf-8")
	@ResponseBody
	public void wxCpLogin(String code, String state, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		WxCpOauth2UserInfo userInfo = WXCpMailList.oauth2Service.getUserInfo(code);
		String userId = ConfConfig.getConfigString("wxCp.mailList.userId");
		List<String> userIdList = Arrays.asList(userId.split(","));
		if (!userIdList.contains(userInfo.getUserId())) {
			response.getWriter().println("无权限访问！");
		} else {
			HttpSession httpSession = request.getSession();
			httpSession.setAttribute(TOKEN, userInfo.getUserId());
			response.sendRedirect(state);
		}
	}

	/**
	 * 根据部门id查询下级部门和用户
	 *
	 * @return
	 */
	@RequestMapping(value = "/getChildDepartAndUserListByDepartId", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object getChildDepartAndUserListByDepartId(HttpServletRequest request) {
		if (!isLogin(request)) {
			return AppUtil.error(ResultConstant.NO_TOKEN, ResultConstant.TOKEN_ERR_MSG);
		}
		try {
			String departId = getPageData().getString("departId");
			SapOrg sapOrg = null;
			if (StringUtils.isBlank(departId) || WebConstants.TOP_DEPART.toString().equals(departId)) {
				departId = WebConstants.TOP_DEPART.toString();
				sapOrg = SapOrg.builder().id(WebConstants.TOP_DEPART.toString()).sapName(WebConstants.TOP_DEPART_NAME)
						.build();
			} else {
				sapOrg = sapOrgService.selectById(departId);
			}
			Map<String, Object> result = Maps.newHashMap();
			result.put("departInfo", sapOrg);
			result.put("departList", sapOrgService.selectListByParentId(departId));
			result.put("userList", sapUserService.selectListByDepartIdAndLevel(departId));
			return AppUtil.success(result, null);
		} catch (Exception e) {
			LoggerUtil.error(e);
			return AppUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	/**
	 * 根据输入查询内容查询对应部门和用户
	 *
	 * @return
	 */
	@RequestMapping(value = "/getDepartAndUserListByName", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object getDepartAndUserListByName(HttpServletRequest request) {
		if (!isLogin(request)) {
			return AppUtil.error(ResultConstant.NO_TOKEN, ResultConstant.TOKEN_ERR_MSG);
		}
		try {
			String name = getPageData().getString("name");
			Map<String, Object> result = Maps.newHashMap();
			result.put("departList", sapOrgService.selectListByName(name));
			result.put("userList", sapUserService.selectListByName(name));
			return AppUtil.success(result, null);
		} catch (Exception e) {
			LoggerUtil.error(e);
			return AppUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	/**
	 * 根据id查询用户信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/getUserInfoByUserId", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object getUserInfoById(HttpServletRequest request) {
		if (!isLogin(request)) {
			return AppUtil.error(ResultConstant.NO_TOKEN, ResultConstant.TOKEN_ERR_MSG);
		}
		try {
			String userId = getPageData().getString("userId");
			return AppUtil.success(sapUserService.getDetailById(userId), null);
		} catch (Exception e) {
			LoggerUtil.error(e);
			return AppUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	/**
	 * 判断是否经过授权
	 *
	 * @param request
	 * @return
	 */
	public boolean isLogin(HttpServletRequest request) {
//		HttpSession httpSession = request.getSession();
//		if (null == httpSession.getAttribute(TOKEN)) {
//			return false;
//		}
		return true;
	}

}
