package com.goafanti.admin.service.impl;

import java.util.*;

import javax.annotation.Resource;

import com.goafanti.admin.service.DepartmentService;
import com.goafanti.admin.service.NewAdminService;
import com.goafanti.common.dao.*;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Department;
import com.goafanti.common.utils.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.admin.bo.AdminContacts;
import com.goafanti.admin.bo.AdminCustomerBo;
import com.goafanti.admin.bo.AdminCustomerDetailBo;
import com.goafanti.admin.bo.AdminDetail;
import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.admin.bo.DepCountBo;
import com.goafanti.admin.service.AdminService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.UserBusiness;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.PasswordUtil;
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 com.goafanti.customer.bo.BusinessListBo;
import com.goafanti.organization.bo.OrganizationListOut;

@Service
public class AdminServiceImpl extends BaseMybatisDao<AdminMapper> implements AdminService {
	@Autowired
	private AdminMapper			adminMapper;
	@Autowired
	private UserRoleMapper		userRoleMapper;
	@Autowired
	private AdminLocationMapper	adminLocationMapper;
	@Autowired
	private UserLockReleaseMapper	userLockReleaseMapper;
	@Autowired
	private UserBusinessMapper	userBusinessMapper;
	@Autowired
	private UserMapper	userMapper;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private DepartmentService departmentService;
	@Resource(name = "passwordUtil")
	private PasswordUtil					passwordUtil;
	@Autowired
	private NewAdminService newAdminService;

	@Autowired
	private RedisUtil	redisUtil;
	@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.selectByPrimaryKey(key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AdminListBo> listAdmin(Integer province, Integer number, String mobile, String name,String roleName,Integer seniorStaff,
			Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(roleName))params.put("roleName", roleName);
		if (StringUtils.isNotBlank(mobile))params.put("mobile", mobile);
		if (StringUtils.isNotBlank(name))params.put("name", name);
		if (null != number)params.put("number", number);
		if (null != seniorStaff)params.put("seniorStaff", seniorStaff);
		if (pageNo == null || pageNo < 0)pageNo = 1;
		if (pageSize == null || pageSize < 0 || pageSize > 10)pageSize = 10;
		if (province != null) params.put("province", province);
		return (Pagination<AdminListBo>) findPage("findAdminListByPage", "findAdminCount", params, pageNo,
					pageSize);
	}

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

