package com.yeejoin.precontrol.common.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
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 org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.CompanyDepartmentDto;
import com.yeejoin.precontrol.common.dto.CompanyDto;
import com.yeejoin.precontrol.common.dto.CompanyImportDto;
import com.yeejoin.precontrol.common.dto.StatisticsDto;
import com.yeejoin.precontrol.common.dto.TeamDto;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.CompanyAcount;
import com.yeejoin.precontrol.common.entity.CompanyBusiness;
import com.yeejoin.precontrol.common.entity.CompanyBusinessAttachment;
import com.yeejoin.precontrol.common.entity.CompanyDepartment;
import com.yeejoin.precontrol.common.entity.CompanyProjectJobStatus;
import com.yeejoin.precontrol.common.entity.CompanyQualifications;
import com.yeejoin.precontrol.common.entity.CompanyQualificationsAttachment;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectCompany;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.mapper.CompanyBusinessAttachmentMapper;
import com.yeejoin.precontrol.common.mapper.CompanyBusinessMapper;
import com.yeejoin.precontrol.common.mapper.CompanyMapper;
import com.yeejoin.precontrol.common.mapper.CompanyQualificationsAttachmentMapper;
import com.yeejoin.precontrol.common.mapper.CompanyQualificationsMapper;
import com.yeejoin.precontrol.common.mapper.DistrictsMapper;
import com.yeejoin.precontrol.common.mapper.StatisticsMapper;
import com.yeejoin.precontrol.common.param.CompanyParam;
import com.yeejoin.precontrol.common.publish.TranslateEventPublish;
import com.yeejoin.precontrol.common.service.IBaseService;
import com.yeejoin.precontrol.common.service.ICompanyAcountService;
import com.yeejoin.precontrol.common.service.ICompanyBusinessAttachmentService;
import com.yeejoin.precontrol.common.service.ICompanyBusinessService;
import com.yeejoin.precontrol.common.service.ICompanyDepartmentService;
import com.yeejoin.precontrol.common.service.ICompanyQualificationAttachmentService;
import com.yeejoin.precontrol.common.service.ICompanyQualificationService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IDistrictsService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectCompanyService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.DistrictsUtils;
import com.yeejoin.precontrol.common.utils.EasyPoiUtil;
import com.yeejoin.precontrol.common.utils.PlatformUtils;
import com.yeejoin.precontrol.common.utils.RedisUtil;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.BadCompanyVo;
import com.yeejoin.precontrol.common.vo.CompanyExcelVo;
import com.yeejoin.precontrol.common.vo.CompanyVo;
import com.yeejoin.precontrol.common.vo.PersonVo;
import com.yeejoin.precontrol.common.vo.SelectPersonVo;
import com.yeejoin.precontrol.common.vo.TeamVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 企业基本信息 服务实现类
 *
 * @author duanwei
 * @date 2020-06-30
 */
