package com.goafanti.admin.service.impl;

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

import javax.annotation.Resource;

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.dao.AdminLocationMapper;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.OrganizationManagementMapper;
import com.goafanti.common.dao.UserBusinessMapper;
import com.goafanti.common.dao.UserLockReleaseMapper;
import com.goafanti.common.dao.UserRoleMapper;
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 OrganizationManagementMapper	organizationManagementMapper;
	@Resource(name = "passwordUtil")
	private PasswordUtil					passwordUtil;
	
	@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 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 (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) {
		
		return adminMapper.listAdminByName(name);
	}

	@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.getAdminRoleList(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 depId, 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(depId)) params.put("depId", depId);
		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){
			i.setRoles(adminMapper.selectRolesByUid(i.getContactId()));
		}
		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();
		List<depCountBo >deps=new ArrayList<>();
		if (depId==null) {
			acb.setName("科德集团");
//			organizationManagementMapper.getDepAll("科德集团",null,startTime,  endTime);
			deps=organizationManagementMapper.selectBysuperName("科德集团");
			
		}else {
			OrganizationListOut oo=organizationManagementMapper.selectAllById(depId);
			acb.setName(oo.getName());
			deps=organizationManagementMapper.selectBysuperName(acb.getName());
		}
		acb.setCompleteCount(0);
		acb.setInputCount(0);
		acb.setInterviewCount(0);
		acb.setReceiveCount(0);
		acb.setUserCount(0);
		//迭代查出所有层级并计算
		acb.setList(nestingList(deps,startTime,  endTime,aName));
		//计算顶层
		acb.setaList(organizationManagementMapper.getDepAll(acb.getName(),null,aName,startTime,  endTime));
		sumCount(acb,0);
		return acb;
	}

	private List<depCountBo> nestingList(List<depCountBo>deps,String startTime, String endTime,String name) {
		List<depCountBo> res=new ArrayList<>();
		//循环取出其中
		for (depCountBo ab : deps) {
			//找出每一个部门的直部门，并嵌套下去，先获取然后将
			List<depCountBo >deps2=organizationManagementMapper.selectBysuperName(ab.getName());
			//查找所有部门的人的信息
			List<AdminCustomerBo> aList=organizationManagementMapper.getDepAll(ab.getName(),null,name,startTime,  endTime);
			ab.setList(nestingList(deps2,startTime,  endTime,name));
			ab.setaList(aList);
			//计算总数
			sumCount(ab,1);
			if (ab.getCompleteCount()!=0||ab.getInputCount()!=0||ab.getInterviewCount()!=0
					||ab.getReceiveCount()!=0||ab.getUserCount()!=0) {
				res.add(ab);
			}
		}
		return res;
	}
	/**
	 * 
	 * @param ab
	 * @param type 0 部门计算 1人员计算
	 */
	private void sumCount(depCountBo ab,int type ) {
		int completeCount=0,inputCount=0,interviewCount=0,receiveCount=0,userCount=0;
		if (ab.getList()!=null&&!ab.getList().isEmpty()) {
			for (depCountBo a : ab.getList()) {
				if ( a.getCompleteCount()!=0) completeCount+=a.getCompleteCount();
				if ( a.getInputCount()!=0) inputCount+=a.getInputCount();
				if ( a.getInterviewCount()!=0) interviewCount+=a.getInterviewCount();
				if ( a.getReceiveCount()!=0) receiveCount+=a.getReceiveCount();
				if ( a.getUserCount()!=0) userCount+=a.getUserCount();
			}
		}
		if (ab.getaList()!=null&&!ab.getaList().isEmpty()) {
			for (AdminCustomerBo a : ab.getaList()) {
				if ( a.getCompleteCount()!=0) completeCount+=a.getCompleteCount();
				if ( a.getInputCount()!=0) inputCount+=a.getInputCount();
				if ( a.getInterviewCount()!=0) interviewCount+=a.getInterviewCount();
				if ( a.getReceiveCount()!=0) receiveCount+=a.getReceiveCount();
				if ( a.getUserCount()!=0) userCount+=a.getUserCount();
			}
		}
		ab.setCompleteCount(completeCount);
		ab.setInputCount(inputCount);
		ab.setInterviewCount(interviewCount);
		ab.setReceiveCount(receiveCount);
		ab.setUserCount(userCount);
	}

	@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");
		return (Pagination<AdminCustomerDetailBo>)findPage("selectAdminCustomerDetailList", "selectAdminCustomerDetailCount", params, pageNo, pageSize);
	}

	@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;
	}



	
	
}
