package com.goafanti.admin.service.impl;

import com.goafanti.admin.bo.*;
import com.goafanti.admin.service.AdminService;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.admin.service.NewAdminService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.Department;
import com.goafanti.common.model.FinanceCount;
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.common.utils.excel.NewExcelUtil;
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;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@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 TOrderNewMapper TOrderNewMapper;
	@Autowired
	private ExpenseAccountMapper expenseAccountMapper;
	@Autowired
	private TOrderInvoiceMapper tOrderInvoiceMapper;
	@Autowired
	private TTaskMemberMapper tTaskMemberMapper;
	@Autowired
	private TOrderPaymentMapper tOrderPaymentMapper;
	@Autowired
	private FinanceCountMapper financeCountMapper;

	@Value(value = "${upload.path}")
	private String uploadPath = null;




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

	@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.update(ad);
	}

	@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) {
		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 (StringUtils.isBlank(startTime))startTime=null;
		if (StringUtils.isBlank(endTime)){
			endTime = null;
		}else {
			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);
			List<AdminCustomerBo> users3 = userMapper.selectFirstInterviewByaids(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());
						admin.setTransferCount(user.getTransferCount());
						admin.setIntentionCount(user.getIntentionCount());
						admin.setKeynoteCount(user.getKeynoteCount());
						admin.setGeneralCount(user.getGeneralCount());
						admin.setPrivateCount(user.getPrivateCount());
						break;
					}
				}
				for (AdminCustomerBo user : users2) {
					if (admin.getAid().equals(user.getAid())){
						admin.setCompleteCount(user.getCompleteCount());
						admin.setChannelCompleteCount(user.getChannelCompleteCount());
						break;
					}
				}
				for (AdminCustomerBo user : users3) {
					if (admin.getAid().equals(user.getAid())){
						admin.setFirstInterviewCount(user.getFirstInterviewCount());
						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);
		if (admin.getTransferCount()==null)admin.setTransferCount(0);
		if (admin.getIntentionCount()==null)admin.setIntentionCount(0);
		if (admin.getKeynoteCount()==null)admin.setKeynoteCount(0);
		if (admin.getGeneralCount()==null)admin.setGeneralCount(0);
		if (admin.getFirstInterviewCount()==null)admin.setFirstInterviewCount(0);
		if (admin.getPrivateCount()==null)admin.setPrivateCount(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,transferCount=0,intentionCount=0,keynoteCount=0,generalCount=0,
				firstInterviewCount=0,privateCount=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 (a.getTransferCount()!=null&& a.getTransferCount()!=0)transferCount+=a.getTransferCount();
				if (a.getIntentionCount()!=null&& a.getIntentionCount()!=0) intentionCount+=a.getIntentionCount();
				if (a.getKeynoteCount()!=null&& a.getKeynoteCount()!=0) keynoteCount+=a.getKeynoteCount();
				if (a.getGeneralCount()!=null&& a.getGeneralCount()!=0) generalCount=a.getGeneralCount();
				if (a.getFirstInterviewCount()!=null&& a.getFirstInterviewCount()!=0) firstInterviewCount+=a.getFirstInterviewCount();
				if (a.getPrivateCount()!=null&& a.getPrivateCount()!=0) privateCount+=a.getPrivateCount();
			}
		}
		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();
				if (a.getTransferCount()!=null&& a.getTransferCount()!=0)transferCount+=a.getTransferCount();
				if (a.getIntentionCount()!=null&& a.getIntentionCount()!=0) intentionCount+=a.getIntentionCount();
				if (a.getKeynoteCount()!=null&& a.getKeynoteCount()!=0) keynoteCount+=a.getKeynoteCount();
				if (a.getGeneralCount()!=null&& a.getGeneralCount()!=0) generalCount=a.getGeneralCount();
				if (a.getFirstInterviewCount()!=null&& a.getFirstInterviewCount()!=0) firstInterviewCount+=a.getFirstInterviewCount();
				if (a.getPrivateCount()!=null&& a.getPrivateCount()!=0) privateCount+=a.getPrivateCount();
			}
		}
		ab.setCompleteCount(completeCount);
		ab.setReceiveCount(receiveCount);
		ab.setUserCount(userCount);
		ab.setSignCount(signCount);
		ab.setChannelCount(channelCount);
		ab.setNewCount(newCount);
		ab.setChannelNewCount(channelNewCount);
		ab.setChannelCompleteCount(channelCompleteCount);
		ab.setTransferCount(transferCount);
		ab.setIntentionCount(intentionCount);
		ab.setKeynoteCount(keynoteCount);
		ab.setGeneralCount(generalCount);
		ab.setFirstInterviewCount(firstInterviewCount);
		ab.setPrivateCount(privateCount);
	}

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


	@Override
	public Object pushStatistics() {
//营销统计处理
//		List<String> roles=new ArrayList<>();
//		roles.add(AFTConstants.SALESMAN);
//		roles.add(AFTConstants.SALESMAN_MANAGER);
//		List<Admin> adminList = adminMapper.getAdminRoleTypesList(roles);
//		for (Admin admin : adminList) {
//		List<AdminUserCount> list =adminMapper.selectAdminPublicRelease(admin.getId());
//		List<AdminUserCount> list2 =adminMapper.selectAdminUserFollow(admin.getId());
//		List<AdminUserCount> list3 =adminMapper.selectAdminOrder(admin.getId());
//		if (list.isEmpty())list=new ArrayList<>();
//		if (!list.isEmpty())list.addAll(list2);
//		if (!list.isEmpty())list.addAll(list3);
//		publiAdminUserCount(list);
//		System.out.println("list="+list.size());
//		}
//咨询师统计处理
//		List<TOrderTask> allTimeRecord = taskTimeMapper.getAllTimeRecord();
//		List<TaskTime> list=new ArrayList<>();
//		for (TOrderTask e : allTimeRecord) {
//			String timeRecord = e.getTimeRecord();
//			System.out.println(e.getTimeRecord());
//			if (StringUtils.isNotBlank(e.getTimeRecord())){
//				Map<String,Object> map = JSON.parseObject(timeRecord, Map.class);
//				for (String s : map.keySet()) {
//					if (s.equals("2")||s.equals("3")||s.equals("29")||s.equals("19")||(s.equals("27"))){
//						JSONObject js = JSON.parseObject(map.get(s).toString());
//						Object date = js.get("date");
//						Object suspendImg  = js.get("suspendImg") ;
//						Object title = js.get("title") ;
//						Object certificateNumber = js.get("certificateNumber") ;
//						Object setUpAmount = js.get("setUpAmount") ;
//						Object appropriation = js.get("appropriation") ;
//						TaskTime tt=new TaskTime();
//						tt.setTid(e.getId());
//						tt.setProjectStatus(Integer.parseInt(s));
//						if (!Objects.isNull(date)){
//							String dates=date.toString();
//							if (StringUtils.isNotBlank(dates)){
//								Date date1 = DateUtils.StringToDate(dates, AFTConstants.YYYYMMDD);
//								tt.setDateTime(date1);
//							}
//						}
//						if (!Objects.isNull(setUpAmount))tt.setSetUpAmount(setUpAmount.toString());
//						if (!Objects.isNull(suspendImg))tt.setSuspendImg(suspendImg.toString());
//						if (!Objects.isNull(title))tt.setTitle(title.toString());
//						if (!Objects.isNull(certificateNumber))tt.setCertificateNumber(certificateNumber.toString());
//						if (!Objects.isNull(appropriation))tt.setAppropriation(appropriation.toString());
//						list.add(tt);
////					taskTimeMapper.insertSelective(tt);
//					}
//				}
//			}
//		}
//		List<TaskTime> addList = new ArrayList<>();
//		for (int i = 0; i <list.size(); i++) {
//			addList.add(list.get(i));
//			if (addList.size()==50|| i==list.size() -1){
//				taskTimeMapper.insertBatch(addList);
//				try {
//					addList.clear();
//					Thread.sleep(500);
//				} catch (InterruptedException exception) {
//					exception.printStackTrace();
//				}
//			}
//		}
		List<String> roles=new ArrayList<>();
		roles.add(AFTConstants.FINANCE);
		roles.add(AFTConstants.FINANCE_MANAGER);
		List<Admin> admins = adminMapper.selectAdminByRoleTypes(roles);
		List<FinanceCount> list=new ArrayList<>();
		for (Admin admin : admins){
			List<FinanceCount> aList=new ArrayList<>();
			List<FinanceCount> orderList = TOrderNewMapper.selectCountByFinance(admin.getId());
			if (!orderList.isEmpty()){
				aList.addAll(orderList);
			}
			List<FinanceCount> expenseList = expenseAccountMapper.selectCountByFinance(admin.getId());
			pushFinanceList(aList, expenseList,0);
			List<FinanceCount> invoiceList =tOrderInvoiceMapper.selectCountByFinance(admin.getId());
			pushFinanceList(aList, invoiceList,1);
			List<FinanceCount> memberList =tTaskMemberMapper.selectCountByFinance(admin.getId());
			pushFinanceList(aList, memberList,2);
			List<FinanceCount> paymentList =tOrderPaymentMapper.selectCountByFinance(admin.getId());
			pushFinanceList(aList, paymentList,3);
			if (!aList.isEmpty()){
				for (FinanceCount financeCount : aList) {
					if (financeCount.getExpenseCount()!=null&&financeCount.getExpenseCount()>0){
						financeCount.toString();
					}
				}
			}
			list.addAll(aList);
		}
		List<FinanceCount> addList=new ArrayList<>();
		for (int i = 0; i <list.size(); i++) {
			FinanceCount financeCount = list.get(i);
			FinanceCount newFc=FinanceCount.initialization(financeCount);
			addList.add(newFc);
			if (addList.size()==50||i==list.size()-1){
				financeCountMapper.insetBatch(addList);
				addList.clear();
				try {
					Thread.sleep(500);
				} catch (InterruptedException exception) {
					exception.printStackTrace();
				}
			}
		}
		return 1;
	}

	@Override
	public Result selectAllUserExport(String depId, String startTime, String endTime, String aName) {
		if(TokenManager.hasRole(AFTConstants.OPERATION_MANAGER)){
			List<String> myShiroDep = departmentService.selectMyDeps();
			if (!myShiroDep.contains(depId))throw new BusinessException("无权查看此部门信息");
		}
		DepCountBo depCountBo = selectAllUser(depId, startTime, endTime, aName);
		List<AdminCustomerBo> adminCustomerBos =pushSelectAllUser(depCountBo);
		NewExcelUtil excel=new NewExcelUtil(AdminCustomerBo.class);
		String sheetName=String.format("部门统计表_%s~%s",startTime,endTime);
		return excel.exportExcel(adminCustomerBos,sheetName,uploadPath);
	}

	private List<AdminCustomerBo> pushSelectAllUser(DepCountBo depCountBo) {
		List<AdminCustomerBo> list = new ArrayList<>();
		if (!depCountBo.getaList().isEmpty()){
			list.addAll(depCountBo.getaList());
		}
		iterDeps(list,depCountBo.getList());
		return list;
	}

	private void iterDeps(List<AdminCustomerBo> list, List<DepCountBo> list1) {
		for (DepCountBo e : list1) {
			if (!e.getaList().isEmpty()){
				list.addAll(e.getaList());
			}
			if (!e.getList().isEmpty()){
				iterDeps(list,e.getList());
			}
		}
	}

	/**
	 *
	 * @param list
	 * @param minList
	 * @param type
	 */
	private void pushFinanceList(List<FinanceCount> list, List<FinanceCount> minList,Integer type) {
		if (!minList.isEmpty()){
			for (FinanceCount expense : minList) {
				boolean flag=true;
				for (FinanceCount e : list) {
					if (e.getDateTime().getTime()==expense.getDateTime().getTime()){
						if (type==0){
							e.setExpenseCount(expense.getExpenseCount());
							e.setExpenseUnauditedCount(expense.getExpenseUnauditedCount());
						}else if (type==1){
							e.setInvoiceCount(expense.getInvoiceCount());
							e.setInvoiceUnauditedCount(expense.getInvoiceUnauditedCount());
						}else if (type==2){
							e.setMemberCount(expense.getMemberCount());
							e.setMemberUnauditedCount(expense.getMemberUnauditedCount());
						}else if (type==3){
							e.setPaymentCount(expense.getPaymentCount());
							e.setPaymentUnauditedCount(expense.getPaymentUnauditedCount());
						}
						flag=false;
					}
				}
				if (flag){
					list.add(expense);
				}
			}
		}
	}




}
