package com.goafanti.user.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.enums.IdentityAuditStatus;
import com.goafanti.common.enums.NoticeReadStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.portal.bo.OrgSubscriberListBo;
import com.goafanti.user.bo.AuditorOrgIdentityDetailBo;
import com.goafanti.user.bo.OrgBasicInfoBo;
import com.goafanti.user.bo.OrgIdentityBo;
import com.goafanti.user.bo.OrgUnitNames;
import com.goafanti.user.service.OrganizationIdentityService;

@Service
public class OrganizationIdentityServiceImpl extends BaseMybatisDao<OrganizationIdentityMapper>
		implements OrganizationIdentityService {
	@Autowired
	private OrganizationIdentityMapper	organizationIdentityMapper;
	@Autowired
	private UserMapper					userMapper;
	@Autowired
	private NoticeMapper				noticeMapper;
	@Autowired
	private UserRoleMapper				userRoleMapper;

	private static final Logger logger = LoggerFactory.getLogger(OrganizationIdentityServiceImpl.class);
	@Override
	public OrganizationIdentity insert(OrganizationIdentity organizationIdentity) {
		organizationIdentityMapper.insert(organizationIdentity);
		return organizationIdentity;
	}

	@Override
	public OrganizationIdentity selectOrgIdentityByUserId(String userId) {
		return organizationIdentityMapper.selectOrgIdentityByUserId(userId);
	}

	@Override
	public int updateByPrimaryKeySelective(OrganizationIdentity organizationIdentity) {
		return organizationIdentityMapper.updateByPrimaryKeySelective(organizationIdentity);
	}

	@Override
	public OrgIdentityBo selectOrgIdentityBoByUserId(String uid) {
		return organizationIdentityMapper.selectOrgIdentityBoByUserId(uid);
	}

	@Override
	public List<OrgUnitNames> selectAllOrgIndentity() {
		String aid = null;
		/*if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			aid = TokenManager.getAdminId();
		}*/
		return organizationIdentityMapper.selectAllOrgIndentity(aid);
	}

	@Override
	public int updateByPrimaryKey(OrganizationIdentity org) {
		return organizationIdentityMapper.updateByPrimaryKey(org);
	}

	@Override
	public Map<String, String> selectContactsByUserId(String uid) {
		OrganizationIdentity i = organizationIdentityMapper.selectOrgIdentityByUserId(uid);
		Map<String, String> map = new TreeMap<String, String>();
		return map;
	}

	@Override
	public int updateOrgDetailByAuditAdmin(OrganizationIdentity oi, String aid, String mid, Integer level) {
		User user = userMapper.selectByPrimaryKey(oi.getUid());
		if (!IdentityAuditStatus.PASSED.getCode().equals(oi.getAuditStatus())) {
			user.setLvl(UserLevel.GENERAL.getCode());
			userMapper.updateByPrimaryKeySelective(user);
			createNotice(user, oi.getAuditStatus());
		} else {
			/*
			 * if (UserLevel.GENERAL.getCode().equals(level)) {
			 * user.setLvl(UserLevel.CERTIFIED.getCode()); }
			 */
			user.setLvl(UserLevel.CERTIFIED.getCode());
			user.setAid(aid);
			user.setMid(mid);
			userMapper.updateByPrimaryKeySelective(user);
			// disposeRatePay(oi, oi.getUid());
			createNotice(user, oi.getAuditStatus());
		}
		return organizationIdentityMapper.updateByPrimaryKeySelective(oi);
	}

	@Override
	public OrgBasicInfoBo selectBasicInfo(String uid, int year) {
		return organizationIdentityMapper.selectBasicInfo(uid, year);
	}

	@Override
	public AuditorOrgIdentityDetailBo selectAuditorOrgIdentityDetailByUserId(String uid) {

		return organizationIdentityMapper.selectAuditorOrgIdentityDetailByUserId(uid,
				Calendar.getInstance().get(Calendar.YEAR - 1));
	}


	// 给业务员及客户经理发送通知
	private void createNotice(User u, Integer status) {
		if (!StringUtils.isBlank(u.getAid())) {
			Notice n = new Notice();
			n.setPid(u.getAid());
			n.setAid(u.getAid());
			n.setUid(u.getId());
			notice(n, status);
		}

		if (!StringUtils.isBlank(u.getMid())) {
			Notice n = new Notice();
			n.setUid(u.getId());
			n.setAid(u.getMid());
			if (!StringUtils.isBlank(u.getAid())) {
				n.setPid(u.getAid());
			}
			notice(n, status);
		}

	}

	// 给所有审核员发送审核通知
	private void createAuditorNotice(User u) {
		List<String> ids = userRoleMapper.listAuditor();
		List<Notice> list = new ArrayList<>();
		if (ids.size() > 0 && null != ids) {
			for (String s : ids) {
				Notice n = new Notice();
				Calendar now = Calendar.getInstance();
				now.set(Calendar.MILLISECOND, 0);
				n.setId(UUID.randomUUID().toString());
				n.setCreateTime(now.getTime());
				n.setReaded(NoticeReadStatus.UNREAD.getCode());

				if (null != u) {
					n.setPid(u.getAid());
				}
				n.setUid(u.getId());
				n.setAid(s);
				n.setContent(
						NoticeStatus.ORGANIZATIONCERTIFY.getDesc() + " " + IdentityAuditStatus.COMMITTED.getDesc());
				n.setNoticeType(NoticeStatus.ORGANIZATIONCERTIFY.getCode());
				list.add(n);
			}
			noticeMapper.insertBatch(list);
		}
	}

	private void notice(Notice n, Integer status) {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		n.setId(UUID.randomUUID().toString());
		n.setCreateTime(now.getTime());
		n.setReaded(NoticeReadStatus.UNREAD.getCode());
		String content = NoticeStatus.ORGANIZATIONCERTIFY.getDesc();
		if (IdentityAuditStatus.UNCOMMITTED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.UNCOMMITTED.getDesc();
		} else if (IdentityAuditStatus.COMMITTED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.COMMITTED.getDesc();
		} else if (IdentityAuditStatus.UNPAID.getCode() == status) {
			content = content + " " + IdentityAuditStatus.UNPAID.getDesc();
		} else if (IdentityAuditStatus.PAID.getCode() == status) {
			content = content + " " + IdentityAuditStatus.PAID.getDesc();
		} else if (IdentityAuditStatus.PASSED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.PASSED.getDesc();
		} else {
			content = content + " " + IdentityAuditStatus.NOTPASSED.getDesc();
		}
		n.setContent(content);
		n.setNoticeType(NoticeStatus.ORGANIZATIONCERTIFY.getCode());
		// noticeMapper.insert(n);
	}

	@Override
	public void save(OrgIdentityBo orgIdentityBo) {
		OrganizationIdentity oi = new OrganizationIdentity();
		BeanUtils.copyProperties(orgIdentityBo, oi);
		User u = userMapper.selectByPrimaryKey(TokenManager.getUserId());
		u.setEmail(orgIdentityBo.getEmail());
		userMapper.updateByPrimaryKeySelective(u);
		OrganizationIdentity o = organizationIdentityMapper.selectOrgIdentityByUserId(TokenManager.getUserId());
		if (null == o && StringUtils.isBlank(oi.getId())) {
			oi.setId(UUID.randomUUID().toString());
			oi.setUid(TokenManager.getUserId());
			organizationIdentityMapper.insert(oi);
		} else if (null != o && StringUtils.isNotBlank(oi.getId())) {
			organizationIdentityMapper.updateByPrimaryKeySelective(oi);
		}
	}
}
