package com.palmnest.service.estateserve.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import com.palmnest.application.core.util.MD5;
import com.palmnest.dao.notice.MobileConfigDao;
import com.palmnest.model.notice.MobileConfigModel;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
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.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.HttpMesssageKit;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.RegularPattern;
import com.palmnest.application.dto.output.PushBillOutputDto;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.PushBillDao;
import com.palmnest.dao.estateserve.PushModelDao;
import com.palmnest.dao.estateserve.VirtUserDao;
import com.palmnest.dao.estateserve.VirtualArchDao;
import com.palmnest.dao.notice.EmailConfigDao;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.PushBill;
import com.palmnest.model.PushModel;
import com.palmnest.model.User;
import com.palmnest.model.VirtUserInfo;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.VirUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.EmailConfigModel;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.model.property.TbBuild;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.PushBillManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatApiManager;
import com.sun.mail.util.MailSSLSocketFactory;

@Service("pushBillManager")
public class PushBillManagerImpl extends GenericManagerImpl<PushBill, Integer> implements PushBillManager {

	private Logger LOG = Logger.getLogger(PushBillManagerImpl.class);

	private PushBillDao pushBillDao;

	@Autowired
	public void setPushBillDao(PushBillDao pushBillDao) {
		this.pushBillDao = pushBillDao;
		this.dao = pushBillDao;
	}


	@Autowired
	private PropertyDao        propertyDao;
	@Autowired
	private OrganizationDao    organizationDao;
	@Autowired
	private VirtualArchDao     virtualArchDao;
	@Autowired
	private AppUserDao         appUserDao;
	@Autowired
	private PushModelDao       pushModelDao;
	@Autowired
	private ReplayContentDao   replayContentDao;
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	@Autowired
	private VirtUserDao        virtUserDao;
	@Autowired
	private WeChatApiManager   weChatApiManager;
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private EmailConfigDao     emailConfigDao;
	@Autowired
	private MobileConfigDao    mobileConfigDao;

	private static String EMAIL_ADDRESS         = PropertiesKit.readPropertiesValue("email_address", "wechat.properties");
	private static String EMAIL_NAME            = PropertiesKit.readPropertiesValue("email_name", "wechat.properties");
	private static String EMAIL_PASSWORD        = PropertiesKit.readPropertiesValue("email_password", "wechat.properties");
	public static  String monthlyBillTempleteId = PropertiesKit.readPropertiesValue("monthlyBillTempleteId", "wechat.properties");


	@Override
	public List<Map<String, Object>> getPushBillList(Map map) {
		return null;
	}

	@Override
	public String addPushBill(PushBill push) {
		String retFlag = "success";
		try {
			PushBill model = pushBillDao.save(push);
			LOG.info("addPushBill:" + retFlag);
		} catch (Exception e) {
			retFlag = "error";
			LOG.info("addPushModel:" + retFlag + "------Exception:" + e.getMessage());
		}
		return retFlag;
	}

	/**
	 * 新增多条推送账单
	 */
	@Override
	public int savePushBill(List<PushBill> pushBillList)
			throws Exception {
		int count = 0;
		for (PushBill pushBill : pushBillList) {
			pushBillDao.save(pushBill);
			count++;
		}
		return count;
	}

