package com.palmnest.service.notice.impl;

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

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 cn.superdesk.libs.common.json.JsonUtils;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.dto.AuditResultVo;
import com.palmnest.application.dto.input.ApprovalRoleDto;
import com.palmnest.application.dto.input.ApprovalSetDto;
import com.palmnest.application.dto.input.ApprovalTypeDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.dao.notice.ApprovalDao;
import com.palmnest.dao.notice.ApprovalRoleDao;
import com.palmnest.dao.notice.NoticeApprovalTypeDao;
import com.palmnest.dao.notice.NoticeApprovalsetDao;
import com.palmnest.model.User;
import com.palmnest.model.notice.ApprovalModel;
import com.palmnest.model.notice.ApprovalRoleModel;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.model.notice.NoticeApprovalsetModel;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.notice.NoticeApprovalsetManager;


@Slf4j
@Service("noticeApprovalsetManager")
public class NoticeApprovalsetManagerImpl extends GenericManagerImpl<NoticeApprovalsetModel, Integer> implements NoticeApprovalsetManager{
	
	private NoticeApprovalsetDao noticeApprovalsetDao;

	@Autowired
	public void setNoticeApprovalsetDao(NoticeApprovalsetDao noticeApprovalsetDao) {
		this.noticeApprovalsetDao = noticeApprovalsetDao;
		this.dao=noticeApprovalsetDao;
	}
	
	@Autowired
	private NoticeApprovalTypeDao noticeApprovalTypeDao;
	
	@Autowired
	private ApprovalRoleDao approvalRoleDao;
	
	@Autowired
	private ApprovalDao approvalDao;

	/**
	 * 根据项目获取该项目是否开启了多级审核操作
	 * @param orgId
	 * @return
	 */
	@Override
	public NoticeApprovalsetModel getByOrgId(Integer orgId) {
		return noticeApprovalsetDao.getByOrgId(orgId);
	}
	/**
	 * 根据项目获取该项目是否开启了多级审核操作
	 * @param orgId
	 * @return
	 */
	@Override
	public Map<String,Object> getSetByOrgId(Integer orgId) {
		int isOpen=0;
		int isviews=0;
		NoticeApprovalsetModel model=noticeApprovalsetDao.getByOrgId(orgId);
		if(null != model && null != model.getId() && null != model.getIsOpen() && 1 == model.getIsOpen().intValue()){
			isOpen=1;
		}
		if(null != model && null != model.getId() && null != model.getIsViews() && 1 == model.getIsViews().intValue()){
			isviews=1;
		}
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("isOpen", isOpen);
		map.put("isViews", isviews);
		return map;
	}
	/**
	 * 保存项目设置多级审核信息
	 * @param dto
	 * @param userId 操作人
	 * @return
	 */
	@Override
	public AppResultDto saveApprovalSet(ApprovalSetDto dto, Integer userId) {
		int isviews=0;
		if(null != dto.getIsViews()){
			isviews=dto.getIsViews();
		}else{
			dto.setIsViews(isviews);
		}
		int isOpen=0;
		if(null != dto.getIsOpen()){
			isOpen=dto.getIsOpen();
		}else{
			dto.setIsOpen(isOpen);
		}
		if(null == dto.getId()){
			//新增设置多级审批信息
			NoticeApprovalsetModel setModel=saveApprovalSetModel(dto,userId);
			if(null == setModel){
				return AppResultUtil.createErrorDto("500", "保存失败");
			}
			//保存审核类型
			if(CollectionUtils.isEmpty(dto.getTypeList())){
				return AppResultUtil.createSuccesDto(dto);
			}
			List<ApprovalTypeDto> typeList=dto.getTypeList();
			log.info("NoticeApprovalsetManagerImpl-saveApprovalSet-typeList:{}",JsonUtils.toJson(typeList));
			for(ApprovalTypeDto typeDto:typeList){
				if(StringUtils.isBlank(typeDto.getName())){
					continue;
				}
				NoticeApprovalTypeModel typeModel=saveApprovalTypeModel(dto,typeDto,userId);
				if(null == typeModel){
					continue;
				}
				//保存审核角色
				if(CollectionUtils.isEmpty(typeDto.getRoleList())){
					continue;
				}
				List<ApprovalRoleDto> roleList=typeDto.getRoleList();
				log.info("NoticeApprovalsetManagerImpl-saveApprovalSet-roleList:{}",JsonUtils.toJson(roleList));
				for(ApprovalRoleDto roleDto:roleList){
					if(null == roleDto.getRoleId()){
						continue;
					}
					saveApprovalRoleModel(dto,typeDto,roleDto,userId);
				}
			}
		}else{
			//修改设置多级审核信息
			NoticeApprovalsetModel setModel=saveApprovalSetModel(dto,userId);
			if(null == setModel){
				return AppResultUtil.createErrorDto("500", "保存失败");
			}
			if(null != dto.getDelIds() && dto.getDelIds().length > 0){
				delApprovalTypeModel(dto.getDelIds(),userId);
			}
			//保存审核类型
			if(CollectionUtils.isEmpty(dto.getTypeList())){
				return AppResultUtil.createSuccesDto(dto);
			}
			List<ApprovalTypeDto> typeList=dto.getTypeList();
			log.info("NoticeApprovalsetManagerImpl-saveApprovalSet-typeList2:{}",JsonUtils.toJson(typeList));
			for(ApprovalTypeDto typeDto:typeList){
				if(StringUtils.isBlank(typeDto.getName())){
					continue;
				}
				NoticeApprovalTypeModel typeModel=saveApprovalTypeModel(dto,typeDto,userId);
				if(null == typeModel){
					continue;
				}
				//保存审核角色
				if(CollectionUtils.isEmpty(typeDto.getRoleList())){
					continue;
				}
				List<ApprovalRoleDto> roleList=typeDto.getRoleList();
				log.info("NoticeApprovalsetManagerImpl-saveApprovalSet-roleList2:{}",JsonUtils.toJson(roleList));
				for(ApprovalRoleDto roleDto:roleList){
					saveApprovalRoleModel(dto,typeDto,roleDto,userId);
				}
			}
		}
		return AppResultUtil.createSuccesDto(dto);
	}
	
