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.constants.WebConstants.DelFlagEnum;
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.ExcelExportUtil;
import org.fouram.core.util.LoggerUtil;
import org.fouram.core.util.ResultUtil;
import org.fouram.entity.SapOrg;
import org.fouram.entity.SapUser;
import org.fouram.input.FindUsersDTO;
import org.fouram.service.SapCheckService;
import org.fouram.service.SapOrgService;
import org.fouram.service.SapUserService;
import org.fouram.service.WxDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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 WxDepartService wxDepartService;
	@Autowired
	private SapCheckService sapCheckService;
	@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)
						.level("1").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);
		}
	}

	/**
	 * 查询离职员工列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/getQuitUserList", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object getQuitUserList(HttpServletRequest request) {
		if (!isLogin(request)) {
			return AppUtil.error(ResultConstant.NO_TOKEN, ResultConstant.TOKEN_ERR_MSG);
		}
		try {
			return AppUtil.success(sapUserService.selectDeleteList(), null);
		} catch (Exception e) {
			LoggerUtil.error(e);
			return AppUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	/**
	 * 删除离职员工
	 *
	 * @return
	 */
	@RequestMapping(value = "/deleteQuitUserByUserId", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object deleteQuitUserByUserId(HttpServletRequest request) {
		if (!isLogin(request)) {
			return AppUtil.error(ResultConstant.NO_TOKEN, ResultConstant.TOKEN_ERR_MSG);
		}
		try {
			String userId = getPageData().getString("userId");
			if (StringUtils.isBlank(userId)) {
				return AppUtil.error("参数用户ID不可以为空");
			}
			SapUser sapUser = sapUserService.selectByUserId(userId);
			if (sapUser.getDelFlag().intValue() != DelFlagEnum.UNABLE.intValue()) {
				return AppUtil.error("该用户ID不是离职数据");
			}
			// 操作用户ID
			String oprUserId = request.getSession().getAttribute(TOKEN).toString();
			sapUserService.deleteQuitUserByUserId(userId, oprUserId);
			return AppUtil.success();
		} 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;
	}

	@RequestMapping(value = "/findDepartJSON", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object findDepartJSON(HttpServletRequest request) {
		try {
			return ResultUtil.success(wxDepartService.findDepartJSON(), "操作成功");
		} catch (Exception e) {
			LoggerUtil.error(e);
			return ResultUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	@RequestMapping(value = "/findUserReports", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object findUsers(HttpServletRequest request, @RequestBody FindUsersDTO dto) {
		try {
			if (dto.getPageNumber() == null) {
				return ResultUtil.error("参数pageNumber为空");
			}
			Object result = sapCheckService.findUserReportPage(dto.getStartDate(), dto.getEndDate(), dto.getDepartId(),
					dto.getName(), dto.getState(), dto.getPageSize(), dto.getPageNumber());
			return ResultUtil.success(result, "操作成功");
		} catch (Exception e) {
			LoggerUtil.error(e);
			return ResultUtil.error(ResultConstant.WEB_ERR_MSG);
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportUserReportExcel")
	public void exportUserReportExcel(HttpServletResponse response, @RequestBody FindUsersDTO dto) {
		try {
			Object object = sapCheckService.findUserReports(dto.getStartDate(), dto.getEndDate(), dto.getDepartId(),
					dto.getName(), dto.getState(), null, null);
			List<Map<String, Object>> dataList = (List<Map<String, Object>>) object;
			String haveFilePath = "/public/excel/userReport.xlsx";
			ExcelExportUtil.exportExcelStream(getRootPath() + haveFilePath, dataList, 1, response);
		} catch (Exception e) {
			LoggerUtil.error(e);
		}
	}
}
