package com.iamberry.rent.handlers.machine;

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

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iamberry.exception.ServiceException;
import com.iamberry.rent.face.machine.MachineService;
import com.iamberry.wechat.core.entity.rent.MachineInfo;
import com.iamberry.wechat.tools.NameUtils;

@RequestMapping("/message")
@Controller
public class AdminAcceptEquipmentMessageHandler {

	@Autowired
	private MachineService machineService;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AdminAcceptEquipmentMessageHandler.class);
	
    /**
     * 校验
     * @param request
     * @param response
     * @throws Exception
     * @author 献
     * @Time   2017年4月5日
     */
    @RequestMapping(value = "/acceptMessage", method = RequestMethod.GET)
	public void verify(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
    	String echostr  = request.getParameter("echostr");	//随即字符串
		response.getOutputStream().write(echostr.getBytes());
    }
    
	/**
	 * 接受设备消息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/acceptMessage", method = RequestMethod.POST)
	public void acceptMessage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		// 从request中读取数据
		ServletInputStream inputStream = request.getInputStream();
		StringBuilder bindingData = new StringBuilder();
		try {
			byte[] buffer = new byte[1024];    
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				bindingData.append(new String(buffer, 0, len));
			}
		} catch (Exception e) {
			LOGGER.error("'method':'{}', 'err':'{}'", "acceptMessage", e.getMessage());
		}
		
		// 格式化数据
		JSONObject  json = JSONObject.fromObject(bindingData.toString());
		LOGGER.error("{'method':{}, 'msg':{}}", "接收到的微信消息",json);
		if(json == null || "".equals(json.toString())) return;
		
		// 获取数据
		String device_id = json.get("device_id").toString();		//设备ID，第三方提供 
		String device_type = json.get("device_type").toString();	//设备类型，目前为“公众账号原始ID”
		String msg_type  = json.get("msg_type").toString();			//消息类型：取值为bind/unbind bind：绑定设备 unbind：解除绑定 
		String open_id  = json.get("open_id").toString();			//微信账号的OpenID 
		String pubNo = NameUtils.getConfig("pubNo");				//公众号原始id
		
		// 校验数据
		/*if(!pubNo.equals(device_type) || StringUtils.isEmpty(device_id) || StringUtils.isEmpty(open_id)){
			return;
		}*/
		
		// 消息类型
		if(msg_type.equals("unbind")){
			//取消绑定
			return;
		} else if (msg_type.equals("bind")) {
			// 绑定
			MachineInfo machineInfo = new MachineInfo();
			machineInfo.setMachineDeviceId(device_id);
			machineInfo.setMachineOpenid(open_id);
			try {
				if (machineService.initBefore(machineInfo) != 1) {
					machineService.bindMachineToOpenId(device_id, open_id);
				}
			} catch (ServiceException e) {
				e.printStackTrace();
				if(machineService.bindMachineToOpenId(device_id, open_id) == 0){
					LOGGER.error("{'method':{}, 'msg':{}}", "绑定用户和机器的关系失败",json);
				}
			}
		} else if (msg_type.equals("device_text")) {
			// 接受到设备消息
			String deviceMessage = new String(Base64Utils.decodeFromString(json.get("content").toString()));
			
			if (deviceMessage.startsWith("ok1")) {

				try {
					machineService.init(open_id, device_id);
				} catch (ServiceException e) {
					LOGGER.error("'method':'{}', 'err':'{}'", "acceptMessage", e.getMessage());
				}
			} else if (deviceMessage.startsWith("getData")) {
				// 获取到的机器信息
				if (!deviceMessage.startsWith("getData01")) {
					return;
				}
				String temp = deviceMessage.replace("getData01", "");
				String[] data = temp.split(" ");
				MachineInfo info = new MachineInfo();
				info.setMachineTDS(Integer.parseInt(data[0]));
				info.setMachineSurplusWater(Integer.parseInt(data[1]));
				info.setMachineConnectState(1);
				info.setMachineDeviceId(device_id);
				machineService.update(info);
			} else if (deviceMessage.startsWith("setDir")) {
				// 设置数据方向
				
			} else {
				// 机器故障码
				LOGGER.error("{'deviceId':'{}', 'errCode':'{}'}", device_id, deviceMessage);
			}
		} else {
			// 未知消息类型
			
		}
	}
}
