package com.goafanti.user.service.impl;

import com.goafanti.common.bo.Result;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
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.portal.bo.OrgSubscriberListBo;
import com.goafanti.user.bo.*;
import com.goafanti.user.service.OrganizationIdentityService;
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 java.util.*;

@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 AsyncUtils				asyncUtils;
	@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.update(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.update(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.update(u);
			}
			return organizationIdentityMapper.update(o);
		}
	}

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

	}

	@Override
	public int updateOrgDetailByAuditAdmin(OrganizationIdentity oi, String aid, String mid, Integer level) {
		User user = userMapper.queryById(oi.getUid());
		if (!IdentityAuditStatus.PASSED.getCode().equals(oi.getAuditStatus())) {
			user.setLvl(UserLevel.GENERAL.getCode());
			userMapper.update(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.update(user);
			// disposeRatePay(oi, oi.getUid());
			createNotice(user, oi.getAuditStatus());
		}
		return organizationIdentityMapper.update(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.update(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);
			}
			asyncUtils.addNoticeBatch(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());
	}

	@Override
	public OrgIdentityDetailAdmin selectOrgIdentityDetailByUserIdAdmin(String uid) {
		OrganizationIdentity o = organizationIdentityMapper.selectOrgIdentityByUserId(uid);
		User u = userMapper.queryById(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.queryById(TokenManager.getUserId());
		u.setEmail(orgIdentityBo.getEmail());
		userMapper.update(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.update(oi);
		}
	}
	
	@CacheEvict(value = "internationalOrgList" ,allEntries = true)
	public void cleanInternationalOrg(){
		LoggerUtils.debug(logger, "清除国际伙伴列表");
	} 
}