@Service
@Slf4j
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

	@Autowired
	private CompanyMapper companyMapper;

	@Autowired
	TranslateEventPublish translateEventPublish;

	@Autowired
	private CompanyBusinessMapper businessMapper;

	@Autowired
	private CompanyBusinessAttachmentMapper businessAttachMapper;

	@Autowired
	private CompanyQualificationsMapper qualificationsMapper;

	@Autowired
	private CompanyQualificationsAttachmentMapper qualificationsAttachMapper;
	// 区域
	@Autowired
	private DistrictsMapper districtsMapper;

	@Autowired
	private IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	private IBaseService ibaseService;

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	ICompanyAcountService iCompanyAcountService;

	@Autowired
	SmallProService smallProService;

	@Autowired
	ICompanyBusinessService iBusinessService;

	@Autowired
	ICompanyBusinessAttachmentService businessAttachService;

	@Autowired
	ICompanyQualificationService iCompanyQualificationService;

	@Autowired
	ICompanyQualificationAttachmentService qualificationAttachService;

	@Autowired
	IDistrictsService districtsService;

	@Autowired
	PlatformUtils platformUtils;

	@Value("${fileserver.domain}")
	String fileServerUrl;

	@Autowired
	StatisticsMapper statisticsMapper;

	@Autowired
	IStatisticsService statisticsService;

	@Autowired
	ICompanyDepartmentService iCompanyDepartmentService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	IProjectCompanyService iProjectCompanyService;

	@Autowired
	RedisUtil redisUtil;

	@Override
	public Page pageInfo(CommonPageableDto pageable, CompanyParam param) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<CompanyVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		List<CompanyVo> pageInfo = companyMapper.pageInfo(param, page);
		pageInfo.forEach(company -> {
			// 区域赋值
			String region = company.getRegion();
			if (region != null) {
				String[] regionArr = region.split(",");
				String regionLabel = districtsMapper.selectLabelByIds(regionArr);
				company.setRegionLabel(regionLabel);
			}
			StatisticsDto statisticsDto = new StatisticsDto(param.getOrgCode(), null, company.getId());
			int personTotal = statisticsMapper.companyPersonCountByPerson(statisticsDto,
					TypeKeyEnum.COMPANY.getLongType(), null, null);
			company.setPersonTotal(personTotal);
		});
		page.setRecords(pageInfo);
		return page;
	}

	@Override
	public List<HashMap<String, Object>> companySelect() {
		return companyMapper.companySelect();
	}

	@Override
	public List<CompanyExcelVo> exportExcel(CompanyParam param) {
		return companyMapper.exportExcel(param);
	}

	@Override
	public synchronized void importExcel(List<CompanyExcelVo> companyList) {

		Set<String> creditCodes = companyList.stream().map(CompanyExcelVo::getCreditCode).collect(Collectors.toSet());

		List<CompanyBusiness> repeatBusinesses = businessMapper.selectList(
				new QueryWrapper<CompanyBusiness>().lambda().in(CompanyBusiness::getCreditCode, creditCodes));
		if (repeatBusinesses != null && repeatBusinesses.size() > 0) {
			List<String> collect = repeatBusinesses.stream().map(CompanyBusiness::getCreditCode)
					.collect(Collectors.toList());
			throw new BaseException("企业社会信用代码信息已存在！" + collect.toString());
		}

		ConvertUtils.register(new Converter() {
			@Override
			public Object convert(Class clazz, Object value) {
				// 将String转化为date
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date parse = null;
				// parse()返回的是一个Date类型数据，format返回的是一个StringBuffer类型的数据
				try {
					parse = format.parse(value.toString());
				} catch (java.text.ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return parse;
			}
		}, Date.class);

		companyList.forEach(c -> {
			Company company = new Company();
			CompanyBusiness business = new CompanyBusiness();
			CompanyQualifications qualifications = new CompanyQualifications();

			try {
				BeanUtils.copyProperties(business, c);
				BeanUtils.copyProperties(company, c);
				BeanUtils.copyProperties(qualifications, c);

				companyMapper.insert(company);
				business.setCompanyId(company.getId());
				qualifications.setCompanyId(company.getId());
				businessMapper.insert(business);
				qualificationsMapper.insert(qualifications);

			} catch (Exception e) {
				e.printStackTrace();
				throw new BaseException("数据格式不正确！");
			}
		});

	}

	@Override
	public IPage<BadCompanyVo> pageBadCompany(boolean isBad, boolean isAllStatus, CommonPageableDto pageable,
			BadCompanyVo badCompanyVo) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<BadCompanyVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		List<BadCompanyVo> list = companyMapper.badCompany(page, isBad, isAllStatus, badCompanyVo);
//		list.forEach(item -> {
//			StatisticsDto statisticsDto = new StatisticsDto(null, null, item.getId());
//			int personTotal = statisticsMapper.companyPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(),
//					null, null, null);
//			item.setPersonCount(String.valueOf(personTotal));
//		});
		page.setRecords(list);
		return page;
	}

	@Override
	public boolean syncCompany(JSONObject jsonObject) {
		JSONObject result = jsonObject.getJSONObject("result");
		String methodName = jsonObject.getString("methodName");
		String agencyCode = jsonObject.getString("agencyCode");
		String operUserId = jsonObject.getString("userId");
		String orgCode = platformUtils.getOrgCode(operUserId);
		if (null != result) {
			JSONObject result1;
			Long status = result.getLong("status");
			Company company;
			CompanyBusiness companyBusiness;
			if (status == 200) {
				switch (methodName) {
				case "create":
					result1 = result.getJSONObject("result");
					company = getCompany(result1);
					company.setTypeKey("0");
					company.setOrgCode(orgCode);
					companyBusiness = getCompanyBusiness(result1);
					this.saveOrUpdate(company);
					iBusinessService.saveOrUpdate(companyBusiness, new LambdaQueryWrapper<CompanyBusiness>()
							.eq(CompanyBusiness::getCompanyId, companyBusiness.getCompanyId()));
					translateEventPublish.publish(company);
					// 更新推送
					statisticsService.initWs("0", Constant.WS_COMPOSITESUM);
					log.info("平台消息同步,添加分包商:{}", company.toString());
					break;
				case "update":
					result1 = result.getJSONObject("result");
					company = getCompany(result1);
					companyBusiness = getCompanyBusiness(result1);
					Company oldCompany = iCompanyService.getById(company.getId());
					if (oldCompany == null) {
						company.setTypeKey("0");
					}
					company.setOrgCode(orgCode);
					this.saveOrUpdate(company);
					iBusinessService.saveOrUpdate(companyBusiness, new LambdaQueryWrapper<CompanyBusiness>()
							.eq(CompanyBusiness::getCompanyId, companyBusiness.getCompanyId()));
					translateEventPublish.publish(company);
					log.info("平台消息同步,更新分包商:{}", company.toString());
					break;
				case "deleteCompany":
					JSONArray result2 = result.getJSONArray("result");
					List<Long> companyIds = new ArrayList<>();
					for (int i = 0; i < result2.size(); i++) {
						String o = result2.getString(i);
						companyIds.add(Long.valueOf(o));
					}
					this.removeByIds(companyIds);
					log.info("平台消息同步,删除分包商:{}", companyIds.toString());
					List<CompanyBusiness> companyBusiness1 = ibaseService.listByFields(new CompanyBusiness(),
							"company_id", companyIds, "id");
					if (StringUtil.isNotEmpty(companyBusiness1)) {
						List<Long> collect = companyBusiness1.stream().map(m -> m.getId()).collect(Collectors.toList());
						ibaseService.removeByFields(new CompanyBusiness(), "company_id", companyIds);
						ibaseService.removeByFields(new CompanyBusinessAttachment(), "company__bussiness_id", collect);
						log.info("平台消息同步,删除分包商企业工商信息");
					}

					ibaseService.removeByFields(new CompanyProjectJobStatus(), "company_id", companyIds);
					log.info("平台消息同步,删除交底记录");
					List<CompanyQualifications> companyQualifications = ibaseService
							.listByFields(new CompanyQualifications(), "company_id", companyIds, "id");
					if (StringUtil.isNotEmpty(companyQualifications)) {
						List<Long> collect = companyQualifications.stream().map(m -> m.getId())
								.collect(Collectors.toList());
						ibaseService.removeByFields(new CompanyQualifications(), "company_id", companyIds);
						ibaseService.removeByFields(new CompanyQualificationsAttachment(), "company_qualifications_id",
								collect);
						log.info("平台消息同步,删除资质信息");
					}

					// 将关联关系表中的企业置空
					List<PersonAscription> list = iPersonAscriptionService.list(
							new LambdaQueryWrapper<PersonAscription>().in(PersonAscription::getCompanyId, companyIds));
					if (StringUtil.isNotEmpty(list)) {
						for (PersonAscription personAscription : list) {
							iPersonAscriptionService.update(null,
									Wrappers.<PersonAscription>lambdaUpdate().set(PersonAscription::getCompanyId, null)
											.set(PersonAscription::getProjectId, null)
											.eq(PersonAscription::getId, personAscription.getId()));
						}
					}
					// 更新推送
					statisticsService.initWs("0", Constant.WS_COMPOSITESUM);
					break;
				default:
					break;
				}
			} else {
				log.error("平台消息同步分包商状态不正确,status!=200,请检查数据:{}", jsonObject.toJSONString());
			}
		} else {
			log.error("平台消息同步分包商result中不存在result数据:{}", jsonObject.toJSONString());
		}
		return true;
	}

	@Override
	public void companyImport(MultipartFile file) throws Exception {
		List<CompanyImportDto> companyImportDtos = EasyPoiUtil.importExcel(file, 1, 1, CompanyImportDto.class);
		companyImportDtos.forEach(companyImportDto -> {
			String name = companyImportDto.getName();
			Company company = iCompanyService.getOne(new LambdaQueryWrapper<Company>().eq(Company::getName, name));
			if (company != null) {
				CompanyBusiness business = new CompanyBusiness();
				CompanyQualifications qualifications = new CompanyQualifications();
				BeanUtils.copyProperties(companyImportDto, company, "id");
				String regionName = companyImportDto.getRegionName();
				if (regionName != null) {
					String region = DistrictsUtils.findByName(regionName);
					company.setRegion(region);
				}
				iCompanyService.updateById(company);
				CompanyBusiness companyBusiness = iBusinessService.getOne(
						new LambdaQueryWrapper<CompanyBusiness>().eq(CompanyBusiness::getCompanyId, company.getId())
								.orderByAsc(CompanyBusiness::getCreateDate).last("limit 1"));
				if (companyBusiness != null) {
					BeanUtils.copyProperties(companyImportDto, companyBusiness, "id");
					companyBusiness.setCompanyId(company.getId());
					iBusinessService.updateById(companyBusiness);
				} else {
					BeanUtils.copyProperties(companyImportDto, business, "id");
					business.setCompanyId(company.getId());
					iBusinessService.save(business);
				}
				CompanyQualifications companyQualifications = iCompanyQualificationService
						.getOne(new LambdaQueryWrapper<CompanyQualifications>()
								.eq(CompanyQualifications::getCompanyId, company.getId())
								.orderByAsc(CompanyQualifications::getCreateDate).last("limit 1"));
				if (companyQualifications != null) {
					BeanUtils.copyProperties(companyImportDto, companyQualifications, "id");
					companyQualifications.setCompanyId(company.getId());
					iCompanyQualificationService.updateById(companyQualifications);
				} else {
					BeanUtils.copyProperties(companyImportDto, qualifications, "id");
					qualifications.setCompanyId(company.getId());
					iCompanyQualificationService.save(qualifications);
				}
			}
		});
	}

	@Override
	public Company saveOrUpdateCompany(CompanyDto companyDto) {
		Company company = new Company();
		try {
			PropertyUtils.copyProperties(company, companyDto);
		} catch (Exception e) {
			log.error("saveOrUpdateCompany 属性copy错误");
		}
		boolean saveFlag = companyDto.getId() == null;

		CompanyBusiness companyBusiness = companyDto.getCompanyBusiness();
		if (companyBusiness != null) {
			String creditCode = companyBusiness.getCreditCode();
			CompanyBusiness business = iBusinessService.getOne(
					new QueryWrapper<CompanyBusiness>().lambda().eq(CompanyBusiness::getCreditCode, creditCode));
			if ((saveFlag && business != null) || (!saveFlag && business != null
					&& business.getId().longValue() != companyBusiness.getId().longValue())) {
				throw new BaseException("企业社会信用代码信息已存在！");
			}
		}
		company.setLogo(company.getLogo().replace(fileServerUrl, ""));
		// 设置companyorgcode
		if (company.getId() == null) {
			Company companyMax = this
					.getOne(new LambdaQueryWrapper<Company>().orderByDesc(Company::getCompanyOrgCode).last("limit 1"));
			int companyOrgCode = 1;
			if (companyMax != null && companyMax.getCompanyOrgCode() != null) {
				companyOrgCode = Integer.valueOf(companyMax.getCompanyOrgCode()) + 1;
			}
			company.setCompanyOrgCode(companyOrgCode);
		}
		iCompanyService.saveOrUpdate(company);
		Long companyId = company.getId();
		// 工商信息
		if (companyBusiness != null) {
			companyBusiness.setCompanyId(companyId);
			iBusinessService.saveOrUpdate(companyBusiness);

			List<CompanyBusinessAttachment> attachment = companyBusiness.getAttachment();
			businessAttachService.saveAttach(companyBusiness.getId(), attachment);
		}
		// 资质信息
		List<CompanyQualifications> qualifications = companyDto.getCompanyQualifications();

		// 每次删除资质
		iCompanyQualificationService.remove(
				new LambdaQueryWrapper<CompanyQualifications>().eq(CompanyQualifications::getCompanyId, companyId));
		if (qualifications != null) {
			for (int i = 0; i < qualifications.size(); i++) {
				CompanyQualifications companyQualification = qualifications.get(i);
				companyQualification.setCompanyId(companyId);
				companyQualification.setOrders(Long.valueOf(i));
				iCompanyQualificationService.saveOrUpdate(companyQualification);
				List<CompanyQualificationsAttachment> attachment2 = companyQualification.getAttachment();
				qualificationAttachService.saveAttach(companyQualification.getId(), attachment2);

			}

		}
		// 每次删除银行卡信息 重新存储
		iCompanyAcountService
				.remove(new LambdaQueryWrapper<CompanyAcount>().eq(CompanyAcount::getCompanyId, companyId));
		if (StringUtil.isNotEmpty(companyDto.getTeamData())) {
			List<TeamDto> teamDtos = companyDto.getTeamData();
			for (TeamDto teamDto : teamDtos) {
				CompanyAcount companyAcount = new CompanyAcount();
				BeanUtils.copyProperties(teamDto, companyAcount);
				companyAcount.setCompanyId(companyId);
				companyAcount.setCompanyName(company.getName());
				companyAcount.setTeamName(teamDto.getName());
				iCompanyAcountService.save(companyAcount);
			}
		}
		return company;
	}

	@Override
	public CompanyDto selectById(Long id) {
		Company company = iCompanyService.getById(id);
		String region = company.getRegion();
		if (region != null) {
			company.setRegionLabel(districtsService.selectLabelByIds(region.split(",")));
		}
		CompanyDto companyDto = new CompanyDto();
		if (company != null) {
			try {
				PropertyUtils.copyProperties(companyDto, company);
				CompanyBusiness business = iBusinessService
						.getOne(new QueryWrapper<CompanyBusiness>().lambda().eq(CompanyBusiness::getCompanyId, id));
				if (business != null) {
					List<CompanyBusinessAttachment> list = businessAttachService
							.list(new QueryWrapper<CompanyBusinessAttachment>().lambda()
									.eq(CompanyBusinessAttachment::getCompanyBusinessId, business.getId()));
					business.setAttachment(list);
				}
				companyDto.setCompanyBusiness(business);

				List<CompanyQualifications> list = iCompanyQualificationService.list(
						new QueryWrapper<CompanyQualifications>().lambda().eq(CompanyQualifications::getCompanyId, id));
				list.forEach(l -> {
					List<CompanyQualificationsAttachment> attachs = qualificationAttachService
							.list(new QueryWrapper<CompanyQualificationsAttachment>().lambda()
									.eq(CompanyQualificationsAttachment::getCompanyQualificationsId, l.getId()));
					l.setAttachment(attachs);
				});
				if (StringUtil.isNotEmpty(list)) {
					companyDto.setCompanyQualifications(list);
				}
				List<CompanyAcount> companyAcount = iCompanyAcountService
						.list(new LambdaQueryWrapper<CompanyAcount>().eq(CompanyAcount::getCompanyId, id));
				List<TeamDto> teamDtos = new ArrayList<>();
				if (StringUtil.isNotEmpty(companyAcount)) {
					for (CompanyAcount acount : companyAcount) {
						TeamDto teamDto = new TeamDto();
						BeanUtils.copyProperties(acount, teamDto);
						teamDto.setName(acount.getTeamName());
						teamDtos.add(teamDto);
					}
				}
				companyDto.setTeamData(teamDtos);
			} catch (Exception e) {
				throw new BaseException(e.getMessage());
			}
		} else {
			throw new BaseException("企业不存在");
		}
		return companyDto;
	}

	private Company getCompany(JSONObject result1) {
		String sequenceNbr = result1.getString("sequenceNbr");
		String companyName = result1.getString("companyName");
		String description = result1.getString("description");
		String email = result1.getString("email");
		String longitude = result1.getString("longitude");
		String latitude = result1.getString("latitude");
		String contact = result1.getString("contact");
		String landlinePhone = result1.getString("landlinePhone");
		String address = result1.getString("address");
		Company company = new Company();
		company.setId(Long.valueOf(sequenceNbr));
		company.setName(companyName);
		company.setContact(contact);
		company.setTel(landlinePhone);
		company.setEmail(email);
		company.setIntroduction(description);
		company.setStatus(0);
		company.setRemark(description);
		return company;
	}

	private CompanyBusiness getCompanyBusiness(JSONObject result1) {
		String sequenceNbr = result1.getString("sequenceNbr");
		String address = result1.getString("address");
		CompanyBusiness companyBusiness = new CompanyBusiness();
		companyBusiness.setCompanyId(Long.valueOf(sequenceNbr));
		companyBusiness.setCompanyAddress(address);
		return companyBusiness;
	}

	@Override
	public List<TeamVo> deptQueryWithAccount(Long id) {
		List<CompanyDepartment> teams = iCompanyDepartmentService.list(new LambdaQueryWrapper<CompanyDepartment>()
				.eq(CompanyDepartment::getCompanyId, id).eq(CompanyDepartment::getLevel, "team"));
		List<TeamVo> teamVos = new ArrayList<>();
		if (StringUtil.isNotEmpty(teams)) {
			teams.forEach(r -> {
				TeamVo teamVo = new TeamVo();
				teamVo.setName(r.getName());
				teamVo.setDepartmentId(r.getId());
				CompanyAcount companyAcount = iCompanyAcountService
						.getOne(new LambdaQueryWrapper<CompanyAcount>().eq(CompanyAcount::getDepartmentId, r.getId()));
				if (companyAcount != null) {
					teamVo.setAcountNumber(companyAcount.getAcountNumber());
					teamVo.setBankName(companyAcount.getBankName());
					teamVo.setRemark(companyAcount.getRemark());
				}
				teamVos.add(teamVo);
			});
		}
		return teamVos;
	}

	@Override
	public SelectPersonVo deptQuery(Long companyId, String roleName, Long projectId) {
		Set<String> ids = getRoleIds(roleName);
		// 分包商根节点人员
		List<PersonVo> companyPersonVoList = iPersonAscriptionService.getUsersByDept(ids, companyId, null, projectId);
		// 获取部门的人员信息
		// Map<String, Object> map = new HashMap<>();
		SelectPersonVo selectPersonVo = new SelectPersonVo();
		selectPersonVo.setCompanyPersonVoList(companyPersonVoList);
		List<CompanyDepartment> depts = iCompanyDepartmentService.list(new LambdaQueryWrapper<CompanyDepartment>()
				.eq(CompanyDepartment::getCompanyId, companyId).eq(CompanyDepartment::getParentId, 1L));
		List<TeamVo> teamVos = new ArrayList<>();
		for (CompanyDepartment companyDepartment : depts) {
			TeamVo teamVo = new TeamVo();
			teamVo.setId(companyDepartment.getId());
			teamVo.setName(companyDepartment.getName());
			List<PersonVo> deptPersonVoList = iPersonAscriptionService.getUsersByDept(ids, companyId,
					companyDepartment.getId(), projectId);
			teamVo.setPersonVo(deptPersonVoList);
			int count = iCompanyDepartmentService.countChildrenPerson(companyDepartment.getId(), ids, projectId);
			teamVo.setNumber(count);
			teamVo.setDepartmentId(companyDepartment.getId());
			teamVo.setOrgCode(companyDepartment.getOrgCode());
			CompanyAcount companyAcount = iCompanyAcountService.getOne(new LambdaQueryWrapper<CompanyAcount>()
					.eq(CompanyAcount::getDepartmentId, companyDepartment.getId()));
			if (companyAcount != null) {
				teamVo.setBankName(companyAcount.getBankName());
				teamVo.setAcountNumber(companyAcount.getAcountNumber());
				teamVo.setRemark(companyAcount.getRemark());
			}
			teamVos.add(teamVo);
		}
		// map.put("teamPersonVoList", teamVos);
		selectPersonVo.setTeamPersonVoList(teamVos);
		return selectPersonVo;
	}

	private Set<String> getRoleIds(String roleName) {
		List<String> roleNames = new ArrayList<>();
		if (StringUtil.isNotEmpty(roleName)) {
			String[] split = roleName.split(",");
			for (String s : split) {
				roleNames.add(s);
			}
		}
		Set<String> ids = new HashSet<>();
		List<RoleModel> roleModels = (List<RoleModel>) redisUtil.get(Constant.ROLE_LIST);
		if (roleModels == null) {
			FeignClientResult<List<RoleModel>> roles = Privilege.roleClient.queryRoleList(null, null);
			roleModels = roles.getResult();
			redisUtil.set(Constant.ROLE_LIST, roleModels);
		}
		if (StringUtil.isNotEmpty(roleNames)) {
			if (StringUtil.isNotEmpty(roleModels)) {
				roleModels.forEach(role -> {
					if (roleNames.contains(role.getRoleName())) {
						ids.add(String.valueOf(role.getSequenceNbr()));
					}
				});
			}
		} else {
			if (StringUtil.isNotEmpty(roleModels)) {
				roleModels.forEach(role -> ids.add(String.valueOf(role.getSequenceNbr())));
			}
		}
		return ids;
	}

	@Override
	public SelectPersonVo teamQuery(Long deptId, String roleName, Long projectId) {
		Set<String> ids = getRoleIds(roleName);
		// 分包商根节点人员
		List<PersonVo> companyPersonVoList = iPersonAscriptionService.getUsersByDept(ids, null, deptId, projectId);
		// 获取部门的人员信息
//		Map<String, Object> map = new HashMap<>();
//		map.put("companyPersonVoList", companyPersonVoList);
		SelectPersonVo selectPersonVo = new SelectPersonVo();
		selectPersonVo.setCompanyPersonVoList(companyPersonVoList);
		List<CompanyDepartment> depts = iCompanyDepartmentService
				.list(new LambdaQueryWrapper<CompanyDepartment>().eq(CompanyDepartment::getParentId, deptId));
		List<TeamVo> teamVos = new ArrayList<>();
		for (CompanyDepartment companyDepartment : depts) {
			TeamVo teamVo = new TeamVo();
			teamVo.setId(companyDepartment.getId());
			teamVo.setName(companyDepartment.getName());
			List<PersonVo> deptPersonVoList = iPersonAscriptionService.getUsersByDept(ids, null,
					companyDepartment.getId(), projectId);
			teamVo.setPersonVo(deptPersonVoList);
			int count = iCompanyDepartmentService.countChildrenPerson(companyDepartment.getId(), ids, projectId);
			teamVo.setNumber(count);
			teamVo.setDepartmentId(companyDepartment.getId());
			teamVo.setOrgCode(companyDepartment.getOrgCode());
			CompanyAcount companyAcount = iCompanyAcountService.getOne(new LambdaQueryWrapper<CompanyAcount>()
					.eq(CompanyAcount::getDepartmentId, companyDepartment.getId()));
			if (companyAcount != null) {
				teamVo.setBankName(companyAcount.getBankName());
				teamVo.setAcountNumber(companyAcount.getAcountNumber());
				teamVo.setRemark(companyAcount.getRemark());
			}
			teamVos.add(teamVo);
		}
		// map.put("teamPersonVoList", teamVos);
		selectPersonVo.setTeamPersonVoList(teamVos);
		return selectPersonVo;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<DepartmentModel> platDeptQuery(String orgcode, Boolean noFbs) {
		FeignClientResult<Collection<CompanyModel>> companyResult = Privilege.companyClient.companyTreeWithoutAuth();
		if (companyResult == null) {
			return null;
		}
		List<CompanyModel> coms = (List<CompanyModel>) companyResult.getResult();
		if (coms.get(0) == null) {
			return null;
		}
		Long companyId = coms.get(0).getSequenceNbr();
		FeignClientResult<Collection<DepartmentModel>> deptResult = Privilege.departmentClient.queryDeptTree(null,
				companyId);
		if (deptResult.getResult() == null) {
			return null;
		}

		Collection<DepartmentModel> result = null;
		;
		if (orgcode == null) {
			result = deptResult.getResult();
		} else {
			result = getOrgCodeList(deptResult.getResult(), orgcode);
		}
		if (noFbs != null && noFbs) {
			return filterFbs(result);
		}
		return result;
	}

	private Collection<DepartmentModel> filterFbs(Collection<DepartmentModel> collection) {
		Collection<DepartmentModel> newCollection = new ArrayList<DepartmentModel>();
		for (Object object : collection) {
			JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));
			DepartmentModel dept = JSONObject.toJavaObject(jsonObject, DepartmentModel.class);
			if (!"fbs".equals(dept.getLevel())) {
				if (dept.getChildren() != null) {
					dept.setChildren(filterFbs(dept.getChildren()));
				}
				newCollection.add(dept);
			}
		}
		return newCollection;
	}

	private Collection<DepartmentModel> getOrgCodeList(Collection<DepartmentModel> collection, String orgcode) {
		for (Object object : collection) {
			JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));
			DepartmentModel departmentModel = JSONObject.toJavaObject(jsonObject, DepartmentModel.class);
			if (orgcode.equals(departmentModel.getOrgCode())) {
				Collection<DepartmentModel> list = new ArrayList<DepartmentModel>();
				list.add(departmentModel);
				return list;
			} else if (departmentModel.getChildren() != null) {
				Collection<DepartmentModel> list = getOrgCodeList(departmentModel.getChildren(), orgcode);
				if (list == null) {
					continue;
				} else {
					return list;
				}
			}
		}
		return null;
	}

	@Override
	public List<Company> getByOrgCode(String orgcode) {
		List<Company> companyList = new ArrayList<Company>();
		if (orgcode != null) {
			List<Project> list = iProjectService
					.list(new LambdaQueryWrapper<Project>().like(Project::getOrgCode, orgcode));
			Set<Long> projectIds = list.stream().map(i -> i.getId()).collect(Collectors.toSet());
			List<ProjectCompany> list2 = iProjectCompanyService
					.list(new LambdaQueryWrapper<ProjectCompany>().in(ProjectCompany::getProjectId, projectIds));
			Set<Long> companyIds = list2.stream().map(i -> i.getCompanyId()).collect(Collectors.toSet());
			companyList = this.list(new LambdaQueryWrapper<Company>().in(Company::getId, companyIds)
					.eq(Company::getTypeKey, TypeKeyEnum.COMPANY.getLongType()));
		} else {
			companyList = this
					.list(new LambdaQueryWrapper<Company>().eq(Company::getTypeKey, TypeKeyEnum.COMPANY.getLongType()));
		}
		return companyList;
	}

	@Override
	public List<Company> byPlatFbsDeptOrgCode(String orgcode) {
		if (orgcode == null || !orgcode.contains("*")) {
			return this.list();
		} else {
			orgcode = orgcode.substring(0, orgcode.lastIndexOf("*"));
			List<Project> proList = iProjectService
					.list(new LambdaQueryWrapper<Project>().like(Project::getOrgCode, orgcode));
			Set<Long> proIdList = proList.stream().map(i -> i.getId()).collect(Collectors.toSet());
			if(proIdList.isEmpty()) 
			{
				throw new BaseException("该项目部下没有对应项目");
			}
			List<ProjectCompany> procList = iProjectCompanyService
					.list(new LambdaQueryWrapper<ProjectCompany>().in(ProjectCompany::getProjectId, proIdList));
			Set<Long> procIdList = procList.stream().map(i -> i.getCompanyId()).collect(Collectors.toSet());
			if(procIdList.isEmpty()) 
			{
				throw new BaseException("该项目部下的项目没有关联分包商");
			}
			return this.list(new LambdaQueryWrapper<Company>().in(Company::getId, procIdList));
		}
	}
}
