package com.palmnest.service.notice.service.impl;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.output.PushSendDto;
import com.palmnest.application.dto.output.PushUserDto;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.notice.EmailSendModel;
import com.palmnest.model.notice.PhoneMessageModel;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.notice.AppNoticeManager;
import com.palmnest.service.notice.EmailSendManager;
import com.palmnest.service.notice.PhoneMessageManager;
import com.palmnest.service.notice.service.PushSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Slf4j
@Service("pushSendService")
public class PushSendServiceImpl implements PushSendService {


	@Autowired
	private EmailSendManager    emailSendManager;
	@Autowired
	private PhoneMessageManager phoneMessageManager;
	@Autowired
	private AppUserManager      appUserManager;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private AppNoticeManager    appNoticeManager;
	@Autowired
	private SmsAuthCodeManager  smsAuthCodeManager;

	private String hostUrl    = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private String wxEmailUrl = PropertiesKit.readPropertiesValue("wxEmailUrl", "wechat.properties");
	private String wxMsgUrl   = PropertiesKit.readPropertiesValue("wxMsgUrl", "wechat.properties");

	/**
	 * 获取详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public PushSendDto getDetailInfo(Integer id, Integer type) {
		if (2 == type && emailSendManager.exists(id)) {//获取发送邮箱的详情
			return emailSendManager.getDetailInfo(id);
		} else if (1 == type && phoneMessageManager.exists(id)) {//获取发送短信的详情
			return phoneMessageManager.getDetailInfo(id);
		}
		return null;
	}

	/**
	 * 审核
	 *
	 * @param dto
	 * @param auditor 审核人
	 * @return
	 */
	@Override
	public AppResultDto approvalSend(PushSendDto dto, String auditor, List<PushUserDto> carDto, String token) {
		String res = "FAIL";
		if (2 == dto.getType() && emailSendManager.exists(dto.getId())) {//获取发送邮箱的详情
			log.info("开始发送邮件email-----------------------------");
			res = approvalEmail(dto, auditor, carDto, token);
		} else if (1 == dto.getType() && phoneMessageManager.exists(dto.getId())) {//获取发送短信的详情
			log.info("开始发送短信mobile-----------------------------");
			res = approvalPhone(dto, auditor, carDto, token);
		}
		if ("FAIL".equals(res)) {
			log.error("approvalSend/审核失败");
			return AppResultUtil.createErrorDto("100", "审核失败");
		}
		return AppResultUtil.createSuccesDto(res);
	}

	/**
	 * 邮箱审核
	 *
	 * @param dto
	 * @param auditor 审核人
	 * @return
	 */
	private String approvalEmail(PushSendDto dto, String auditor, List<PushUserDto> userList, String token) {
		String str = "FAIL";
		try {
			String         id        = dto.getId() + "";
			EmailSendModel emailSend = emailSendManager.get(dto.getId());
			emailSend.setApproval_user(auditor);
			emailSend.setApproval_time((new Date()));
			int state = 0;
			if (1 == dto.getIsPass()) {//通过
				state = 1;
			} else if (0 == dto.getIsPass()) {//不通过
				state = 2;
			}
			emailSend.setAuditOpinion(dto.getAuditOpinion());//审核意见
			emailSend.setIsPass(dto.getIsPass());//审核结果（0不通过1通过）
			emailSend.setState(state);//状态   0待审核1已发布2已驳回
			emailSend.setSend_time(new Date());
			int    count          = 0;
			String recipientEmail = "";
			String userIds        = "";
			if (userList != null && userList.size() > 0) {
				count = userList.size();
				for (int i = 0; i < userList.size(); i++) {
					PushUserDto userDto = userList.get(i);
					if (userDto != null && StringUtil.isNotEmpty(userDto.getContactWay())) {
						recipientEmail = recipientEmail + userDto.getContactWay() + ";";
					}
					if (userDto != null && StringUtil.isNotEmpty(userDto.getId())) {
						userIds = userIds + userDto.getId() + ",";
					}
				}
			}
			emailSend.setTotal(count);
			emailSend.setEmailaccount_id(Integer.parseInt(dto.getAccountId()));
			emailSend.setSsender_email(dto.getSendEmail());
			emailSend.setRecipient_email(recipientEmail);
			emailSend.setEmail_theme(dto.getTitle());
			emailSend.setEmail_centent(dto.getEmailCentent());
			emailSend.setAttach_ment(dto.getAttachment());
			emailSend.setContentTxt(dto.getContent());
			emailSend.setModifier(auditor);
			emailSend.setModifyTime(new Date());
			emailSend.setUserIds(userIds);
			emailSendManager.updateModel(emailSend);
			//推送消息
			String     userId    = emailSend.getCreator();
			List<User> usersList = new ArrayList<User>();
			User       user1     = userManager.get(Long.parseLong(userId));
			usersList.add(user1);

			String pathUrl = hostUrl + wxEmailUrl.replace("@id", id) + "&token=" + token;
			if (dto.getIsPass() == 1) {
				//发送邮件
				emailSendManager.sendEmail(emailSend);
				appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您发起的邮箱消息已审核通过", "已审核通过", usersList);
			} else if (dto.getIsPass() == 0) {
				appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您发起的邮箱消息已被驳回", "未通过审核", usersList);
			}
			str = pathUrl;
		} catch (Exception e) {
			str = "FAIL";
			e.printStackTrace();
			log.error("邮箱审核失败(approvalEmail)" + e.getMessage());
		}
		return str;
	}

