package com.palmnest.webapp.controller.kafka;

import com.palmnest.application.core.util.BeanUtils;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.outer.KafkaOuterService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * @Author HIAPAD
 * @Description 超级前台--服务之窗 信息同步
 * @Date 2018/11/14 16:01
 **/
@Slf4j
@Controller
@RequestMapping("/kafka")
public class KafkaController {


	@Autowired
	private AppUserManager    appUserManager;
	@Autowired
	private KafkaOuterService kafkaOuterService;

	/**
	 * 新增修改用户
	 * 超级前台企业人员信息同步到服务之窗
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/user/addOrUpdateUser", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String addOrUpdateUser(HttpServletRequest request) {

		//获取到JSONObject
		String     message = this.getJSONParam(request);
		JSONObject ob      = JSONObject.fromObject(message);
		AppUser    appUser = (AppUser) JSONObject.toBean(ob, AppUser.class);
		appUser.setCreator("admin");
		//保存操作
		AppUser appUser2 = appUserManager.get(appUser.getId());
		if (appUser2 == null) {
			appUserManager.saveModel(appUser);
		} else {
			appUser.setCreateTime(appUser.getCreateTime() == null ? new Date() : appUser.getCreateTime());
			appUser.setModifyTime(appUser.getModifyTime() == null ? new Date() : appUser.getModifyTime());
			try {
				BeanUtils.copyProperties(appUser2, appUser);
				appUserManager.updateModel(appUser2);
			} catch (IllegalAccessException e) {
				log.warn("KafkaController addOrUpdateUser:" + e.getMessage(), e);
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				log.warn("KafkaController addOrUpdateUser:" + e.getMessage(), e);
				e.printStackTrace();
			}
		}

		// 服务之窗用户信息同步到商城
		kafkaOuterService.syncUser(appUser2);
		return "success";
	}

	public String getJSONParam(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			// 获取输入流
			BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

			// 写入数据到Stringbuilder
			String line = null;
			while ((line = streamReader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