	@Override
	public int updateByPrimaryKeySelective(Admin ad, List<String> roleIds) {
		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());
		}
		return adminMapper.updateByPrimaryKeySelective(ad);
	}

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

	@Override
	public AdminDetail selectAdminDetail(String id) {
		Admin a = adminMapper.selectByPrimaryKey(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) {
		return adminMapper.insert(ad);
	}

	@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());
		}
		return map;
	}

	@Override
	public List<Admin> listAdminByName(String name,Integer status) {
		if(status==null)status=0;
		return adminMapper.listAdminByName(name,status);
	}

	@Override
	public List<AdminListBo> selectDepartmentStaff(String departmentId, String name) {

		return adminMapper.selectDepartmentStaff( departmentId,  name);
	}

	@Override
	public int updateLockAdmin() {
		int count=0;
		List<Admin> list=adminMapper.selectAllAdmin(null);//获取所有用户
		List<List<Admin>>aList=groupList(list);//拆分成多个
		String lockIds = "";
		for(List<Admin> al:aList){
			for (Admin a : al) {
				String pwd=a.getPassword();
				a.setPassword("123456");
				String pwd2=passwordUtil.getEncryptPwd(a);
				if (pwd.equals(pwd2)) {
					lockIds += a.getId() + ",";
				}
			}
			if(lockIds.length()>0){
				try {
				lockIds = "'" + lockIds.substring(0,lockIds.length()-1).replace(",", "','") + "'";
				count+= adminMapper.updateLockIds(lockIds);
				lockIds = "";
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					LoggerUtils.error(getClass(), "未修改管理员锁定失败", e);
				}
			}
		}
		return count;
	}

	  /*
     * List分割
     */
    public  List<List<Admin>> groupList(List<Admin> list) {
        List<List<Admin>> listGroup = new ArrayList<List<Admin>>();
        int listSize = list.size();
        //子集合的长度
        int toIndex = 100;
        for (int i = 0; i < list.size(); i += toIndex) {
            if (i + toIndex > listSize) {
                toIndex = listSize - i;
            }
            List<Admin> newList = list.subList(i, i + toIndex);
            listGroup.add(newList);
        }
        return listGroup;
    }


	@Override
	public List<Admin> getListDefaultPassword(String depId) {
		List<Admin> list=adminMapper.selectAllAdmin(depId);
		List<Admin> list2=new ArrayList<>();
		for (Admin a : list) {
			String pwd=a.getPassword();
			a.setPassword("123456");
			String pwd2=passwordUtil.getEncryptPwd(a);
			if (pwd.equals(pwd2)) {
				list2.add(a);
			}
		}
		return list2;
	}

	@Override
	public List<Admin> getAdminRoleList(String roleName) {
		return adminMapper.getAdminRoleNameList(roleName);
	}

	@Override
	public int addFrequentContacts(String id) {
		String []ss=id.split(",");
		List<String> list=adminMapper.getaidFrequentContacts(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		for (String s : ss) {
			boolean flag=true;
			for (String s2 : list) {
				if (s.equals(s2)) {
					flag=false;
				}
			}
			if (flag) {
				AdminContacts a=new AdminContacts();
				a.setId(UUID.randomUUID().toString());
				a.setAid(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
				a.setContactsId(s);
				adminMapper.addAdminContacts(a);
			}
		}
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AdminListBo> frequentContactsList(String deps, String name,String roleName, Integer pageSize, Integer pageNo) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if (StringUtils.isNotBlank(deps)){
			params.put("depId", departmentService.parseArray(deps));
		}
		if (StringUtils.isNotBlank(name)) params.put("name", name);
		if (StringUtils.isNotBlank(roleName)) params.put("roleName", roleName);
		params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		Pagination<AdminListBo> p = (Pagination<AdminListBo>)findPage("frequentContactsList", "frequentContactsCount", params, pageNo, pageSize);
		List<AdminListBo> list=(List<AdminListBo>)p.getList();
		for(AdminListBo i:list){
			newAdminService.pushRolesName(i);

		}
		return p;
	}

	@Override
	public int deleteFrequentContacts(String id) {
		return adminMapper.deleteFrequentContacts(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AdminCustomerBo> selectAdminCustomerStatistics(String depId, String startTime, String endTime, Integer pageSize, Integer pageNo) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if (StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if (StringUtils.isNotBlank(startTime)) params.put("startTime", startTime);
		if (StringUtils.isNotBlank(endTime)) params.put("endTime", endTime+" 23:59:59");
		return (Pagination<AdminCustomerBo>)findPage("selectAdminCustomerList", "selectAdminCustomerCount", params, pageNo, pageSize);
	}
	@Override
	public DepCountBo selectAllUser(String depId, String startTime, String endTime,String aName) {
		DepCountBo acb=new DepCountBo();
		if (endTime!=null)endTime=endTime+" 23:59:59";
		List<DepCountBo >deps=new ArrayList<>();
		List<Department> depIds=new ArrayList<>();
		//总裁助力不查看老员工
		Integer seniorstaff = null;
		if (TokenManager.hasRole(AFTConstants.CED_ASSISTANT)){
			seniorstaff=0;
		}

		if (depId==null) {
			acb.setName("科德集团");
			deps=departmentMapper.selectBysuperName("科德集团");
		}else {
			OrganizationListOut oo=departmentMapper.selectAllById(depId);
			acb.setName(oo.getName());
			acb.setId(depId);
			if(TokenManager.hasRole(AFTConstants.OPERATION_MANAGER)){
				List<String> myShiroDep = departmentService.selectMyDeps();
				if (!myShiroDep.contains(depId))throw new BusinessException("无权查看此部门信息");
			}
			depIds =departmentService.selectSubordinateDeps(depId);
			Department department = new Department();
			department.setId(depId);
			depIds.add(department);
			deps=departmentMapper.selectBysuperId(oo.getId());
		}
		List<AdminCustomerBo> list =null;
		//原sql计算
//		list=departmentMapper.AlldepCount(depIds,startTime,  endTime);
		//新java计算
		list=AllDepCount(depIds,startTime,endTime,seniorstaff);
		for (AdminCustomerBo ad : list) {
			if (acb.getId().equals(ad.getDepId())){
				acb.getaList().add(ad);
			}
		}
		for (DepCountBo dep : deps) {
			dep.setList(iterationDeps(dep.getId(),list));
			for (AdminCustomerBo ad : list) {
				if (dep.getId().equals(ad.getDepId())){
					dep.getaList().add(ad);
				}
				sumCount(dep);
			}
		}
		acb.setList(deps);
		sumCount(acb);
		return acb;
	}

	private List<AdminCustomerBo> AllDepCount(List<Department> depIds, String startTime, String endTime,Integer seniorStaff) {
		List<AdminCustomerBo> admins = adminMapper.selectByDeps(depIds,seniorStaff);
		if(!admins.isEmpty()){
			List<AdminCustomerBo> users = 	userMapper.selectNoChannelByaids(admins,startTime,endTime);
			List<AdminCustomerBo> users2 = 	userMapper.selectChannelByaids(admins,startTime,endTime);
			for (AdminCustomerBo admin : admins) {
				for (AdminCustomerBo user : users) {
					if (admin.getAid().equals(user.getAid())){
						admin.setUserCount(user.getUserCount());
						admin.setChannelCount(user.getChannelCount());
						admin.setSignCount(user.getSignCount());
						admin.setNewCount(user.getNewCount());
						admin.setChannelNewCount(user.getChannelNewCount());
						admin.setReceiveCount(user.getReceiveCount());
						break;
					}
				}
				for (AdminCustomerBo user : users2) {
					if (admin.getAid().equals(user.getAid())){
						admin.setCompleteCount(user.getCompleteCount());
						admin.setChannelCompleteCount(user.getChannelCompleteCount());
						break;
					}
				}
				pushAdminCount(admin);
			}
		}
		return admins;
	}

	private void pushAdminCount(AdminCustomerBo admin) {
		if (admin.getUserCount()==null) admin.setUserCount(0);
		if (admin.getChannelCount()==null) admin.setChannelCount(0);
		if (admin.getSignCount()==null) admin.setSignCount(0);
		if (admin.getNewCount()==null) admin.setNewCount(0);
		if (admin.getChannelNewCount()==null) admin.setChannelNewCount(0);
		if (admin.getReceiveCount()==null) admin.setReceiveCount(0);
		if (admin.getCompleteCount()==null) admin.setCompleteCount(0);
		if (admin.getChannelCompleteCount()==null) admin.setChannelCompleteCount(0);
	}

	//迭代获取所有部门与部门员工并计算出部门数量
	public List<DepCountBo> iterationDeps(String id,List<AdminCustomerBo> list) {
		List<DepCountBo>  deps =departmentMapper.selectBysuperId(id);
		for (DepCountBo dep : deps) {
			dep.setList(iterationDeps(dep.getId(),list));
			for (AdminCustomerBo ad : list) {
				if (dep.getId().equals(ad.getDepId())){
					dep.getaList().add(ad);
				}
			}
			sumCount(dep);
		}
    	return deps;
	}

	/**
	 *
	 * @param ab
	 */
	public void sumCount(DepCountBo ab) {
		int completeCount=0,receiveCount=0,userCount=0,signCount=0,channelCount=0,newCount=0,channelNewCount=0,channelCompleteCount=0;
		if (ab.getList()!=null&&!ab.getList().isEmpty()) {
			for (DepCountBo a : ab.getList()) {
				if (a.getCompleteCount()!=null&& a.getCompleteCount()!=0) completeCount+=a.getCompleteCount();
				if (a.getReceiveCount()!=null&& a.getReceiveCount()!=0) receiveCount+=a.getReceiveCount();
				if (a.getUserCount()!=null&& a.getUserCount()!=0) userCount+=a.getUserCount();
				if (a.getSignCount()!=null&& a.getSignCount()!=0) signCount+=a.getSignCount();
				if (a.getChannelCount()!=null&& a.getChannelCount()!=0) channelCount+=a.getChannelCount();
				if (a.getNewCount()!=null&& a.getNewCount()!=0) newCount+=a.getNewCount();
				if (a.getChannelNewCount()!=null&& a.getChannelNewCount()!=0) channelNewCount+=a.getChannelNewCount();
				if (a.getChannelCompleteCount()!=null&& a.getChannelCompleteCount()!=0) channelCompleteCount+=a.getChannelCompleteCount();
			}
		}
		if (ab.getaList()!=null&&!ab.getaList().isEmpty()) {
			for (AdminCustomerBo a : ab.getaList()) {
				if (a.getCompleteCount()!=null&& a.getCompleteCount()!=0) completeCount+=a.getCompleteCount();
				if (a.getReceiveCount()!=null&& a.getReceiveCount()!=0) receiveCount+=a.getReceiveCount();
				if (a.getUserCount()!=null&& a.getUserCount()!=0) userCount+=a.getUserCount();
				if (a.getSignCount()!=null&& a.getSignCount()!=0) signCount+=a.getSignCount();
				if (a.getChannelCount()!=null&& a.getChannelCount()!=0) channelCount+=a.getChannelCount();
				if (a.getNewCount()!=null&& a.getNewCount()!=0) newCount+=a.getNewCount();
				if (a.getChannelNewCount()!=null&& a.getChannelNewCount()!=0) channelNewCount+=a.getChannelNewCount();
				if (a.getChannelCompleteCount()!=null&& a.getChannelCompleteCount()!=0) channelCompleteCount+=a.getChannelCompleteCount();
			}
		}
		ab.setCompleteCount(completeCount);
		ab.setReceiveCount(receiveCount);
		ab.setUserCount(userCount);
		ab.setSignCount(signCount);
		ab.setChannelCount(channelCount);
		ab.setNewCount(newCount);
		ab.setChannelNewCount(channelNewCount);
		ab.setChannelCompleteCount(channelCompleteCount);

	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AdminCustomerDetailBo> selectAdminCustomerList(String aid, String startTime, String endTime,Integer type,
			Integer pageSize, Integer pageNo) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if (StringUtils.isNotBlank(aid)) params.put("aid", aid);
		if (type==null) params.put("type", 0);
		else  params.put("type", type);
		if (StringUtils.isNotBlank(startTime)) params.put("startTime", startTime);
		if (StringUtils.isNotBlank(endTime)) params.put("endTime", endTime+" 23:59:59");
		Pagination<AdminCustomerDetailBo> p =(Pagination<AdminCustomerDetailBo>)findPage("selectAdminCustomerDetailList", "selectAdminCustomerDetailCount", params, pageNo, pageSize);
		if (type == 2&& !TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			List<AdminCustomerDetailBo> list = (List<AdminCustomerDetailBo>) p.getList();
			for (AdminCustomerDetailBo out : list) {
				out.setContacts("***");
				out.setContactMobile("***");
			}
		}
		return p;
	}

	@Override
	public int updatePrivateBusinessTransfer(String inputId, String uid, String pid) {
		String aid=TokenManager.getAdminId();
		int i=userLockReleaseMapper.updatePrivateBusinessTransfer( inputId,  uid,  pid,aid);
		if (i>0) {
			List<BusinessListBo> l=userBusinessMapper.selectBusinessProjectByUAPid(uid, inputId, pid);
			if (l.isEmpty()) {
				UserBusiness ub=new UserBusiness();
				ub.setId(UUID.randomUUID().toString());
				ub.setAid(inputId);
				ub.setUid(uid);
				ub.setBusinessProjectId(pid);
				ub.setCustomerStatus(4);
				ub.setFollowSituation(5);
				ub.setRemarks("转交客户业务触发");
				userBusinessMapper.insertSelective(ub);
			}
		}
		return i;
	}





}
