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.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.goafanti.common.bo.Result;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.dao.OrgHumanResourceMapper;
import com.goafanti.common.dao.OrgRatepayMapper;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.enums.CertifySubmitType;
import com.goafanti.common.enums.DeleteStatus;
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.OrgHumanResource;
import com.goafanti.common.model.OrgRatepay;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.organization.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.OrgIdentityDetailAdmin;
import com.goafanti.user.bo.OrgIdentityDetailBo;
import com.goafanti.user.bo.OrgUnitNames;
import com.goafanti.user.bo.OrganizationIndentityUserBo;
import com.goafanti.user.service.OrganizationIdentityService;

@Service
public class OrganizationIdentityServiceImpl extends BaseMybatisDao<OrganizationIdentityMapper>
		implements OrganizationIdentityService {
	@Autowired
	private OrganizationIdentityMapper	organizationIdentityMapper;
	@Autowired
	private OrgRatepayMapper			orgRatepayMapper;
	@Autowired
	private UserMapper					userMapper;
	@Autowired
	private OrgHumanResourceMapper		orgHumanResourceMapper;
	@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);
	}

	public OrganizationIndentityUserBo selectOrgIdentityUserBoByUserId(String userId) {
		OrganizationIdentity oi = organizationIdentityMapper.selectOrgIdentityByUserId(userId);
		OrgRatepay ratepay = orgRatepayMapper.selectRatepayByUidAndYear(userId,
				Calendar.getInstance().get(Calendar.YEAR) - 1);
		OrganizationIndentityUserBo bo = new OrganizationIndentityUserBo();
		BeanUtils.copyProperties(oi, bo);
		if (null != ratepay && StringUtils.isNotBlank(ratepay.getId())) {
			bo.setRatepayId(ratepay.getId());
		}
		return bo;
	}

	@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) {
		organizationIdentityMapper.selectOrgIdentityByUserId(uid);
		Map<String, String> map = new TreeMap<String, String>();
		return map;
	}

	@Override
	public int saveOrgIndentityProcess(Result res, OrganizationIdentity o, String uid) {
		OrganizationIdentity org = organizationIdentityMapper.selectOrgIdentityByUserId(uid);
		if (StringUtils.isNotBlank(o.getLastYearTaxReportUrl())) {
			disposeRatePay(o, uid);
		}
		if (null == org) {
			o.setId(UUID.randomUUID().toString());
			o.setUid(uid);
			return organizationIdentityMapper.insert(o);
		} else {
			o.setId(org.getId());
			if (null != o.getAuditStatus() && 5 == o.getAuditStatus()) {
				User u = new User();
				u.setId(uid);
				u.setLvl(UserLevel.CERTIFIED.getCode());
				userMapper.updateByPrimaryKeySelective(u);
			}
			return organizationIdentityMapper.updateByPrimaryKeySelective(o);
		}
	}

	@Override
	public int updateOrgDetail(OrganizationIdentity orgIdentity, String saveSign, Integer level) {
		if (StringUtils.isNotBlank(orgIdentity.getLastYearTaxReportUrl())) {
			disposeRatePay(orgIdentity, orgIdentity.getUid());
		}
		User user = userMapper.selectByPrimaryKey(orgIdentity.getUid());
		user.setLvl(level);
		userMapper.updateByPrimaryKeySelective(user);
		if (CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			createAuditorNotice(user);
		}
		return organizationIdentityMapper.updateByPrimaryKeySelective(orgIdentity);

	}

	@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 int saveBasicInfo(OrganizationIdentity oi, OrgHumanResource ohr) {
		if (StringUtils.isBlank(oi.getId())) {
			oi.setId(UUID.randomUUID().toString());
			organizationIdentityMapper.insert(oi);
		} else {
			organizationIdentityMapper.updateByPrimaryKeySelective(oi);
		}

		if (StringUtils.isBlank(ohr.getId())) {
			ohr.setId(UUID.randomUUID().toString());
			ohr.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			Calendar now = Calendar.getInstance();
			ohr.setYear(now.get(Calendar.YEAR) - 1);
			orgHumanResourceMapper.insert(ohr);
		} else {
			orgHumanResourceMapper.updateByPrimaryKeySelective(ohr);
		}
		return 1;
	}

	@Override
	public OrgIdentityDetailBo selectOrgIdentityDetailByUserId(String uid) {
		return organizationIdentityMapper.selectOrgIdentityDetailByUserId(uid);
	}

	@Override
	public AuditorOrgIdentityDetailBo selectAuditorOrgIdentityDetailByUserId(String uid) {

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

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrgSubscriberListBo> listSubscriber(String url,String name, Integer level, String field, Integer province,
			Integer city, Integer area, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(url)) {
			params.put("url", url);
		}
		if (StringUtils.isNotBlank(name)) {
			params.put("name", name);
		}

		if (null != level) {
			params.put("level", level);
		}

		if (StringUtils.isNotBlank(field)) {
			params.put("field", field);
		}

		if (null != province) {
			params.put("province", province);
		}

		if (null != city) {
			params.put("city", city);
		}

		if (null != area) {
			params.put("area", area);
		}

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 12) {
			pSize = 12;
		}
		return (Pagination<OrgSubscriberListBo>) findPage("findSearchSubscriberListByPage", "findSearchSubscriberCount",
				params, pNo, pSize);
	}

	// 给业务员及客户经理发送通知
	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 OrgIdentityDetailAdmin selectOrgIdentityDetailByUserIdAdmin(String uid) {
		OrganizationIdentity o = organizationIdentityMapper.selectOrgIdentityByUserId(uid);
		User u = userMapper.selectByPrimaryKey(uid);
		OrgIdentityDetailAdmin bo = new OrgIdentityDetailAdmin();
		BeanUtils.copyProperties(o, bo);
		bo.setLevel(u.getLvl().toString());
		Calendar now = Calendar.getInstance();
		OrgRatepay ratepay = orgRatepayMapper.selectRatepayByUidAndYear(uid, now.get(Calendar.YEAR) - 1);
		if (null != ratepay) {
			bo.setRatepayId(ratepay.getId());
		}
		return bo;
	}

	private void disposeRatePay(OrganizationIdentity o, String uid) {
		Calendar now = Calendar.getInstance();
		OrgRatepay ratepay = orgRatepayMapper.selectRatepayByUidAndYear(uid, now.get(Calendar.YEAR) - 1);
		if (null == ratepay) {
			OrgRatepay r = new OrgRatepay();
			r.setId(UUID.randomUUID().toString());
			r.setUid(uid);
			r.setYear(now.get(Calendar.YEAR) - 1);
			r.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			r.setTaxReturnUrl(o.getLastYearTaxReportUrl());
			orgRatepayMapper.insert(r);
		} else {
			ratepay.setTaxReturnUrl(o.getLastYearTaxReportUrl());
			orgRatepayMapper.updateByPrimaryKeySelective(ratepay);
		}
	}

	@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);
		}
	}
	
	@CacheEvict(value = "internationalOrgList" ,allEntries = true)
	public void cleanInternationalOrg(){
		LoggerUtils.debug(logger, "清除国际伙伴列表");
	} 
}
