package com.goafanti.admin.service.impl;

import com.goafanti.admin.bo.AdminDetail;
import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.admin.bo.AdminPublicReviewerBo;
import com.goafanti.admin.bo.AdminReviewer;
import com.goafanti.admin.service.NewAdminService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NewAdminServiceImpl extends BaseMybatisDao<AdminMapper> implements NewAdminService {
	@Resource
	private AdminMapper			adminMapper;
	@Resource
	private UserRoleMapper		userRoleMapper;
	@Resource
	private AdminLocationMapper	adminLocationMapper;
	@Resource
	private AmbSystemMapper	ambSystemMapper;
	@Resource
	private RoleMapper	roleMapper;
	@Resource
	private AsyncUtils asyncUtils;
	@Resource
	private AdminPublicReviewerMapper adminPublicReviewerMapper;
	@Resource
	private AdminCallDayMapper adminCallDayMapper;

	@Override
	public Pagination<AdminListBo> listAdmin(AdminListBo alb, String rid,String roleName,Integer pageNo, Integer pageSize) {
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(alb.getName())) params.put("name", alb.getName());
		if(StringUtils.isNotBlank(roleName)) params.put("roleName", roleName);
		if(StringUtils.isNotBlank(alb.getDepartmentId())) params.put("departmentId", alb.getDepartmentId());
		if(StringUtils.isNotBlank(rid)) params.put("rid", rid);
		if(StringUtils.isNotBlank(alb.getDuty())) params.put("duty",alb.getDuty());
		if(StringUtils.isNotBlank(alb.getPosition())) params.put("position", alb.getPosition());
		if(StringUtils.isNotBlank(alb.getStatus())) params.put("status", alb.getStatus());
		if(StringUtils.isNotBlank(alb.getMobile())) params.put("mobile", alb.getMobile());
		if(StringUtils.isNotBlank(alb.getSuperiorId())) params.put("superiorId", alb.getSuperiorId());
		if(StringUtils.isNotBlank(alb.getAmbId())) params.put("ambId", alb.getAmbId());
		//新增团队查询
		if(alb.getTeamId()!=null) params.put("teamId", alb.getTeamId());
		if(StringUtils.isNotBlank(alb.getAncestors())) params.put("ancestors", alb.getAncestors());
		if(alb.getAmbManage()!=null) params.put("ambManage", alb.getAmbManage());
		if(alb.getSeniorStaff()!=null) params.put("seniorStaff", alb.getSeniorStaff());
		if(alb.getPublicPurview()!=null) params.put("publicPurview", alb.getPublicPurview());
		Pagination<AdminListBo> p=(Pagination<AdminListBo>)findPage("selectAdminListByPage","selectAdminCount",params,pageNo,pageSize);
		List<AdminListBo> list= (List<AdminListBo>) p.getList();
		for(AdminListBo i:list){
			pushRolesName(i);
		}
		return p;
	}

	@Override
	public void pushRolesName(AdminListBo i) {
		List<Role> roles = adminMapper.selectRolesByUid(i.getId());
		i.setRoles(roles);
		List<String> ls=new ArrayList<>();
		for (Role role : roles) {
			ls.add(role.getRoleName());
		}
		i.setRolesName(ls);
		List<AdminPublicReviewerBo> list = adminPublicReviewerMapper.selectByAid(i.getId());
		List<AdminPublicReviewerBo> collect = list.stream().filter(e -> e.getType() == 2).collect(Collectors.toList());
		StringJoiner sb = new StringJoiner(",");
		for (AdminPublicReviewerBo e : collect) {
			sb.add(e.getReviewerName());
		}
		if  (sb.length() > 0) {
			i.setSuperior(sb.toString());
		}

	}

	@Override
	public Object publicReviewer(String id) {
		List<AdminPublicReviewerBo> list = adminPublicReviewerMapper.selectByAid(id);
		List<AdminPublicReviewerBo> collect = list.stream().filter(e -> e.getType() == 0).collect(Collectors.toList());
		List<AdminPublicReviewerBo> collect2 = list.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
		List<AdminPublicReviewerBo> collect3 = list.stream().filter(e -> e.getType() == 2).collect(Collectors.toList());
		List<AdminPublicReviewerBo> collect4 = list.stream().filter(e -> e.getType() == 3).collect(Collectors.toList());
		Map<String, Object> map = new HashMap<>();
			map.put("publicReviewer", collect);
			map.put("assistReviewer", collect2);
			map.put("superReviewer", collect3);
			map.put("carbonCopyReviewer", collect4);
		return map;
	}

	@Override
	public List<Admin> selectAllAdmin() {
		return adminMapper.selectAllAdmin(null);
	}

	@Override
	public Admin selectByMobile(String mobile) {
		return adminMapper.selectByMobile(mobile);
	}

	@Override
	public Admin selectByPrimaryKey(String key) {
		return adminMapper.selectById(key);
	}

	@Override
	public int insert(Admin ad) {
		return adminMapper.insert(ad);
	}

	@SuppressWarnings("unused")
	@Override
	public int updateByPrimaryKeySelective(Admin ad, Admin useAdmin, List<String> roleIds, AdminReviewer adminReviewer) {
		Map<String, Object> params = new HashMap<>();
		params.put("uid", ad.getId());
		params.put("roles", roleIds);
		List<Role>  useRole = roleMapper.selectByAid(ad.getId());
		if (ad.getId() != "1") {
			userRoleMapper.deleteByUserId(ad.getId());
			if (!roleIds.isEmpty()) {
				userRoleMapper.insertBatch(params);
			}
			TokenManager.clearUserAuthByUserId(ad.getId());
		}
		ad.setType(sumType(roleIds));
		if (ad.getExpenseSuperExamine()==null)ad.setExpenseSuperExamine(0);
		int count=adminMapper.update(ad);
		if (StringUtils.isBlank(ad.getManagerId())){
			ad.setManagerId(null);
			adminMapper.updateManagerId(ad);
		}
		//
		asyncUtils.pushRoleUpdateExamine(ad,useAdmin,roleIds,useRole);
		//修改公出审核人
		updateReviewer(ad, adminReviewer);
		pushAmbRole(ad);
		//统计团队更换每天统计表
		if (useAdmin.getTeamId()!=null&&!useAdmin.getTeamId().equals(ad.getTeamId())){
			adminCallDayMapper.updateTeamId(ad.getId(),ad.getTeamId());
		}

		if (count>0&&ad.getAmbId()!=null){
			//进行巴人数计算
//			AmbSystem ambSystem = ambSystemMapper.selectByPrimaryKey(Long.valueOf(ad.getAmbId()));
//			if (ambSystem.getAncestors()!=null){
//				List<String> list = Arrays.asList(ambSystem.getAncestors().split(","));
//
//			}
		}
		return count;
	}

	private void updateReviewer(Admin ad, AdminReviewer adminReviewer) {
		if(adminReviewer.getPublicReviewerIds()!=null)updatePublicReviewer(ad.getId(), adminReviewer.getPublicReviewerIds(),0);
		if(adminReviewer.getAssistReviewerIds()!=null)updatePublicReviewer(ad.getId(), adminReviewer.getAssistReviewerIds(),1);
		if(adminReviewer.getSuperReviewerIds()!=null)updatePublicReviewer(ad.getId(), adminReviewer.getSuperReviewerIds(),2);
		if(adminReviewer.getCarbonCopyReviewerIds()!=null)updatePublicReviewer(ad.getId(), adminReviewer.getCarbonCopyReviewerIds(),3);
	}

	private void updatePublicReviewer(String aid ,String reviewerIds,Integer type) {
		String[] split = reviewerIds.split(",");
		if (split.length==1&&split[0].isEmpty()){
				adminPublicReviewerMapper.deleteByAid(aid,type);
		}else {
			List<AdminPublicReviewerBo> list = adminPublicReviewerMapper.selectByAid(aid);
			list=list.stream().filter(e -> Objects.equals(e.getType(), type)).collect(Collectors.toList());
			//
			for (AdminPublicReviewerBo e : list) {
				boolean flag = false;
				for (String s : split) {
					if (e.getReviewerId().equals(s)){
						flag = true;
					}
				}
				if (!flag){
					adminPublicReviewerMapper.deleteById(e.getId());
				}
			}
			for (String s : split) {
				boolean flag = false;
				for (AdminPublicReviewerBo e : list) {
					if (e.getReviewerId().equals(s)){
						flag = true;
					}
				}
				if (!flag&&StringUtils.isNotBlank(s)){
					AdminPublicReviewer adminPublicReviewer = new AdminPublicReviewer();
					adminPublicReviewer.setAid(aid);
					adminPublicReviewer.setReviewerId(s);
					adminPublicReviewer.setType(type);
					adminPublicReviewer.setCreateTime(new Date());
					adminPublicReviewerMapper.insert(adminPublicReviewer);
				}
			}
		}
	}


	/**
	 * 用户角色类型
	 * 用在发起公出判定能否，其他位置待补充
	 */
	private int sumType(List<String > roleIds) {
		//其他角色就是0=其他
		int type=0;
		for (String roleId : roleIds) {
			Role r=userRoleMapper.selectById(roleId);
			String rt=r.getRoleType().toString();
			//咨询角色设置成咨询
			if (rt.equals(AFTConstants.TECH)||rt.equals(AFTConstants.TECH_MANAGER)||rt.equals(AFTConstants.TECH_ADMIN)){
				type=3;
				break;
			//营销角色设置成咨询
			} else if (rt.equals(AFTConstants.SALESMAN)||rt.equals(AFTConstants.SALESMAN_MANAGER)||rt.equals(AFTConstants.SALESMAN_ADMIN)){
				type=1;
				break;
			//财务角色设置成咨询
			}else if (rt.equals(AFTConstants.FINANCE)||rt.equals(AFTConstants.FINANCE_MANAGER)||rt.equals(AFTConstants.FINANCE_ADMIN)){
				type=2;
				break;
			}

		}
		return type;
	}

	@Override
	public int updateByPrimaryKey(Admin a) {
		return adminMapper.update(a);
	}

	@Override
	public AdminDetail selectAdminDetail(String id) {
		Admin a = adminMapper.selectById(id);
		if (null == a) {
			return null;
		}

		AdminDetail ad = new AdminDetail();
		BeanUtils.copyProperties(a, ad);
		ad.setRoles(adminMapper.selectRolesByPrimaryKey(id));
		return null;
	}

	@Override
	public List<Admin> selectCognizanceConsultant() {
		return adminMapper.selectCognizanceConsultant();
	}

	@Override
	public List<Admin> selectPatentAuthor() {
		return adminMapper.selectPatentAuthor();
	}

	@Override
	public List<Admin> selectPatentPrincipal() {
		return adminMapper.selectPatentPrincipal();
	}

	@Override
	public List<Admin> selectCopyrightConsultant() {
		return adminMapper.selectCopyrightConsultant();
	}

	@Override
	public List<Admin> selectCognizancePrincipal() {
		return adminMapper.selectCognizancePrincipal();
	}

	@Override
	public List<Admin> selectCopyrightPrincipal() {
		return adminMapper.selectCopyrightPrincipal();
	}

	@Override
	public List<Admin> selectTechprojectConsultant() {
		return adminMapper.selectTechprojectConsultant();
	}

	@Override
	public List<Admin> selectTechprojectPrincipal() {
		return adminMapper.selectTechprojectPrincipal();
	}

	@Override
	public List<String> selectRoleByPrimaryKey(String uid) {
		return adminMapper.selectRoleByPrimaryKey(uid);
	}

	@Override
	public List<String> listAuditor() {
		return userRoleMapper.listAuditor();
	}

	@Override
	public Map<String, String> selectAccoutManager() {
		return disposeAdminList(adminMapper.selectAccoutManager());
	}

	@Override
	public Map<String, String> selectTechnician() {
		return disposeAdminList(adminMapper.selectTechnician());
	}

	@Override
	public Map<String, String> selectSalesman() {
		return disposeAdminList(adminMapper.selectSalesman());
	}

	@Override
	public Map<String, String> selectContractManager() {
		return disposeAdminList(adminMapper.selectContractManager());
	}

	@Override
	public Map<String, String> selectTechBroder() {
		return disposeAdminList(adminMapper.selectTechBroder());
	}

	@Override
	public int insertNewAdmin(Admin ad ,List<String> roleIds,AdminReviewer adminReviewer) {
		ad.setStatus("0");
		ad.setId(UUID.randomUUID().toString());
		ad.setType(sumType(roleIds));
		if (ad.getPublicPurview()==null)ad.setPublicPurview(0);
		if (ad.getSeniorStaff()==null)ad.setSeniorStaff(0);
		Map<String, Object> params = new HashMap<>();
		params.put("uid", ad.getId());
		params.put("roles", roleIds);

		if (ad.getId() != "1") {
			userRoleMapper.deleteByUserId(ad.getId());
			if (!roleIds.isEmpty()) {
				userRoleMapper.insertBatch(params);
			}
			TokenManager.clearUserAuthByUserId(ad.getId());
		}
		if(ad.getAmbId()!=null)pushAmbRole(ad);
		//修改公出审核人
		updateReviewer(ad, adminReviewer);
		adminMapper.insert(ad);
		return 1;
	}



	/**
	 * 计算巴权限
	 * @param ad
	 */
	private void pushAmbRole(Admin ad) {
		if (ad.getId()!=null){
			ad.setAmbRole("7");
		}else {
			Admin use = adminMapper.selectById(ad.getId());
			AmbSystem ambSystem = ambSystemMapper.selectByPrimaryKey(Long.valueOf(ad.getAmbId()));
			if (ambSystem.getLvl() == 5 || ambSystem.getLvl() == 6) {
				if (use.getAmbRole() == null) {
					ad.setAmbRole("7");
				} else {
					if (!use.getAmbRole().contains("7")) {
						ad.setAmbRole(use.getAmbRole() + ",7");
					}
				}
			}
		}

	}

	@Override
	public Map<String, String> listAdminSelect() {
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			return disposeAdminList(adminMapper.listAdminSelectBySuperAdmin());
		} else if (TokenManager.hasRole(AFTConstants.AREAADMIN)) {
			List<Integer> provinceList = adminLocationMapper
					.selectProvinceWhereCityIsNullByAdminId(TokenManager.getAdminId());
			List<Integer> cityList = adminLocationMapper.selectCityByAdminId(TokenManager.getAdminId());
			provinceList.addAll(cityList);
			return disposeAdminList(adminMapper.listAdminSelectByAreaAdmin(provinceList, cityList));
		}
		return null;
	}

	private Map<String, String> disposeAdminList(List<Admin> list) {
		Map<String, String> map = new TreeMap<String, String>();
		for (Admin o : list) {
			map.put(o.getId(), o.getName() + " " + (StringUtils.isBlank(o.getPosition()) ? "" : o.getPosition()));
		}
		return map;
	}

	@Override
	public List<Admin> listAdminByName(String name) {

		return adminMapper.listAdminByName(name,0);
	}

	@Override
	public Admin selectAllByid(String id) {
		Admin admin=adminMapper.selectAllByid(id);
		return admin;
	}

	@Override
	public int deleteById(String id) {
		adminMapper.deleteById(id);
		if(id!="1"){
			userRoleMapper.deleteByUserId(id);
		}
		return 1;
	}

	@Override
	public List<AdminListBo> selectAdminByOrg() {
		return adminMapper.selectSubList(TokenManager.getAdminId());
	}

	@Override
	public boolean checkAdminRole(List<String> roles, Admin admin) {
		List<UserRole> list=userRoleMapper. selectAdminRole(AFTConstants.CONSULTANT_MANAGER);
		if (!roles.isEmpty()) {
			for (String s : roles) {
				if (list.size()>0) {
					if (null==admin) {
						if (list.get(0).getRid().equals(s)) {
							return true;
						}
					}else {
						if (list.get(0).getRid().equals(s)&&!list.get(0).getUid().equals((admin.getId()))) {
							return true;
						}
					}

				}
			}
		}
		return false;

	}

}
