package com.goafanti.admin.service.impl;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.admin.bo.AdminDetail;
import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.admin.service.NewAdminService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.AdminLocationMapper;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.model.Admin;
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;

@Service
public class NewAdminServiceImpl extends BaseMybatisDao<AdminMapper> implements NewAdminService {
	@Autowired
	private AdminMapper			adminMapper;
	@Autowired
	private UserRoleMapper		userRoleMapper;
	@Autowired
	private AdminLocationMapper	adminLocationMapper;
	
	@Override
	public Pagination<AdminListBo> listAdmin(AdminListBo alb, String rid, 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(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());		
		@SuppressWarnings("unchecked")
		Pagination<AdminListBo> p=(Pagination<AdminListBo>)findPage("selectAdminListByPage","selectAdminCount",params,pageNo,pageSize);
		@SuppressWarnings("unchecked")
		List<AdminListBo> list=(List<AdminListBo>)p.getList();
		for(AdminListBo i:list){
			i.setRoles(adminMapper.selectRolesByUid(i.getId()));
			i.setRolesId(adminMapper.selectRolesIdByUid(i.getId()));
		}
		return p;
	}
	
	@Override
	public List<Admin> selectAllAdmin() {
		return adminMapper.selectAllAdmin();
	}

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

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

	@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());
		}
			
		int count=adminMapper.updateByPrimaryKeySelective(ad);
		//*******下第一级管理员用户修改
		String autNo;
		int n=0;
		List<Admin> Nos =adminMapper.selectIDNBySuperiorId(ad.getId());
		for(Admin i:Nos){			
			autNo=adminMapper.selectUserNoById(i.getSuperiorId());
			if(n<10){
				String aut=autNo+"0"+n;			
				if(n>=10){
					aut=autNo+n;	
				}else{
					aut=autNo+"0"+n;
				}	
				i.setUserNo(aut);
			}
			if(n>=10){
				String aut=autNo+n;			
				aut=autNo+n;	
				i.setUserNo(aut);
			}
			adminMapper.updateByUserNo(i);
			n++;
			//*******下第二级管理员用户修改
			int m=0;
			List<Admin> Noss =adminMapper.selectIDNBySuperiorId(i.getId());
			for(Admin o:Noss){			
				autNo=adminMapper.selectUserNoById(o.getSuperiorId());
				if(m<10){
					String aut=autNo+"0"+m;			
					if(m>=10){
						aut=autNo+m;	
					}else{
						aut=autNo+"0"+m;
					}	
					o.setUserNo(aut);
				}
				if(m>=10){
					String aut=autNo+m;			
					aut=autNo+m;	
					o.setUserNo(aut);
				}
				adminMapper.updateByUserNo(o);
				m++;
				//*******下第三级管理员用户修改
				int z=0;
				List<Admin> Nosss =adminMapper.selectIDNBySuperiorId(o.getId());
				for(Admin p:Nosss){			
					autNo=adminMapper.selectUserNoById(p.getSuperiorId());
					if(z<10){
						String aut=autNo+"0"+z;			
						if(z>=10){
							aut=autNo+z;	
						}else{
							aut=autNo+"0"+z;
						}	
						p.setUserNo(aut);
					}
					if(z>=10){
						String aut=autNo+z;			
						aut=autNo+z;	
						p.setUserNo(aut);
					}
					adminMapper.updateByUserNo(p);
					z++;
				}
			}
		}
		return count;
	}

	@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 ,List<String> roleIds) {
		ad.setStatus("正常");		
		String sdepNo=adminMapper.selectUserNoBySuperiorId(ad.getSuperiorId());
		int Count=adminMapper.selectCountBySuperiorId(ad.getSuperiorId());
		if(Count<10){
			String dep=sdepNo+"0"+Count;
			String sid=adminMapper.selectIdByUserNo(dep);
			while(sid!=null){
				Count=Count+1;				
				if(Count>=10){
					dep=sdepNo+Count;	
				}else{
					dep=sdepNo+"0"+Count;
				}
				sid=adminMapper.selectIdByUserNo(dep);				
			}
			ad.setUserNo(dep);
		}
		if(Count>=10){
			String dep=sdepNo+Count;
			String sid=adminMapper.selectIdByUserNo(dep);
			while(sid!=null){
				Count=Count+1;				
				dep=sdepNo+Count;
				sid=adminMapper.selectIdByUserNo(dep);				
			}
			ad.setUserNo(dep);
		}		
		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.insertn(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() + " " + (StringUtils.isBlank(o.getPosition()) ? "" : o.getPosition()));
		}
		return map;
	}

	@Override
	public List<Admin> listAdminByName(String name) {
		
		return adminMapper.listAdminByName(name);
	}

	@Override
	public Admin selectAllByid(String id) {
		Admin admin=adminMapper.selectAllByid(id);
		admin.setSuperior(adminMapper.selectNameByid(admin.getSuperiorId()));
		if(admin.getDistrict()==null){
			admin.setDistrict(" ");
		}
		if(admin.getHeadPortraitUrl()==null){
			admin.setHeadPortraitUrl("");
		}
		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());
	}

}
