package com.palmnest.service.estateserve.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.OAuthConstants;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.NeigouOAuth2Details;
import com.palmnest.application.core.util.NeigouOAuthUtils;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.NeigouOrderDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.NeigouOrder;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.NeigouOrderManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.webapp.controller.wechat.NeigouController;

@Service("neigouOrderManager")
public class NeigouOrderManagerImpl extends GenericManagerImpl<NeigouOrder, Integer> implements NeigouOrderManager {

	private static Logger LOG = Logger.getLogger(NeigouOrderManagerImpl.class);

	public static final String CURRENTMESSAGEID = "currentmessageid";
	public static final String LAST_MESSAGE_ID  = "last_message_id";

	@Autowired
	private ReplayContentDao replayContentDao;
	@Autowired
	private WeChatApiManager weChatApiManager;
	@Autowired
	private AppUserManager   appuserManager;
	@Autowired
	private ScWxuserManager  scWxuserManager;
	@Autowired
	private NeigouOrderDao   neigouOrderDao;

	@Autowired
	public void setNeigouOrderDao(NeigouOrderDao neigouOrderDao) {
		this.neigouOrderDao = neigouOrderDao;
		this.dao = neigouOrderDao;
	}

	@Override
	public void doNeigouOrderNews() {


		LOG.info("NeigouOrderManagerImpl doNeigouOrderNews start =====");

		//Load the properties file
		//**************不同 环境需要修改参数 oauth2Client.properties**************
		Properties config = NeigouOAuthUtils.getClientConfigProps(OAuthConstants.CONFIG_FILE_PATH);

		//Generate the OAuthDetails bean from the config properties file
		NeigouOAuth2Details oauthDetails = NeigouOAuthUtils.createOAuthDetails(config);


		if (Constants.CacheNeigouOrderMap.size() == 0) {//为0 读数据库

			NeigouOrder neigouOrder = neigouOrderDao.get(1);
			Constants.CacheNeigouOrderMap.put(LAST_MESSAGE_ID, neigouOrder.getLast_message_id());

			LOG.info("NeigouOrderManagerImpl doNeigouOrderNews 读数据库 last_message_id =====" + neigouOrder.getLast_message_id());
		}

		//getLast_message_id 通过接口来取 因为数据库可能不是最新的
		/*String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);
		String return_last_message_id=getLastMessageId(oauthDetails,accessToken);
		if(StringUtils.isNotEmpty(return_last_message_id)){
			int return_message_Last_id=Integer.valueOf(return_last_message_id);
			if(Constants.CacheNeigouOrderMap.containsKey(LAST_MESSAGE_ID)){
				int message_Last_id=Constants.CacheNeigouOrderMap.get(LAST_MESSAGE_ID);
				if(return_message_Last_id>message_Last_id){
					Constants.CacheNeigouOrderMap.put(LAST_MESSAGE_ID, return_message_Last_id);
					//neigouOrderDao.updateLastMessageId(return_message_Last_id);//更新 last_message_id	
					NeigouOrder neigouOrderTemp= neigouOrderDao.get(1);
					neigouOrderTemp.setLast_message_id(return_message_Last_id);
					neigouOrderDao.saveNeigouOrder(neigouOrderTemp);
					//neigouOrderManager.updateModel(neigouOrder);
				}
			}else{
				Constants.CacheNeigouOrderMap.put(LAST_MESSAGE_ID, return_message_Last_id);
				//neigouOrderDao.updateLastMessageId(return_message_Last_id);//更新 last_message_id	
				NeigouOrder neigouOrderTemp= neigouOrderDao.get(1);
				neigouOrder.setLast_message_id(return_message_Last_id);
				neigouOrderDao.saveNeigouOrder(neigouOrderTemp);
				//neigouOrderManager.updateModel(neigouOrder);
			}

		}*/

		int localhost_last_message_id = Constants.CacheNeigouOrderMap.get(LAST_MESSAGE_ID);//本地last_message_id
		LOG.info("NeigouOrderManagerImpl doNeigouOrderNews 本地 localhost_last_message_id =====" + localhost_last_message_id);
		String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);
		String news_last_message_idStr = getLastMessageId(oauthDetails, accessToken);
		int news_last_message_id = Integer.valueOf(news_last_message_idStr);
		LOG.info("NeigouOrderManagerImpl doNeigouOrderNews   读取最新 news_last_message_id=====" + news_last_message_id);
		if (localhost_last_message_id < news_last_message_id) {
			//for(int currentId=currentmessageid;currentId<=last_message_id;currentId++){


			accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);
			getUserMessage(oauthDetails, accessToken, localhost_last_message_id);//从localhost_last_message_id+1 到news_last_message_id 到会拉取