	@Override
	public Map<String, Object> saveImportPushBillData(InputStream ins) throws Exception {

		Map<String, Object> retMap = new HashMap<String, Object>();
		List<PushBillOutputDto> list = new ArrayList<PushBillOutputDto>();
		int bugCount = 0;
		StringBuffer bugStr = new StringBuffer("");
		Sheet sheet = null;
		try {

			Workbook workbook = WorkbookFactory.create(ins);
			sheet = workbook.getSheet("PushBill");
		} catch (Exception e) {
			LOG.error(e.getMessage());
			bugStr.append("模板格式有问题，请下载最新的模板");
		}

		try {
			if (sheet == null) {
				bugStr.append("模板格式有问题，请下载最新的模板");
			} else {
				//具体实现业务
				int rows = sheet.getLastRowNum();
				//如果大于2000行数据
				if (rows > 20000) {
					bugStr.append("数据量太大，不能大于2w行");
				} else if (rows < 1) {
					bugStr.append("数据为空，请录入账单信息");
				} else {
					for (int i = 1; i <= rows; i++) {
						if (sheet.getRow(i) == null) {
							continue;
						}
//						if(sheet.getRow(i).getCell(0)==null){
//							bugStr.append("第"+i+"行第1列数据有问题，请检查，问题：楼宇信息必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
//						
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(0).getStringCellValue())){
//							bugStr.append("第"+i+"行第1列数据有问题，请检查，问题：楼宇信息必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}

//						//房间号
//						if(sheet.getRow(i).getCell(1)==null){
//							bugStr.append("第"+i+"行第2列数据有问题，请检查，问题：房间必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
//						
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(1).getStringCellValue())){
//							bugStr.append("第"+i+"行第2列数据有问题，请检查，问题：房间必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						String roomName=sheet.getRow(i).getCell(1).getStringCellValue();

						//企业编码
//						if(sheet.getRow(i).getCell(2)==null){
//							bugStr.append("第"+i+"行第3列数据有问题，请检查，问题：企业编码必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(2).getStringCellValue())){
//							bugStr.append("第"+i+"行第3列数据有问题，请检查，问题：企业编码必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}

//						String code=sheet.getRow(i).getCell(2).getStringCellValue();
//						List<VirtualArchitecture> virList=virtualArchDao.getVirByCode(code);
//						if(virList==null||virList.size()<=0){
//							bugStr.append("第"+i+"行第3列数据有问题，请检查，问题：企业编码不存在，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						//企业名称
//						if(sheet.getRow(i).getCell(3)==null){
//							bugStr.append("第"+i+"行第4列数据有问题，请检查，问题：企业名称必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(3).setCellType(Cell.CELL_TYPE_STRING);
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(3).getStringCellValue())){
//							bugStr.append("第"+i+"行第4列数据有问题，请检查，问题：企业名称必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						String virName=sheet.getRow(i).getCell(3).getStringCellValue();
						String buildName = "";
						if (sheet.getRow(i).getCell(0) != null) {
							sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
							buildName = sheet.getRow(i).getCell(0).getStringCellValue();
						}
						String roomName = "";
						if (sheet.getRow(i).getCell(1) != null) {
							sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
							roomName = sheet.getRow(i).getCell(1).getStringCellValue();
						}

						String code = "";
						if (sheet.getRow(i).getCell(2) != null) {
							sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);
							code = sheet.getRow(i).getCell(2).getStringCellValue();
						}
						String virName = "";
						if (sheet.getRow(i).getCell(3) != null) {
							sheet.getRow(i).getCell(3).setCellType(Cell.CELL_TYPE_STRING);
							virName = sheet.getRow(i).getCell(3).getStringCellValue();
						}

						//推送金额---Excel中获取
						if (sheet.getRow(i).getCell(4) == null) {
							bugStr.append("第" + i + "行第5列数据有问题，请检查，问题：账单金额输入有误<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(4).setCellType(Cell.CELL_TYPE_STRING);
						String amount = sheet.getRow(i).getCell(4).getStringCellValue();
						if (StringUtils.isEmpty(amount)) {
							amount = "0.00";
						}
						BigDecimal amt = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP);

						String userName = "";
						if (sheet.getRow(i).getCell(5) != null) {
							sheet.getRow(i).getCell(5).setCellType(Cell.CELL_TYPE_STRING);
							userName = sheet.getRow(i).getCell(5).getStringCellValue();
						}

						String mobile = "";
						if (sheet.getRow(i).getCell(6) != null) {
							sheet.getRow(i).getCell(6).setCellType(Cell.CELL_TYPE_STRING);
							mobile = sheet.getRow(i).getCell(6).getStringCellValue();
						}
						String email = "";
						if (sheet.getRow(i).getCell(7) != null) {
							sheet.getRow(i).getCell(7).setCellType(Cell.CELL_TYPE_STRING);
							email = sheet.getRow(i).getCell(7).getStringCellValue();
						}
//						//接收人
//						if(sheet.getRow(i).getCell(5)==null){
//							bugStr.append("第"+i+"行第6列数据有问题，请检查，问题：账单接收人姓名必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(5).setCellType(Cell.CELL_TYPE_STRING);
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(5).getStringCellValue())){
//							bugStr.append("第"+i+"行第6列数据有问题，请检查，问题：账单接收人姓名必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}

//						String userName=sheet.getRow(i).getCell(5).getStringCellValue();
						//接收手机
//						if(sheet.getRow(i).getCell(6)==null){
//							bugStr.append("第"+i+"行第7列数据有问题，请检查，问题：账单接收人手机号码必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(6).setCellType(Cell.CELL_TYPE_STRING);
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(6).getStringCellValue())){
//							bugStr.append("第"+i+"行第7列数据有问题，请检查，问题：账单接收人手机号码必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}

//						String mobile=sheet.getRow(i).getCell(6).getStringCellValue();
//						boolean bool=RegularPattern.isMobileNO(mobile);
//						if(StringUtils.isNotEmpty(mobile)&&!bool){
//							bugStr.append("第"+i+"行第7列数据有问题，请检查，问题：账单接收人手机号码有问题，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						//接收邮箱
//						if(sheet.getRow(i).getCell(7)==null){
//							bugStr.append("第"+i+"行第8列数据有问题，请检查，问题：账单接收人邮箱必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						sheet.getRow(i).getCell(7).setCellType(Cell.CELL_TYPE_STRING);
//						if(StringUtils.isBlank(sheet.getRow(i).getCell(7).getStringCellValue())){
//							bugStr.append("第"+i+"行第8列数据有问题，请检查，问题：账单接收人邮箱必填，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}
//						String email=sheet.getRow(i).getCell(7).getStringCellValue();
//						boolean bool1=RegularPattern.checkEmail(email);
//						if(StringUtils.isNotEmpty(email)&&!bool1){
//							bugStr.append("第"+i+"行第8列数据有问题，请检查，问题：账单接收人邮箱有问题，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}


//						VirtualArchitecture virInfo=virList.get(0);
//						if(virInfo==null){
//							bugStr.append("第"+i+"行第3列数据有问题，请检查，问题：企业信息不存在，请导出系统模板匹配录入<br/>");
//							bugCount++;
//							continue;
//						}

						PushBillOutputDto dto = new PushBillOutputDto();
						dto.setAmount(amt);
						dto.setEmail(email);
						dto.setMobile(mobile);
//						dto.setVirId(virInfo.getId().toString());
						dto.setUserName(userName);
						dto.setBuildName(buildName);
//						dto.setFloorNames(floo);
						dto.setRoomNames(roomName);
						dto.setVirName(virName);
						dto.setVirNumber(code);
						list.add(dto);
					}
				}
			}
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			return retMap;
		} catch (Exception e) {
			LOG.error(e.getMessage());
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			throw new Exception(e);
		}
	}

	/**
	 * excel数据内容转换成实体类
	 *
	 * @param data
	 * @return
	 */
	public List<PushBill> convert(List<String[]> data) {
		List<PushBill> bills = new ArrayList<PushBill>();
		for (String[] d : data) {

			PushBill bill = new PushBill();
//			bill.setBillType(billType);
		}
		return null;
	}

	@Override
	@Transactional
	public List<PushBill> getPushBillListByListObj(String orgId, String title, String remark, String monthDate, String beginTime, String endTime, int billType,
												   String pushUpDate, List<PushBillOutputDto> listObj, User user) throws Exception {

		String username = "";//短信账号用户名
		String password = "";//短信账号MD5加密密码
		if (StringUtils.isNotBlank(orgId)) {
			List<MobileConfigModel> list = mobileConfigDao.getMobileConfigList(orgId);
			if (null != list && list.size() > 0) {
				//获取当前项目配置的短信账号信息
				MobileConfigModel model = list.get(0);
				username = model.getMobileNum();
				//密码加密
				String md5temp = MD5.sign(model.getPassword(), "", "utf-8");
				password = MD5.sign(username + md5temp, "", "utf-8");
			}
		}

		List<PushBill> list = new ArrayList<PushBill>();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			for (int i = 0; i < listObj.size(); i++) {
				PushBillOutputDto dto = listObj.get(i);
				String content = "";
				String modelIds = "";
				PushModel pushM = pushModelDao.getPushModel(billType, 0, orgId);//短信
				PushModel pushE = pushModelDao.getPushModel(billType, 1, orgId);//邮箱
				if (pushM != null) {
					content = pushM.getPushContent();
					modelIds = modelIds + pushM.getId() + ";";
				}
				if (pushE != null) {
					content = pushE.getPushContent();
					modelIds = modelIds + pushE.getId() + ";";
				}
				String text = getContent(dto.getAmount().toString(), monthDate, beginTime + "至" + endTime, content);
				PushBill pushBill = new PushBill();
				pushBill.setOrgId(orgId);
				pushBill.setBillType(billType);
				pushBill.setBillUpDate(sf.parse(pushUpDate));
				pushBill.setCreateTime(new Date());
				pushBill.setSenderId(user.getId());
				pushBill.setPushUser1(dto.getUserName());
				pushBill.setUserTel1(dto.getMobile());
				pushBill.setUserEmail1(dto.getEmail());
				pushBill.setVirName(dto.getVirName());
				pushBill.setVirNumber(dto.getVirNumber());
				pushBill.setBuildName(dto.getBuildName());
//				pushBill.setVirtId(Long.parseLong(dto.getVirId()));
				pushBill.setRoomName(dto.getRoomNames());
				pushBill.setPushAmount(dto.getAmount());
				pushBill.setBeginTime(sf.parse(beginTime));
				pushBill.setEndTime(sf.parse(endTime));
				pushBill.setMonthDate(Integer.parseInt(monthDate));
				pushBill.setMessageData(text);
				pushBill.setEmailData(text);
//				String openId1="";
//				if(StringUtils.isNotBlank(dto.getMobile())){
//					AppUser user1=appUserDao.getAppUsersByPhone(dto.getMobile());
//					if(user1!=null){
//						WxUser wxUser=scWxuserManager.getScWxuserByUserId(user1.getId());
//						if(wxUser!=null){
//							openId1=wxUser.getOpenId().toString();
//							pushBill.setOpenId1(openId1);
//						}
//					}
//				}
				if (StringUtils.isNotBlank(dto.getUserName()) && StringUtils.isNotBlank(dto.getEmail())) {
					String result = sendEmail(orgId, billType, dto.getUserName(), dto.getEmail(), text);
					LOG.info("isEmail" + result);
					if ("success".equals(result)) {
						pushBill.setEmailStatus(3);//0为都没发送成功，1为user1发送成功，2为user2发送成功,3为都发送成功
					}
				}
				if (StringUtils.isNotBlank(dto.getMobile())) {
					String result = smsAuthCodeManager.smsSend(username, password, text, dto.getMobile());
					LOG.info("isMessage" + result);
					if (!"Fail".equals(result)) {
						pushBill.setMessageStatus(3);//0为都没发送成功，1为user1发送成功，2为user2发送成功,3为都发送成功
					}
				}
				pushBill.setPushModelId(modelIds);
				list.add(pushBill);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return list;
	}
	/**
	 * 发送邮件
	 * @param pushBill
	 * @param modelIds
	 * @param amt
	 * @param billType
	 * @param monthDate
	 * @param beginTime
	 * @param endTime
	 * @param pushMap
	 */
//	public void pushEmail(PushBill pushBill,String modelIds,BigDecimal amt,int billType,String monthDate,String beginTime,String endTime,Map<String,Object> pushMap){
//		try {
//			PushModel  pushModel=pushModelDao.getPushModel(billType, 1);
//			String content=pushModel.getPushContent();
//			modelIds=modelIds+pushModel.getId()+";";
//			pushBill.setIsEmail(1);
//			pushBill.setPushAmount(amt);
//			//调用发送邮件的方法
//			String user1Email=pushMap.get("userEmail1")==null?"":pushMap.get("userEmail1").toString();
//			String user1=pushMap.get("pushUser1")==null?"":pushMap.get("pushUser1").toString();
//			String text=getContent(amt.toString(),monthDate,beginTime+"至"+endTime,content);
//			pushBill.setEmailData(text);
//			if(StringUtils.isNotBlank(user1)&&StringUtils.isNotBlank(user1Email)){
//				String result=sendEmail(billType,user1,user1Email,text);
//				LOG.info("isEmail"+result);
//				if("success".equals(result)){
//					pushBill.setEmailStatus(3);//0为都没发送成功，1为user1发送成功，2为user2发送成功,3为都发送成功
//				}
//			}
//		} catch (Exception e) {
//			LOG.error(e.getMessage());
//			e.printStackTrace();
//		}
//	}

	/**
	 * 发送短信
	 *
	 * @param pushBill
	 * @param modelIds
	 * @param amt
	 * @param billType
	 * @param monthDate
	 * @param beginTime
	 * @param endTime
	 * @param pushMap
	 */
//	public void pushMessage(PushBill pushBill,String modelIds,BigDecimal amt,int billType,String monthDate,String beginTime,String endTime,Map<String,Object> pushMap){
//		try {
//			PushModel  pushModel=pushModelDao.getPushModel(billType, 0);
//			String content=pushModel.getPushContent();
//			String text = getContent(amt.toString(),monthDate,beginTime+"至"+endTime,content);
//			pushBill.setMessageData(text);
//			modelIds=modelIds+pushModel.getId()+";";
//			pushBill.setIsMessage(1);
//			pushBill.setPushAmount(amt);
//			//发送短信
//			String userTel=pushMap.get("userTel1")==null?"":pushMap.get("userTel1").toString();
//			if(StringUtils.isNotBlank(userTel)){
//				String result=smsAuthCodeManager.smsSend(userTel, text);
//				LOG.info("isMessage"+result);
//				if(!"Fail".equals(result)){
//					pushBill.setMessageStatus(3);//0为都没发送成功，1为user1发送成功，2为user2发送成功,3为都发送成功
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			LOG.error(e.getMessage());
//		}
//	}
	public String getContent(String amount, String monthDate, String date, String text) throws Exception {

		if (StringUtils.isNotEmpty(monthDate)) {
			text = text.replace("[keyword2]", monthDate);
		}
		if (StringUtils.isNotEmpty(amount)) {
			text = text.replace("[keyword1]", amount);
		}
		if (StringUtils.isNotEmpty(date)) {
			text = text.replace("[keyword3]", date);
		}


		return text;

	}

	/**
	 * 查询推送历史
	 */
	@Override
	public Page queryBillPushList(String proId, String beginTime, String endTime,
								  String billType, String orgId, String floorIds, String virName,
								  int pageNo, int pageSize) throws Exception {
		return pushBillDao.queryBillPushList(proId, beginTime, endTime, billType, orgId, floorIds, virName, pageNo, pageSize);
	}

	public String sendEmail(String orgId, int billType, String user, String userEmail, String text) throws Exception {
		String result = "fail";
		if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(userEmail)) {
			try {
				//根据第一个项目查找邮箱
				EmailConfigModel model = emailConfigDao.getEmailByOrg(orgId);
				JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
				senderImpl.setHost(model.getSmtp_server());
				senderImpl.setPort(model.getStmp_port());
				senderImpl.setUsername(model.getEmail_address());
				senderImpl.setPassword(model.getPassword());
				senderImpl.setDefaultEncoding("UTF-8");
				Properties prop = new Properties();
				MailSSLSocketFactory sf = new MailSSLSocketFactory();
				sf.setTrustAllHosts(true);
				prop.put("mail.smtp.ssl.enable", "true");
				prop.put("mail.smtp.ssl.socketFactory", sf);
				prop.put("mail.smtp.auth", "true");
				prop.put("mail.smtp.timeout", "20000");
				senderImpl.setJavaMailProperties(prop);
				MimeMessage mail = senderImpl.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(mail, true, "UTF-8");
				if (StringUtils.isNotEmpty(model.getSend_email_name())) {
					helper.setFrom(model.getEmail_address(), model.getSend_email_name());  //发件人_发信名称
				} else {
					helper.setFrom(model.getEmail_address());  //发件人
				}

				helper.setTo(userEmail);  //收件人
				if (billType == 0) {
					helper.setSubject("账单日账单");  //邮件主题
				} else {
					helper.setSubject("逾期账单");  //邮件主题
				}

				helper.setText(text, false);  //邮件内容
				//保存至收件箱start
				senderImpl.send(mail);
				result = "success";
				//保存至收件箱end
				System.out.println("HTMLMAIL SENDED");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public String sendWechat(String month, String time, int publicNo, String openId, String user, String virName, String amount, String title, String remark) {
		String templateId = monthlyBillTempleteId;
		String result = "fail";
		if (StringUtils.isNotEmpty(templateId)) {
			Map<String, String> paramMap = new HashMap<String, String>();
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				paramMap.put("developId", wxUser.getDevelopId());
				paramMap.put("openId", wxUser.getOpenId());
				paramMap.put("templateId", templateId);
				paramMap.put("url", "");
				paramMap.put("first", title + "\\n");
				paramMap.put("keyword1", amount + "元");
				paramMap.put("keyword2", month);
				paramMap.put("keyword3", time);
				paramMap.put("remark", remark);
				weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, "", wxUser.getId(), paramMap);
				result = "success";
			}
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getWechatPushBillList(String openId)
			throws Exception {
		return pushBillDao.getWechatPushBillList(openId);
	}
}
