package com.palmnest.service.notice.impl;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.NumberUtils;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.PushSendDto;
import com.palmnest.application.dto.output.PushUserDto;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.VirtualArchDao;
import com.palmnest.dao.notice.PhoneMessageDao;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.model.notice.PhoneMessageModel;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.notice.NoticeApprovalsetManager;
import com.palmnest.service.notice.NoticeSubGroupManager;
import com.palmnest.service.notice.PhoneMessageManager;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("phoneMessageManager")
public class PhoneMessageManagerImpl extends GenericManagerImpl<PhoneMessageModel, Integer> implements PhoneMessageManager {

	private PhoneMessageDao phoneMessageDao;

	@Autowired
	public void setRoomInfoDao(PhoneMessageDao phoneMessageDao) {
		this.phoneMessageDao = phoneMessageDao;
		this.dao = phoneMessageDao;
	}

	@Autowired
	private UserDao            userDao;
	@Autowired
	private AppUserDao         appUserDao;
	@Autowired
	private OrganizationDao    organizationDao;
	@Autowired
	private VirtualArchDao     virtualArchDao;
	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;
	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	@Override
	public Page getDataList(Map<String, Object> map, int pageNo, int pageSize)
			throws Exception {
		Page page=phoneMessageDao.getDataList(map, pageNo, pageSize);
		List<Map<String, Object>> list=page.getItems();
		if(CollectionUtils.isEmpty(list)){
			return page;
		}
		String roleIds="";
		if(map.containsKey("roleIds") && null != map.get("roleIds") && StringUtils.isNotBlank(map.get("roleIds").toString())){
			roleIds=map.get("roleIds").toString();
		}
		if(StringUtils.isBlank(roleIds)){
			return page;
		}
		String [] roleArr=roleIds.split(",");
		if(null == roleArr || roleArr.length<=0 ){
			return page;
		}
		List<String> roleList = new ArrayList<>();
		roleList = Arrays.asList(roleArr);
		for(int i=0;i<list.size();i++){
			Map<String, Object> resMap=list.get(i);
			resMap.put("isPublish", 0);
			Integer id=null;
			if(resMap.containsKey("id") && null != resMap.get("id") && StringUtils.isNotBlank(resMap.get("id").toString())){
				id=Integer.parseInt(resMap.get("id").toString());
			}
			if(null == id){
				continue;
			}
			
			Integer orgId=null;
			if(resMap.containsKey("orgId") && null != resMap.get("orgId") && StringUtils.isNotBlank(resMap.get("orgId").toString())){
				orgId=Integer.parseInt(resMap.get("orgId").toString());
			}
			//项目为空时不执行多审批相关的数据
			if(null == orgId){
				continue;
			}
			
			Integer approvalTypeId=null;
			if(resMap.containsKey("approvalType") && null != resMap.get("approvalType") && StringUtils.isNotBlank(resMap.get("approvalType").toString())){
				approvalTypeId=Integer.parseInt(resMap.get("approvalType").toString());
			}
			
			Integer state=null;
			if(resMap.containsKey("state") && null != resMap.get("state") && StringUtils.isNotBlank(resMap.get("state").toString())){
				state=Integer.parseInt(resMap.get("state").toString());
			}
			//非未审核状态的直接返回，不需要判断
			if(null != state && 0 == state){
				//不为空说明该项目设置了多级审核权限,则需要判断当前登录的人是否有审核权限
				if(null != approvalTypeId && 0 != approvalTypeId.intValue()){
					Map<String,Object> roleMap=noticeApprovalsetManager.getRoleIdByOrderId(orgId, CodeConstants.APPROVAL_TYPE_NOTICE,CodeConstants.ORDER_TYPE_MESSAGE, approvalTypeId, id);
					String roleId="";
					if(roleMap.containsKey("roleId") && null != roleMap.get("roleId") && StringUtils.isNotBlank(roleMap.get("roleId").toString())){
						roleId=roleMap.get("roleId").toString();
					}
					String roleName=roleMap == null ? "" : roleMap.get("roleName") == null ? "" : roleMap.get("roleName") .toString();
					resMap.put("roleId", roleId);
					resMap.put("roleName", roleName);
					//不为空则和当前登录的角色做比对,存在当前的角色中，订单状态为未审核，则代表有审核权限
					if(StringUtils.isNotBlank(roleId) && roleList.contains(roleId) && 0 == state){
						resMap.put("isApproval", 1);
					}
				}else{
					resMap.put("isPublish",1);
				}
			}
			
		}
		return page;
	}

