package com.palmnest.service.estateserve.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.PushMessageHelper;
import com.palmnest.application.dto.input.WatermentInputDto;
import com.palmnest.application.dto.output.WatermenterDto;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.estateserve.EnterpriseDao;
import com.palmnest.dao.estateserve.FloorInfoDao;
import com.palmnest.dao.estateserve.RoomInfoDao;
import com.palmnest.dao.estateserve.VirtUserDao;
import com.palmnest.dao.estateserve.WatermeterDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.EnterpriseInfo;
import com.palmnest.model.FloorInfo;
import com.palmnest.model.RoomInfo;
import com.palmnest.model.User;
import com.palmnest.model.VirtUserInfo;
import com.palmnest.model.WatermeterInfo;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.EnterpriseManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.WatermeterManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatApiManager;

@Service("watermeterManager")
public class WatermeterManagerImpl extends GenericManagerImpl<WatermeterInfo, Integer> implements WatermeterManager {

	private WatermeterDao watermeterDao;

	@Autowired
	public void setWatermeterDao(WatermeterDao watermeterDao) {
		this.watermeterDao = watermeterDao;
		this.dao = watermeterDao;
	}

	@Autowired
	private EnterpriseManager enterpriseManager;
	@Autowired
	private EnterpriseDao     enterpriseDao;
	@Autowired
	private RoomInfoDao       roomInfoDao;
	@Autowired
	private FloorInfoDao      floorInfoDao;
	@Autowired
	private WeChatApiManager  weChatApiManager;
	@Autowired
	private ScWxuserManager   scWxuserManager;
	@Autowired
	private ReplayContentDao  replayContentDao;
	@Autowired
	private VirtUserDao       virtUserDao;
	@Autowired
	private UserDao           userDao;

	public static String virInfoTableTempleteId = PropertiesKit.readPropertiesValue("virInfoTableTempleteId", "wechat.properties");

	/**
	 * 根据来源ID及企业状态类型(1企业入驻2企业迁出)查询相对应的电表信息
	 * 如果要查询该企业入驻获企业迁出单的水电表信息就无需传floorId,roomId,
	 * 如果要查单个楼层或者单个房间的水电表信息就需要加上该参数
	 */
	@Override
	public List<WatermenterDto> getWatermeterList(int sourseId, int enterType,
												  String floorId, String roomId) throws Exception {

		List<WatermeterInfo> list = watermeterDao.getWatermeterList(sourseId, enterType, floorId, roomId);

		List<WatermenterDto> wateDtoList = new ArrayList<WatermenterDto>();
		FileUploadUtils fileUploadUtils = new FileUploadUtils();

//		fileUploadUtils.init();
		for (int i = 0; i < list.size(); i++) {
			WatermeterInfo wInfo = list.get(i);
			String wateImage = "";
			String wateUrl = "";
			if (StringUtils.isNotEmpty(wInfo.getWateImageUrl())) {
				wateImage = fileUploadUtils.fullVisitPath(wInfo.getWateImageUrl());
				wateUrl = wInfo.getWateImageUrl();
			}
			String mateImage = "";
			String mateUrl = "";
			if (StringUtils.isNotEmpty(wInfo.getMaterImageUrl())) {
				mateImage = fileUploadUtils.fullVisitPath(wInfo.getMaterImageUrl());
				mateUrl = wInfo.getMaterImageUrl();
			}
			WatermenterDto wateDtoInfo = new WatermenterDto(wInfo.getId(), sourseId, enterType, wInfo.getWateReading() == null ? "" : wInfo.getWateReading(), wateImage == null ? "" : wateImage, String.valueOf(wInfo.getCreator())
					, wInfo.getFloorId(), wInfo.getRoomId(), wInfo.getMaterReading() == null ? "" : wInfo.getMaterReading(), mateImage == null ? "" : mateImage, mateUrl == null ? "" : mateUrl, wateUrl == null ? "" : wateUrl);
			wateDtoInfo.setCreateTime(DateHelper.formatDate(wInfo.getCreateTime(), DateHelper.DATE_STRING));
			String floorRoom = enterpriseManager.getFloorAndRoom(wInfo.getFloorId(), wInfo.getRoomId());
			wateDtoInfo.setFloorAndRoom(floorRoom);
			wateDtoList.add(wateDtoInfo);
		}

		if ((wateDtoList == null || wateDtoList.size() == 0) && enterType == 2) {
			EnterpriseInfo enterInfo = enterpriseDao.get(sourseId);
			String[] str = enterInfo.getRoomIds().split(";");
			for (int i = 0; i < str.length; i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				RoomInfo roomInfo = roomInfoDao.get(Integer.parseInt(str[i]));
				FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
				WatermenterDto wateDtoInfo = new WatermenterDto(sourseId, enterType, "", "", "", floorInfo.getId(), roomInfo.getId(), "", "");
				String floorRoom = enterpriseManager.getFloorAndRoom(floorInfo.getId(), roomInfo.getId());
				wateDtoInfo.setFloorAndRoom(floorRoom);
				wateDtoList.add(wateDtoInfo);
			}
		}
		return wateDtoList;
	}