	/**
	 * 短信发送
	 *
	 * @param dto
	 * @param auditor
	 * @return
	 */
	private String approvalPhone(PushSendDto dto, String auditor, List<PushUserDto> userList, String token) {
		String str = "FAIL";
		try {
			String            id           = dto.getId() + "";
			PhoneMessageModel phoneMessage = phoneMessageManager.get(dto.getId());
			String            userId       = phoneMessage.getCreator();
			List<User>        usersList    = new ArrayList<User>();
			User              user2        = userManager.get(Long.parseLong(userId));
			usersList.add(user2);
			String pathUrl = hostUrl + wxMsgUrl.replace("@id", id) + "&token=" + token;

			int state = 0;
			if (1 == dto.getIsPass()) {//通过
				state = 1;
			} else if (0 == dto.getIsPass()) {//不通过
				state = 2;
			}
			phoneMessage.setAuditOpinion(dto.getAuditOpinion());//审核意见
			phoneMessage.setIsPass(dto.getIsPass());//审核结果（0不通过1通过）
			phoneMessage.setApproval_user(auditor);//审核人
			phoneMessage.setApproval_time((new Date()));//审核时间
			phoneMessage.setModifyTime((new Date()));//修改时间
			phoneMessage.setModifier(auditor);
			phoneMessage.setState(state);
			int    count   = 0;
			String mobiles = "";
			String userIds = "";
			if (userList != null && userList.size() > 0) {
				count = userList.size();
				for (int i = 0; i < userList.size(); i++) {
					PushUserDto userDto = userList.get(i);
					if (userDto != null && StringUtil.isNotEmpty(userDto.getContactWay())) {
						mobiles = mobiles + userDto.getContactWay() + ",";
					}
					if (userDto != null && StringUtil.isNotEmpty(userDto.getId())) {
						userIds = userIds + userDto.getId() + ",";
					}

				}
			}
			phoneMessage.setUserIds(userIds);
			phoneMessage.setTotal(count);//推送条数
			phoneMessage.setPhones(mobiles);
			phoneMessage.setSend_time(new Date());
			phoneMessage.setMsgCost(count);
			phoneMessage.setPhones_quantity(count);
			phoneMessage.setContent(dto.getContent());
			phoneMessageManager.updateModel(phoneMessage);
			//推送消息
			if (dto.getIsPass() == 1) {
				//发送短信
				log.info("发送短信号码：" + mobiles);
				String result = smsAuthCodeManager.smsSendByOrgId(phoneMessage.getOrgId().toString()
						, dto.getContent(), mobiles, "", CodeConstants.SMS_MESSAGE_TYPE);
				log.info("isMessage：" + result);
				appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您发起的短信消息已审核通过", "已审核通过", usersList);
			} else if (dto.getIsPass() == 0) {
				appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您发起的短信消息已被驳回", "未审核通过", usersList);
			}
			str = pathUrl;
		} catch (Exception e) {
			str = "FAIL";
			e.printStackTrace();
			log.error("短信审核失败(approvalPhone)" + e.getMessage());
		}

		return str;

	}

	/**
	 * 发送短信
	 */
	@Override
	public AppResultDto sendMessage(String orgId, String userId, String userIds, String content) {
		PhoneMessageModel model = new PhoneMessageModel();
		try {
			model.setOrgId(Integer.parseInt(orgId));
			model.setContent(content);
			model.setPhones(getSendWay(1, userIds));
			model.setCreateTime(new Date());
			model.setCreator(userId);
			model.setIsEnabled("1");
			model.setTotal(userIds.split(",").length);
			model.setUserIds(userIds);
			model.setState(0);
			phoneMessageManager.save(model);
		} catch (Exception e) {
			log.error("保存短信信息失败：" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "保存短信信息失败");
		}
		return AppResultUtil.createSuccesDto();
	}

	private String getSendWay(int type, String userIds) {
		String   sendWay = "";
		String[] userArr = userIds.split(",");
		if (userArr != null && userArr.length > 0) {
			for (int i = 0; i < userArr.length; i++) {
				if (appUserManager.exists(Integer.parseInt(userArr[i]))) {
					AppUser user = appUserManager.get(Integer.parseInt(userArr[i]));
					if (type == 1) {
						//短信
						sendWay = sendWay + user.getUserMobile() + ",";
					} else if (type == 2) {
						//邮箱
						sendWay = sendWay + user.getEmail() + ";";
					}
				}
			}
		}
		return sendWay;
	}

	/**
	 * 发送邮箱
	 */
	@Override
	public AppResultDto sendEmail(String orgId, String userId, String userIds, String content,
								  String sendEmailId, String title, String filePaths, String emailCentent) {
		EmailSendModel model = new EmailSendModel();
		try {
			model.setRecipient_email(getSendWay(2, userIds));
			model.setEmail_theme(title);
			model.setEmail_centent(emailCentent);
			model.setContentTxt(content);
			model.setCreateTime(new Date());
			model.setCreator(userId);
			model.setEmailaccount_id(Integer.parseInt(sendEmailId));
			model.setIsEnabled("1");
			model.setTotal(userIds.split(";").length);
			model.setOrgId(Integer.parseInt(orgId));
			model.setUserIds(userIds);
			model.setState(0);
			emailSendManager.save(model);
		} catch (Exception e) {
			log.error("保存邮件信息失败：" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "保存邮件信息失败");
		}
		return AppResultUtil.createSuccesDto();
	}


}