	/**
	 * 保存多级审核设置
	 * @param dto
	 * @param userId
	 * @return
	 */
	private NoticeApprovalsetModel saveApprovalSetModel(ApprovalSetDto dto, Integer userId){
		if(null == dto.getId()){
			NoticeApprovalsetModel setModel=new NoticeApprovalsetModel();
			setModel.setCreatedAt(new Date());
			setModel.setCreatedBy(userId);
			setModel.setIsOpen(dto.getIsOpen());
			setModel.setOrgId(dto.getOrgId());
			setModel.setIsViews(dto.getIsViews());
			setModel=noticeApprovalsetDao.save(setModel);
			dto.setId(setModel.getId());
			return setModel;
		}else{
			if(!noticeApprovalsetDao.exists(dto.getId())){
				return null;
			}
			NoticeApprovalsetModel setModel=noticeApprovalsetDao.get(dto.getId());
			setModel.setIsOpen(dto.getIsOpen());
			setModel.setIsViews(dto.getIsViews());
			setModel.setUpdatedAt(new Date());
			setModel.setUpdatedBy(userId);
			noticeApprovalsetDao.updateObj(setModel);
			return setModel;
		}
		
	}
	
	/**
	 * 保存多级审核中审核类型信息
	 * @param dto
	 * @param typeDto
	 * @param userId
	 * @return
	 */
	private NoticeApprovalTypeModel saveApprovalTypeModel(ApprovalSetDto dto,ApprovalTypeDto typeDto, Integer userId){
		if(null == typeDto.getId() || StringUtils.isBlank(typeDto.getId().toString())){
			NoticeApprovalTypeModel typeModel=new NoticeApprovalTypeModel();
			typeModel.setApprovalsetId(dto.getId());
			typeModel.setCreatedAt(new Date());
			typeModel.setCreatedBy(userId);
			typeModel.setEnabled(1);
			typeModel.setName(typeDto.getName());
			typeModel=noticeApprovalTypeDao.save(typeModel);
			typeDto.setId(typeModel.getId());
			typeDto.setIsOperation(0);
			return typeModel;
		}else if (null != typeDto.getId()){
			if(!noticeApprovalTypeDao.exists(typeDto.getId())){
				return null;
			}
			NoticeApprovalTypeModel typeModel=noticeApprovalTypeDao.get(typeDto.getId());
			////1-新增；2-修改;3-删除；
			if(CodeConstants.OPERATION_UPDATE == typeDto.getIsOperation()){
				//修改
				typeModel.setUpdatedAt(new Date());
				typeModel.setUpdatedBy(userId);
				typeModel.setName(typeDto.getName());
				noticeApprovalTypeDao.updateObj(typeModel);
				typeDto.setIsOperation(0);
				
			}else if(CodeConstants.OPERATION_DELETE == typeDto.getIsOperation()){
				//删除
				typeModel.setUpdatedAt(new Date());
				typeModel.setUpdatedBy(userId);
				typeModel.setEnabled(0);
				noticeApprovalTypeDao.updateObj(typeModel);
			}
			return typeModel;
		}
		return null;
		
	}
	