	@Override
	@Transactional
	public String saveWaterInfo(List<WatermenterDto> list, int enterId, int userId) throws Exception {
//		List<WatermenterDto> list=dto.getWateDtoList();
//		int enterId=dto.getEnterId();
//		EnterpriseInfo enterInfo=enterpriseDao.get(enterId);
		watermeterDao.removeWaterList(enterId, 1);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				WatermeterInfo wateInfo = new WatermeterInfo();
				WatermenterDto wateDto = list.get(i);
				wateInfo.setCreator(userId);
				wateInfo.setCreateTime(new Date());
				wateInfo.setEnterType(wateDto.getEnterType());//来源单据类型
				wateInfo.setFloorId(wateDto.getFloorId());
				wateInfo.setWateImageUrl(wateDto.getWateImageUrl());
				wateInfo.setWateReading(wateDto.getWateReading());
				wateInfo.setMaterImageUrl(wateDto.getMaterImageUrl());
				wateInfo.setMaterReading(wateDto.getMaterReading());
				wateInfo.setRoomId(wateDto.getRoomId());
				wateInfo.setIsEnabled("1");
				wateInfo.setSourseId(wateDto.getSourseId());
				watermeterDao.save(wateInfo);
			}
			if (enterId != 0) {
				EnterpriseInfo info = enterpriseDao.get(enterId);
				info.setStatus("5");
				enterpriseDao.updateObj(info);
			}
			return "200";
		}
		return "100";
	}

	@Override
	public List<WatermeterInfo> getWatermeterLists(int sourseId, int enterType,
												   String floorId, String roomId) throws Exception {
		List<WatermeterInfo> list = watermeterDao.getWatermeterList(sourseId, enterType, floorId, roomId);
		return list;
	}

	@Async
	public String sendWechat(String enterId, List<WatermenterDto> wateList)
			throws Exception {
//		List<WxtemplateMessageTypeModel> templateList=replayContentDao.getWxTemplateByTempId(0, "KlRZryc99rR8oHAlQ9e6gIrzMHSKOgLTyGNsF4K7KZ4");
		String templateId = virInfoTableTempleteId;
		String code = "fail";
		if (StringUtils.isEmpty(templateId)) {
			code = "模板为空";
			return code;
		}
		EnterpriseInfo enterInfo = new EnterpriseInfo();
		if (StringUtils.isNotEmpty(enterId)) {
			enterInfo = enterpriseDao.get(Integer.parseInt(enterId));
		}
		if (enterInfo != null) {
			if ("1".equals(enterInfo.getState())) {//企业入驻(企业入驻发起就是微信发起的，因此存储的id就是微信表的id)
				String userId = String.valueOf(enterInfo.getCreator());
				Map<String, String> paramMap = new HashMap<String, String>();
				boolean bool = scWxuserManager.exists(Integer.parseInt(userId));
				int wxUserId = Integer.parseInt(userId);
				if (bool) {
					WxUser wxUser = scWxuserManager.get(Integer.parseInt(userId));
					for (int i = 0; i < wateList.size(); i++) {
						WatermenterDto dto = wateList.get(i);
						String floorAndRoom = dto.getFloorAndRoom() == null ? "" : dto.getFloorAndRoom();
						String virName = enterInfo.getVirName() == null ? "" : enterInfo.getVirName();
						String reading = dto.getMaterReading();
						paramMap.put("developId", wxUser.getDevelopId());
						paramMap.put("openId", wxUser.getOpenId());
						paramMap.put("templateId", templateId);
						paramMap.put("url", "");
						paramMap.put("first", "您好！您收到电表信息一则，请审阅！");
						paramMap.put("keyword1", floorAndRoom);//房间
						paramMap.put("keyword2", virName);//企业名称
						paramMap.put("keyword3", DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING));//时间
						paramMap.put("remark", "您的电表读数为：" + reading + ",热忱地欢迎您的入驻，祝您生活愉快！生意兴隆！");
						weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, "", wxUserId, paramMap);
					}
				}
			} else if ("2".equals(enterInfo.getState())) {//企业迁出
				//根据企业id查出相应的负责人----要给两个负责人发送
				if (StringUtils.isNotEmpty(String.valueOf(enterInfo.getVirId()))) {
					List<VirtUserInfo> list = virtUserDao.getVirUserByVirId(enterInfo.getVirId());
					if (list != null && list.size() > 0) {
						for (int k = 0; k < list.size(); k++) {
							VirtUserInfo virUserInfo = list.get(k);
							int userId = virUserInfo.getUserId();//这个是tb_user表中的id
							WxUser wxUser = scWxuserManager.getScWxuserByUserId(userId);
							if (wxUser != null) {
								Map<String, String> paramMap = new HashMap<String, String>();
								for (int i = 0; i < wateList.size(); i++) {
									WatermenterDto dto = wateList.get(i);
									String floorAndRoom = dto.getFloorAndRoom() == null ? "" : dto.getFloorAndRoom();
									String virName = enterInfo.getVirName() == null ? "" : enterInfo.getVirName();
									String reading = dto.getMaterReading();
									paramMap.put("developId", wxUser.getDevelopId());
									paramMap.put("openId", wxUser.getOpenId());
									paramMap.put("templateId", templateId);
									paramMap.put("url", "");
									paramMap.put("first", "您好！您收到电表信息一则，请审阅！");
									paramMap.put("keyword1", floorAndRoom);//房间
									paramMap.put("keyword2", virName);//企业名称
									paramMap.put("keyword3", DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING));//时间
									//paramMap.put("reading",reading);//读数
									paramMap.put("remark", "您的电表读数为：" + reading + ",欢迎您能再次回家！");
									weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, "", userId, paramMap);
								}
							}
						}
					}
				}
			}
		}
		return code;
	}

	@Async
	public String sendAppMessage(String enterId)
			throws Exception {
		EnterpriseInfo entInfo = new EnterpriseInfo();
		if (StringUtils.isNotEmpty(enterId)) {
			entInfo = enterpriseDao.get(Integer.parseInt(enterId));
		}
		if (entInfo == null) {
			return "100";
		}

		String code = "";
		if ("1".equals(entInfo.getState())) {
			code = CodeConstants.ENTER_PUSH_CODE;
		} else if ("2".equals(entInfo.getState())) {
			code = CodeConstants.EMIG_PUSH_CODE;
		}
		String title = "水电表信息";
		String content = "企业名称为" + entInfo.getVirName() + "的企业已提交水电表信息！";
		List<User> userList = new ArrayList<User>();
		String userId = entInfo.getCustomerService();
		User user = new User();
		if (StringUtils.isNotEmpty(userId)) {
			boolean bool = userDao.exists(Long.parseLong(userId));
			if (bool) {
				user = userDao.get(Long.valueOf(userId));
				userList.add(user);
			}
		}
		if (userList != null && userList.size() > 0) {
			PushMessageHelper helper=new PushMessageHelper();
			helper.pushMessage(Long.parseLong(enterId), code, userList, title, content);
		}
		return "200";
	}

}
