package com.palmnest.service.estateserve.impl;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.dao.estateserve.AnnouncementDao;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.estateserve.Announcement;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.service.AsynchronousDataService;
import com.palmnest.service.Executable;
import com.palmnest.service.estateserve.AnnouncementManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatAccessManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 通知公告业务层信息接口实现
 *
 * @author yubing
 * @since 2017-1-19
 */
@Slf4j
@Service("announcementManager")
public class AnnouncementManagerImpl extends GenericManagerImpl<Announcement, Integer> implements AnnouncementManager {


	private AnnouncementDao     announcementDao;
	@Autowired
	private ReplayContentDao    replayContentDao;
	@Autowired
	private ScWxuserDao         scWxuserDao;
	@Autowired
	private WeChatApiManager    weChatApiManager;
	@Autowired
	private WeChatAccessManager weChatAccessManager;
	@Autowired
	private AppUserDao          appUserDao;

	private String webUrl = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");

	//线程异步处理数据Serveice
	@Autowired
	private AsynchronousDataService asynchronousWorkService;

	@Autowired
	public void setAnnouncementDao(AnnouncementDao announcementDao) {
		this.announcementDao = announcementDao;
		this.dao = announcementDao;
	}

	@Override
	public Page getAnnouncementByPage(int pageno, int pagesize, String wheresql) {
		return announcementDao.getAnnouncementByPage(pageno, pagesize, wheresql);
	}

	public Pagenation<Announcement> queryAnnouncement(int pageNo,
													  List<Criterion> filterList) {
		int                 pageSize  = 10;
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();
		orderList.add(Order.desc("createTime"));
		return this.announcementDao.queryPage(pageNo, pageSize, aliasMap, filterList, orderList, Announcement.class);
	}

	@Override
	public void assginMassnotification(final Announcement anno) {
		final List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(anno.getType(), 0);
		if (!CollectionUtils.isEmpty(templateList)) {
			asynchronousWorkService.store(new Executable() {
				@Override
				public Void execute() {
					//获取消息模板ID
					String              templateId = (String) templateList.get(0).get("templateId");
					Map<String, String> paramMap   = null;
					if (ElementConstant.TemplateType01.equals(anno.getType())) {
						paramMap = new HashMap<String, String>();
						paramMap.put("templateId", templateId);
						paramMap.put("title", anno.getTitle());
						paramMap.put("bgTime", anno.getBgTime());
						paramMap.put("introduction", anno.getIntroduction());
					} else if (ElementConstant.TemplateType05.equals(anno.getType())) {
						paramMap = new HashMap<String, String>();
						paramMap.put("templateId", templateId);
						paramMap.put("title", anno.getTitle());
						paramMap.put("bgTime", anno.getBgTime());
						paramMap.put("introduction", anno.getIntroduction());
						paramMap.put("address", anno.getAddress());
					}

					if (paramMap != null) {
						List<WxUser> wxUsers = scWxuserDao.getWxUserListByOrgId(anno.getOrganizationId());
						log.info("wxUsers'size:" + wxUsers.size());

						//这一段code的目的：判断AccessToken是否失效，如果失效，重新获取
						if (wxUsers != null && wxUsers.size() > 0) {
							try {
								String developId  = wxUsers.get(0).getDevelopId();
								String resutlJson = weChatApiManager.getMenuInfo(developId);
								log.info("resutlJson:" + resutlJson);
								Map<String, Object> resultMap = JSONObject.parseObject(resutlJson, Map.class);
								String              errcode   = resultMap.get("errcode").toString();
								if (StringUtils.isNotBlank(errcode) && "40001".equals(errcode)) {
									weChatAccessManager.getAccessToken(developId);
								}
							} catch (Exception e) {
								log.error("assginMassnotification validate accesstoken occur error." + LogExceptionStackUtil.LogExceptionStack(e));
							}
						}
						for (WxUser wxUser : wxUsers) {
							try {
								AppUser appuser = appUserDao.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
								String  userId  = "";
								if (appuser != null) {
									userId = appuser.getId() + "";
								}
								String url = "";
								if (StringUtils.isNotBlank(anno.getDetailUrl())) {
									url = anno.getDetailUrl();
								} else {
									url = webUrl + "/wechat/info/getDetail/" + ElementConstant.InformationTypeNotice + "&" + anno.getId() + "&" + userId + "&" + wxUser.getOpenId() + "&" + wxUser.getDevelopId();
								}
								paramMap.put("url", url);
								paramMap.put("openId", wxUser.getOpenId());
								paramMap.put("developId", wxUser.getDevelopId());

								if (ElementConstant.TemplateType01.equals(anno.getType())) {
									String result = weChatApiManager.sendTemplateMsg04(paramMap);
									log.info("assginMassnotification result:" + result);
								} else if (ElementConstant.TemplateType05.equals(anno.getType())) {
									paramMap.put("nickName", StringUtils.isNotBlank(wxUser.getNickName()) == true ? wxUser.getNickName() : "亲爱的粉丝");
									String result = weChatApiManager.sendTemplateMsg05(paramMap);
									log.info("assginMassnotification result:" + result);
								}
							} catch (Exception e) {
								log.info("assginMassnotification execute occur error." + LogExceptionStackUtil.LogExceptionStack(e));
							}
						}
					}
					return null;
				}
			});
		}
	}

	@Override
	public void assignTimerAnnouncement() {
		List<Announcement> annoList = announcementDao.queryTimerAnnouncementList();
		if (!CollectionUtils.isEmpty(annoList)) {
			for (Announcement announcement : annoList) {
				log.info("assignTimerAnnouncement begin.");
				assginMassnotification(announcement);
				announcement.setSendStatus("1");
				announcementDao.updateObj(announcement);
			}
		}
	}
}