	@Override
	public PhoneMessageModel saveOrUpdatePhoneMessageModel(
			PhoneMessageModel phoneMessageModel) {
		if (phoneMessageModel.getId() == null) {
			PhoneMessageModel model = phoneMessageDao.save(phoneMessageModel);
			if (model != null) {
				return model;
			}
		} else {
			try {
				phoneMessageDao.updateObj(phoneMessageModel);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return phoneMessageModel;
	}

	@Override
	public Integer getTotal(String orgIds) {
		return phoneMessageDao.getTotal(orgIds);
	}

	@Override
	public PushSendDto getDetailInfo(Integer id) {
		PushSendDto dto = new PushSendDto();
		try {
			if (phoneMessageDao.exists(id)) {
				PhoneMessageModel pmm = phoneMessageDao.get(id);
				if (pmm != null) {
					dto.setId(id);
					dto.setContent(pmm.getContent());
					if (pmm.getCreateTime() != null) {
						dto.setEditTime(DateHelper.formatDate(pmm.getCreateTime(), DateHelper.DATE_TIME_STRING));
					}

					String         orgName = "";
					String         orgId   = "";
					TbOrganization orgs    = organizationDao.getOrganizationById(pmm.getOrgId());
					if (orgs != null) {
						orgId = pmm.getOrgId().toString();
						orgName = orgs.getName();
					}

					//设置编辑人
					if (StringUtil.isNotEmpty(pmm.getCreator()) && NumberUtils.isInteger(pmm.getCreator()) && userDao.exists(Long.parseLong(pmm.getCreator()))) {
						User user = userDao.get(Long.parseLong(pmm.getCreator()));
						if (user != null) {
							dto.setEditUser(user.getUsername());
						}
					} else {
						dto.setEditUser(pmm.getCreator());
					}
					dto.setState(pmm.getState().toString());
					String auditor = "";
					if (StringUtil.isNotEmpty(pmm.getApproval_user()) && NumberUtils.isInteger(pmm.getApproval_user()) && userDao.exists(Long.parseLong(pmm.getApproval_user()))) {
						User user = userDao.get(Long.parseLong(pmm.getApproval_user()));
						if (user != null) {
							auditor = user.getUsername();
						}
					} else {
						auditor = pmm.getApproval_user();
					}
					dto.setAuditor(auditor);
					dto.setType(1);
					if (pmm.getApproval_time() != null) {
						dto.setAuditTime(DateHelper.formatDate(pmm.getApproval_time(), DateHelper.DATE_TIME_STRING));
					}
					dto.setOrgId(orgId);
					dto.setIsPass(pmm.getIsPass());
					dto.setAuditOpinion(pmm.getAuditOpinion());
					dto.setApprovalType(pmm.getApprovalType());
					String approvalTypeName="";
					if(null != pmm.getApprovalType() && 0 != pmm.getApprovalType().intValue()){
						NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(pmm.getApprovalType());
						if(null != typeModel){
							approvalTypeName=typeModel.getName();
						}
					}
					
					dto.setApprovalTypeName(approvalTypeName);
					List<AuditDto> auditList=new ArrayList<AuditDto>();
					if(null != pmm && null != pmm.getApprovalType() && 0 != pmm.getApprovalType().intValue()){
						auditList=noticeApprovalsetManager.getAuditList(pmm.getOrgId(), CodeConstants.ORDER_TYPE_MESSAGE, pmm.getId());
					}else{
						if(StringUtils.isNotBlank(dto.getAuditTime())){
							AuditDto auditDto=new AuditDto();
							auditDto.setApprovalOpinion(dto.getAuditOpinion());
							if(null != dto.getIsPass() && 1 == dto.getIsPass().intValue()){
								auditDto.setApprovalResult(1);
							}else{
								auditDto.setApprovalResult(2);
							}
							auditDto.setApprovalTime(dto.getAuditTime());
							auditDto.setApprovalUser(auditor);
							auditList.add(auditDto);
						}
					}
					dto.setAuditList(auditList);
					
					//设置目标用户
					List<PushUserDto> userList = new ArrayList<PushUserDto>();
					if (StringUtil.isNotEmpty(pmm.getUserIds())) {
						String[] userArr = pmm.getUserIds().split(",");
						if (userArr != null && userArr.length > 0) {
							for (int i = 0; i < userArr.length; i++) {
								if (appUserDao.exists(Integer.parseInt(userArr[i]))) {
									AppUser user = appUserDao.get(Integer.parseInt(userArr[i]));
									if (user != null) {
										PushUserDto userDto = new PushUserDto();
										userDto.setId(userArr[i]);
										userDto.setName(user.getUserName());
										userDto.setContactWay(user.getUserMobile());
										System.out.println("项目：" + user.getOrganizationName() + "、企业:" + user.getVirtualArchName());
										//项目名
										if (user.getOrganizationId() != null) {
											TbOrganization org = organizationDao.getOrganizationById(user.getOrganizationId());
											if (org != null) {
												userDto.setOrgName(org.getName());
											}
										}
										//企业名
										if (user.getVirtualArchId() != null && virtualArchDao.exists(user.getVirtualArchId())) {
											VirtualArchitecture vir = virtualArchDao.get(user.getVirtualArchId());
											if (vir != null) {
												userDto.setVirName(vir.getName());
											}
										}
										userList.add(userDto);
									}
								}
							}
						}
					} else {//公告部分发布的
						if (StringUtil.isNotEmpty(pmm.getPhones())) {
							String[] emailArr = pmm.getPhones().split(",");
							for (int i = 0; i < emailArr.length; i++) {
								PushUserDto userDto = new PushUserDto();
								userDto.setContactWay(emailArr[i]);
								userDto.setOrgName(orgName);
								userList.add(userDto);
							}
						}
					}
					dto.setUserList(userList);
					if (userList != null) {
						dto.setCount(userList.size());
					}
					
					dto.setReceiveType(pmm.getReceiveType());
					//类型：1-公告;2-微信模板;3-短信;4-邮件;
					dto.setDeptGroupList(noticeSubGroupManager.getDeptGroupDto(3, pmm.getId()));

				}
			}
		} catch (Exception e) {
			log.error("获取短信消息详情失败(getDetailInfo):" + e.getMessage());
			e.printStackTrace();
		}
		return dto;
	}


	@Override
	public void sendMessage(List<AppUser> users, String msgContent) {

		// 循环发送短信消息
		for (AppUser user : users) {
			smsAuthCodeManager.smsSendByOrgId(user.getOrganizationId() + "", msgContent, user.getUserMobile(), null, CodeConstants.SMS_PUBLIC_TYPE);
		}
	}
}