	/**
	 * 删除审核类型
	 * @param delIds 被删除的审核类型
	 * @return
	 */
	private void delApprovalTypeModel(Integer [] delIds,Integer userId){
		for(Integer id:delIds){
			if(null == id){
				continue;
			}
			NoticeApprovalTypeModel typeModel=noticeApprovalTypeDao.get(id);
			typeModel.setUpdatedAt(new Date());
			typeModel.setUpdatedBy(userId);
			typeModel.setEnabled(0);
			noticeApprovalTypeDao.updateObj(typeModel);
		}
		
	}
	
	/**
	 * 保存多级审核中审核类型下的角色信息
	 * @param dto
	 * @param typeDto
	 * @param userId
	 * @return
	 */
	private ApprovalRoleModel saveApprovalRoleModel(ApprovalSetDto dto,ApprovalTypeDto typeDto, ApprovalRoleDto roleDto,Integer userId){
		if((null == roleDto.getId() || StringUtils.isBlank(roleDto.getId().toString())) && null != roleDto.getRoleId()){
			ApprovalRoleModel roleModel=new ApprovalRoleModel();
			roleModel.setCreatedAt(new Date());
			roleModel.setCreatedBy(userId);
			roleModel.setEnabled(1);
			roleModel.setOrderno(roleDto.getOrderno());
			roleModel.setOrgId(dto.getOrgId());
			roleModel.setRoleId(roleDto.getRoleId());
			roleModel.setSourceId(typeDto.getId());
			roleModel.setType(CodeConstants.APPROVAL_TYPE_NOTICE);
			roleModel=approvalRoleDao.save(roleModel);
			roleDto.setId(roleModel.getId());
			roleDto.setIsOperation(0);
			return roleModel;
		}else if(null != roleDto.getId()){
			if(!approvalRoleDao.exists(roleDto.getId())){
				return null;
			}
			ApprovalRoleModel roleModel=approvalRoleDao.get(roleDto.getId());
			if(CodeConstants.OPERATION_DELETE == typeDto.getIsOperation() || (null == roleDto.getRoleId() || StringUtils.isBlank(roleDto.getRoleId().toString()))){
				roleModel.setUpdatedAt(new Date());
				roleModel.setUpdatedBy(userId);
				roleModel.setEnabled(0);
				approvalRoleDao.updateObj(roleModel);
			}else{
			////1-新增；2-修改;3-删除；
				if(CodeConstants.OPERATION_UPDATE == roleDto.getIsOperation()){
					//修改
					roleModel.setUpdatedAt(new Date());
					roleModel.setUpdatedBy(userId);
					roleModel.setRoleId(roleDto.getRoleId());
					approvalRoleDao.updateObj(roleModel);
					roleDto.setIsOperation(0);
					
				}else if(CodeConstants.OPERATION_DELETE == roleDto.getIsOperation() || (null == roleDto.getRoleId() || StringUtils.isBlank(roleDto.getRoleId().toString()))){
					//删除
					roleModel.setUpdatedAt(new Date());
					roleModel.setUpdatedBy(userId);
					roleModel.setEnabled(0);
					approvalRoleDao.updateObj(roleModel);
				}
			}
			return roleModel;
		}
		return null;
	}
	/**
	 * 根据项目获取多级审核详情
	 */
	@Override
	public AppResultDto getApprovalSetDto(Integer orgId) {
		NoticeApprovalsetModel setModel=getByOrgId(orgId);
		ApprovalSetDto dto=new ApprovalSetDto();
		if(null == setModel){
			dto.setIsOpen(0);
			dto.setIsViews(0);
			dto.setOrgId(orgId);
			return AppResultUtil.createSuccesDto(dto);
		}
		dto.setIsOpen(setModel.getIsOpen() == null ? 0 : setModel.getIsOpen());
		dto.setIsViews(setModel.getIsViews() == null ? 0 : setModel.getIsViews());
		dto.setId(setModel.getId());
		dto.setOrgId(setModel.getOrgId());
		List<NoticeApprovalTypeModel> typeModelList=noticeApprovalTypeDao.getTypeListBySetId(CodeConstants.ENABLED_ONE, setModel.getId());
		if(CollectionUtils.isEmpty(typeModelList)){
			return AppResultUtil.createSuccesDto(dto);
		}
		List<ApprovalTypeDto> typeList=getTypeDtoList(typeModelList,orgId);
		if(!CollectionUtils.isEmpty(typeList)){
			dto.setTypeList(typeList);
		}
		return AppResultUtil.createSuccesDto(dto);
	}
	/**
	 * 设置审核类型
	 * @param typeModelList
	 * @param orgId
	 * @return
	 */
	private List<ApprovalTypeDto> getTypeDtoList(List<NoticeApprovalTypeModel> typeModelList,Integer orgId){
		List<ApprovalTypeDto> typeList=new ArrayList<ApprovalTypeDto>();
		for(NoticeApprovalTypeModel typeModel:typeModelList){
			if(null == typeModel || null == typeModel.getId()){
				continue;
			}
			ApprovalTypeDto typeDto=new ApprovalTypeDto();
			typeDto.setId(typeModel.getId());
			typeDto.setName(typeModel.getName());
			typeDto.setIsOperation(0);
			List<ApprovalRoleModel> roleModelList=approvalRoleDao.getRoleListBySourceId(orgId, CodeConstants.APPROVAL_TYPE_NOTICE, typeModel.getId());
			if(!CollectionUtils.isEmpty(roleModelList)){
				List<ApprovalRoleDto> roleList=getRoleDtoList(roleModelList);
				if(!CollectionUtils.isEmpty(roleList)){
					typeDto.setRoleList(roleList);
				}
			}
			
			typeList.add(typeDto);
		}
		return typeList;
	}
	
