package com.palmnest.webapp.controller.weixiao;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.model.MethodLog;
import com.palmnest.model.User;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.MethodExecuteLogManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author hxt
 * @Description 腾讯微校card身份认证接口对接控制类
 * @Date 2018/12/25 10:10
 **/
@Slf4j
@Controller
@RequestMapping(value = "/weixiao")
public class WeiXiaoController {


	private String app_key       = PropertiesKit.readPropertiesValue("weixiao_app_key", "wechat.properties");
	private String app_secret    = PropertiesKit.readPropertiesValue("weixiao_app_secret", "wechat.properties");
	private String url_sync_info = PropertiesKit.readPropertiesValue("weixiao_url_sync_info", "wechat.properties");

	@Autowired
	private AppUserManager          appUserManager;
	@Autowired
	private MethodExecuteLogManager methodExecuteLogManager;

	/**
	 * 主动同步员工信息接口(同步信息到海纳后台)
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/syncEmployeeInfo")
	@ResponseBody
	public AppResultDto syncEmployeeInfo(HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("UserCache");

		String userIds = request.getParameter("userIds");
		String orgId   = request.getParameter("orgId");

		log.info("WeiXiaoController syncEmployeeInfo: ========>userIds:{},orgId{}", userIds, orgId);

		if (StringUtils.isBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目id为空");
		}

		if (StringUtils.isBlank(userIds)) {
			// 用户id为空时,全部同步
			// 全部同步的操作需要间隔15分钟
			MethodLog methodLog = methodExecuteLogManager.getMethodLog(Integer.parseInt(orgId), "syncEmployeeInfo", 15);
			if (methodLog != null) {
				// 还未到下次操作时间
				return AppResultUtil.createErrorDto("100", "15分钟内不可重复操作");
			}
		}


		if (StringUtils.isNotBlank(userIds) && userIds.endsWith(",")) {
			userIds = userIds.substring(0, userIds.length() - 1);
		}

		return appUserManager.syncEmployeeInfo(userIds, Integer.parseInt(orgId), user);
	}

	/**
	 * 微笑card身份认证绑定接口
	 *
	 * @param request 请求数据
	 * @return 返回认证结果
	 */
	@RequestMapping(value = "/auth", method = RequestMethod.POST)
	@ResponseBody
	public String auth(HttpServletRequest request) {

		JSONObject result = new JSONObject();

		JSONObject object = JSONObject.parseObject(receiveParam(request));

		String rawData = object.getString("raw_data");// 接收到的原始加密数据
		String appKey  = object.getString("app_key");// app_key

		log.info("接收的原始数据==========>raw_data:{},app_key:{}", rawData, appKey);

		if (StringUtils.isAnyBlank(rawData, appKey)) {
			result.put("code", -1);
			result.put("message", "参数为空");
			result.put("raw_data", "");
			result.put("app_key", appKey);
			return result.toJSONString();
		}

		try {
			// 解密
			long   lStart   = System.currentTimeMillis();
			String DeString = AES.Decrypt(rawData, appKey, app_secret.substring(0, 16));
			System.out.println("解密后的字串是：" + DeString);
			long lUseTime = System.currentTimeMillis() - lStart;
			System.out.println("解密耗时：" + lUseTime + "毫秒");
		} catch (Exception e) {
			log.error("参数解密异常=========>" + e.getMessage());
		}

		return "";
	}


	/**
	 * 处理接收到的请求参数
	 *
	 * @param request
	 * @return
	 */
	private String receiveParam(HttpServletRequest request) {

		BufferedReader streamReader = null;
		try {
			streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String        inputStr;
			while ((inputStr = streamReader.readLine()) != null) {
				responseStrBuilder.append(inputStr);
			}
			return responseStrBuilder.toString();
		} catch (IOException e) {
			log.error("接收参数异常=========>" + e.getMessage());
		} finally {
			try {
				if (streamReader != null) {
					streamReader.close();
				}
			} catch (Exception e) {
				log.error("流关闭异常=======>" + e.getMessage());
			}
		}

		return "";
	}
}