			//}
		}

		LOG.info("NeigouOrderManagerImpl doNeigouOrderNews end =====");
	}

	//创建用户
	public String getLastMessageId(NeigouOAuth2Details oauthDetails, String accessToken) {

		LOG.info("NeigouOrderManagerImpl--getUserMessage start ======");


		LOG.info("NeigouOrderManagerImpl--getUserMessage 使用 accessToken======" + accessToken);

		//创建公司 url
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/sync");
		//http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/sync
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/Message/getUserMessage");
		HttpPost post = new HttpPost(oauthDetails.getGetUserMessage_url());

		LOG.info("NeigouOrderManagerImpl--oauthDetails.getGetUserMessage_url() ======" + oauthDetails.getGetUserMessage_url());

		post.setHeader("AUTHORIZATION", "Bearer " + accessToken);

		//String clientId = oauthDetails.getClientId();
		//String clientSecret = oauthDetails.getClientSecret();
		String scope = oauthDetails.getScope();

		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		JSONObject jsonData = new JSONObject();
		jsonData.put("last_message_id", 0);
		//jsonData.put("external_user_id", user_id);//必录
		//jsonData.put("external_company_id", company_id);//必录
		//jsonData.put("external_company_id", "cjqt_20171127");//必录
		//jsonData.put("mobile", user_id);
		//jsonData.put("mail", "2290989798@qq.com");			

		LOG.info("NeigouOrderManagerImpl--getLastMessageId BasicNameValuePair data======" + jsonData.toJSONString());

		parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));

		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String last_message_id = "";
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					throw new RuntimeException("Could not retrieve access token for client: " + oauthDetails.getClientId());
				}

			}

			////{"Result":"true","ErrorMsg":"operate success","Data":{"member_id":"39312"}}
			Map map = NeigouOAuthUtils.handleResponse(response);

			LOG.info("NeigouOrderManagerImpl--getLastMessageId map======" + map.toString());
			System.out.println("NeigouOrderManagerImpl--getLastMessageId map======" + map.toString());


			JSONObject dataJsonData = JSONObject.parseObject((String) map.get("Data"));
			if (dataJsonData.containsKey("last_message_id")) {
				last_message_id = dataJsonData.getString("last_message_id");

			}

		} catch (ClientProtocolException e) {
			NeigouOAuthUtils.doCatchException(e);
		} catch (IOException e) {
			NeigouOAuthUtils.doCatchException(e);
		}

		LOG.info("NeigouOrderManagerImpl--getUserMessage end ======");

		return last_message_id;
	}

	//创建用户
	public void getUserMessage(NeigouOAuth2Details oauthDetails, String accessToken, int currentmessageid) {

		LOG.info("NeigouOrderManagerImpl--getUserMessage start ======");


		LOG.info("NeigouOrderManagerImpl--getUserMessage 使用 accessToken======" + accessToken);


		LOG.info("NeigouOrderManagerImpl--getUserMessage 当前消息ID currentmessageid======" + currentmessageid);
		System.out.println("NeigouOrderManagerImpl--getUserMessage 当前消息ID currentmessageid======" + currentmessageid);

		//创建公司 url
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/sync");
		//http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/sync
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/Message/getUserMessage");

		HttpPost post = new HttpPost(oauthDetails.getGetUserMessage_url());
		post.setHeader("AUTHORIZATION", "Bearer " + accessToken);

		//String clientId = oauthDetails.getClientId();
		//String clientSecret = oauthDetails.getClientSecret();
		String scope = oauthDetails.getScope();

		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		JSONObject jsonData = new JSONObject();
		jsonData.put("last_message_id", currentmessageid);//会找大于当前id 的数据
		//jsonData.put("external_user_id", user_id);//必录
		//jsonData.put("external_company_id", company_id);//必录
		//jsonData.put("external_company_id", "cjqt_20171127");//必录
		//jsonData.put("mobile", user_id);
		//jsonData.put("mail", "2290989798@qq.com");			

		LOG.info("NeigouOrderManagerImpl--getUserMessage BasicNameValuePair data======" + jsonData.toJSONString());

		parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));

		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createUserResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					throw new RuntimeException("Could not retrieve access token for client: " + oauthDetails.getClientId());
				}

			}

			////{"Result":"true","ErrorMsg":"operate success","Data":{"member_id":"39312"}}
			Map map = NeigouOAuthUtils.handleResponse(response);
			createUserResult = (String) map.get("Result");

			LOG.info("NeigouOrderManagerImpl--getUserMessage createUserResult======" + createUserResult);
			LOG.info("NeigouOrderManagerImpl--getUserMessage map======" + map.toString());


			String title = "";
			String OrderSn = "";
			String OrderStatus = "";
			String remark = "";
			String orderDetailUrl = "";
			String external_user_id = "";
			String last_message_id = "";
			JSONObject dataJsonData = JSONObject.parseObject((String) map.get("Data"));
			if (dataJsonData.containsKey("last_message_id")) {
				last_message_id = dataJsonData.getString("last_message_id");

				if (StringUtils.isNotEmpty(last_message_id)) {
					int message_int_id = Integer.valueOf(last_message_id);
					if (message_int_id == 0) {
						return;
					} else {

						//在方法里调用
						Constants.CacheNeigouOrderMap.put(LAST_MESSAGE_ID, message_int_id);

						NeigouOrder neigouOrderTemp = neigouOrderDao.get(1);
						neigouOrderTemp.setLast_message_id(message_int_id);
						NeigouOrder no = neigouOrderDao.saveNeigouOrder(neigouOrderTemp);
						LOG.info("最新返回  no.getLast_message_id()===" + no.getLast_message_id());
					}

				}
			}

			if (dataJsonData.containsKey("message_list")) {
				//String message_listStr=(String) dataJsonData.get("message_list");
				//String message_listStr=((com.alibaba.fastjson.JSONArray)dataJsonData.get("message_list")).get(0).toString();

				JSONArray message_lists = ((com.alibaba.fastjson.JSONArray) dataJsonData.get("message_list"));

				for (int i = 0; i < message_lists.size(); i++) {

					JSONObject message_listJson = JSONObject.parseObject(message_lists.getString(i));


					LOG.info("message_lists 信息循环======" + i);

					if (message_listJson.containsKey("external_user_id")) {
						external_user_id = (String) message_listJson.get("external_user_id");
						LOG.info("external_user_id===" + external_user_id);
					}


					if (message_listJson.containsKey("content")) {
						title = (String) message_listJson.get("content");
						LOG.info("title===" + title);
					}

					if (message_listJson.containsKey("extra_params")) {
						JSONObject extra_paramsJson = JSONObject.parseObject(message_listJson.getString("extra_params"));
						if (extra_paramsJson.containsKey("OrderSn")) {//订单编号
							OrderSn = extra_paramsJson.getString("OrderSn");
							LOG.info("OrderSn===" + OrderSn);
						}
						if (extra_paramsJson.containsKey("OrderStatus")) {//订单状态
							OrderStatus = extra_paramsJson.getString("OrderStatus");
							LOG.info("OrderStatus===" + OrderStatus);
						}
						if (extra_paramsJson.containsKey("remark")) {//备注
							remark = extra_paramsJson.getString("remark");
							LOG.info("remark===" + remark);
						}
						if (extra_paramsJson.containsKey("url")) {//详情url
							orderDetailUrl = extra_paramsJson.getString("url");
							LOG.info("orderDetailUrl===" + orderDetailUrl);
						}
					}

					if (StringUtils.isEmpty(OrderSn)) {
						LOG.info("OrderSn 订单编号为空 不发消息===" + external_user_id);
						continue;
					}

					//external_user_id="18589021134";
					AppUser appUser = appuserManager.getAppUsersByPhone(external_user_id);//能查到用户才发
					if (appUser != null) {
						WxUser wxUser = scWxuserManager.getScWxuserByUserId(appUser.getId());
						LOG.info("external_user_id 查询到超级前台用户===" + external_user_id);
						System.out.println("external_user_id 查询到超级前台用户===" + external_user_id);

						List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType04, 0);
						if (!CollectionUtils.isEmpty(templateList)) {
							String templateId = (String) templateList.get(0).get("templateId");
							Map<String, String> paramMap = new HashMap<String, String>();

							//http://test.neigou.com/m/member-new_orderdetail-201712040719352243.html
							//http://test.neigou.com/m/product-376205.html

							paramMap.put("openId", wxUser.getOpenId());
							paramMap.put("developId", wxUser.getDevelopId());
							paramMap.put("templateId", templateId);
							paramMap.put("url", orderDetailUrl);
							//paramMap.put("url", "http://test.neigou.com/m/member-new_orderdetail-201712040719352243.html");
							paramMap.put("title", title + "\\n");
							paramMap.put("orderNum", OrderSn);
							paramMap.put("orderStateDesc", OrderStatus);
							paramMap.put("remark", remark);
							String msg03 = weChatApiManager.sendTemplateMsg03(paramMap);
							LOG.info("NeigouOrderManagerImpl--msg03 ======" + msg03);
						}
					} else {
						System.out.println("external_user_id 不是超级前台用户===" + external_user_id);
						LOG.info("external_user_id 不是超级前台用户===" + external_user_id);
					}
				}
			}

		} catch (ClientProtocolException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
		} catch (IOException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
		}

		LOG.info("NeigouOrderManagerImpl--getUserMessage end ======");
	}

}