	/**
	 * 设置审核角色
	 * @param roleModelList
	 * @return
	 */
	private List<ApprovalRoleDto> getRoleDtoList(List<ApprovalRoleModel> roleModelList){
		List<ApprovalRoleDto> roleList=new ArrayList<ApprovalRoleDto>();
		for(ApprovalRoleModel roleModel:roleModelList){
			if(null == roleModel || null == roleModel.getId()){
				continue;
			}
			ApprovalRoleDto roleDto=new ApprovalRoleDto();
			roleDto.setId(roleModel.getId());
			roleDto.setIsOperation(0);
			roleDto.setRoleId(roleModel.getRoleId());
			roleDto.setOrderno(roleModel.getOrderno());
			roleList.add(roleDto);
		}
		return roleList;
	}
	/**
	 * 根据订单id获取该订单下一级审核人
	 * @param orgId
	 * @param type
	 * @param orderId
	 * @return
	 */
	@Override
	public Map<String, Object> getRoleIdByOrderId(Integer orgId, Integer type,Integer orderType,Integer approvalTypeId,Integer orderId) {
		if(null == orgId || null == type || null == orderType || null == approvalTypeId || null == orderId){
			Map<String, Object> roleMap=new HashMap<String, Object>();
			roleMap.put("roleId", "");
			roleMap.put("roleName", "");
			return roleMap;
		}
		//根据订单获取当前审核的级别 778,2,160
		int orderno=approvalDao.getOrdernoBySourceId(orgId, orderType, orderId);
		orderno++;
		//根据订单的审核类型及下一级审核人级别查询下一级审核人；
		Map<String, Object> roleMap=approvalRoleDao.getRoleIdByOrderno(orgId, type, approvalTypeId, orderno);
		//null == roleId表示已经是最后的审核人了，没有下一级了
		return roleMap;
	}
	
	/**
	 * 获取审核类型
	 * @param orgId
	 * @return
	 */
	public List<Map<String,Object>> getApprovalTypeList(Integer orgId){
		log.info("getApprovalTypeList-orgId:{}",JsonUtils.toJson(orgId));
		List<Map<String,Object>> list=noticeApprovalTypeDao.getTypeByOrgId(orgId);
		log.info("getApprovalTypeList-list:{}",JsonUtils.toJson(list));
		return list;
	}
	/**
	 * 根据订单获取审核信息
	 */
	@Override
	public List<AuditDto> getAuditList(Integer orgId, Integer type, Integer id) {
		List<ApprovalModel>  list=approvalDao.getApprovalList(orgId, type, id);
		log.info("getAuditList-list:{}",JsonUtils.toJson(list));
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		if(CollectionUtils.isEmpty(list)){
			log.info("getAuditList-auditList1:{}",JsonUtils.toJson(auditList));
			return auditList;
		}
		for(ApprovalModel model:list){
			if(null == model || null == model.getId()){
				continue;
			}
			AuditDto dto=new AuditDto();
			dto.setApprovalUser(model.getApprovalUser());
			if(null != model.getApprovalAt()){
				dto.setApprovalTime(DateHelper.formatDate(model.getApprovalAt(), DateHelper.DATE_TIME_STRING));
			}
			dto.setApprovalResult(model.getApprovalResult());
			dto.setApprovalOpinion(model.getApprovalOpinion());
			auditList.add(dto);
		}
		log.info("getAuditList-auditList2:{}",JsonUtils.toJson(auditList));
		return auditList;
	}
	/**
	 * 保存审核信息  并返回是否存在下一级
	 */
	@Override
	public AuditResultVo saveAuditInfo(AuditInfoDto dto) {
		AuditResultVo vo=new AuditResultVo();
		//查询当前审核人信息
		Map<String,Object> roleMap=getRoleIdByOrderId(dto.getOrgId(), CodeConstants.APPROVAL_TYPE_NOTICE,dto.getType(), dto.getApprovalTypeId(), dto.getSourceId());
		if(null == roleMap || !roleMap.containsKey("roleId") || null == roleMap.get("roleId") || StringUtils.isBlank(roleMap.get("roleId").toString())){
			vo.setHaveNext(0);
			vo.setApprovalModel(null);
			return vo;
		}
		ApprovalModel approvalModel=new ApprovalModel();
		approvalModel.setApprovalAt(new Date());
		approvalModel.setApprovalBy(dto.getApprovalBy());
		approvalModel.setApprovalOpinion(dto.getApprovalOpinion());
		approvalModel.setApprovalResult(dto.getApprovalResult());
		approvalModel.setApprovalSource(1);
		approvalModel.setApprovalUser(dto.getApprovalUser());
		approvalModel.setEnabled(1);
		approvalModel.setSourceId(dto.getSourceId());
		approvalModel.setType(dto.getType());
		approvalModel.setOrgId(dto.getOrgId());
		
		if(roleMap.containsKey("orderno") && null != roleMap.get("orderno")){
			approvalModel.setOrderno(Integer.parseInt(roleMap.get("orderno").toString()));
		}
		approvalModel.setRoleId(Integer.parseInt(roleMap.get("roleId").toString()));
		approvalModel=approvalDao.save(approvalModel);
		//查询下一级审核人信息
		Map<String,Object> map=getRoleIdByOrderId(dto.getOrgId(), CodeConstants.APPROVAL_TYPE_NOTICE,dto.getType(), dto.getApprovalTypeId(), dto.getSourceId());
		if(null == map || !map.containsKey("roleId") || null == map.get("roleId") || StringUtils.isBlank(map.get("roleId").toString())){
			vo.setHaveNext(0);
			vo.setApprovalModel(approvalModel);
			return vo;
		}
		vo.setHaveNext(1);
		vo.setApprovalModel(approvalModel);
		return vo;
	}
	/**
	 * 根据审核角色获取所有的审核人信息
	 * @param roleId
	 * @return
	 */
	@Override
	public List<User> getAppUserByRoleId(String roleId) {
		if(StringUtils.isBlank(roleId)){
			return null;
		}
		List<User> users=approvalDao.getAppUserByRoleId(roleId);
		log.info("getAppUserByRoleId-users:{}",JsonUtils.toJson(users));
		return users;
	}
	@Override
	public ApprovalModel updateApproval(ApprovalModel model) {
		approvalDao.updateObj(model);
		model=approvalDao.get(model.getId());
		return model;
	}
	
	/**
	 * 获取审核类型的信息
	 * @param id
	 * @return
	 */
	@Override
	public NoticeApprovalTypeModel findById(Integer id) {
		if(null == id || !noticeApprovalTypeDao.exists(id)){
			return null;
		}
		return noticeApprovalTypeDao.get(id);
	}

	
}
