package com.yeejoin.amos.boot.module.common.biz.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.dto.MaintenanceCompanyDto;
import com.yeejoin.amos.boot.module.common.api.dto.MaintenancePersonExcleDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.entity.SourceFile;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.DynamicFormInstanceMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.MaintenanceCompanyMapper;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;

/**
 * 维保单位服务实现类
 *
 * @author system_generator
 * @date 2021-07-16
 */
@Service
public class MaintenanceCompanyServiceImpl
		extends BaseService<MaintenanceCompanyDto, MaintenanceCompany, MaintenanceCompanyMapper>
		implements IMaintenanceCompanyService {

	private static final String MAINTENANCE_COMPANY = "maintenanceCompany";
	private static final String MAINTENANCE_PERSON = "maintenancePerson";
	private static final String MAINTENANCE_DEPARTMENT = "maintenanceDepartment";

	private static final String PERSON = "PERSON";
	private static final String COMPANY = "COMPANY";
	private static final String DEPARTMENT = "DEPARTMENT";

	@Autowired
	DynamicFormInstanceServiceImpl dynamicFormInstanceService;

	@Autowired
	DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;

	@Autowired
	Sequence sequence;

	@Autowired
	MaintenanceCompanyMapper maintenanceCompanyMapper;

	@Autowired
	IOrgUsrService iOrgUsrService;

	@Autowired
	DynamicFormInstanceMapper dynamicFormInstanceMapper;

	@Autowired
	SourceFileServiceImpl sourceFileService;

	/**
	 * 分页查询
	 */
	public Page<MaintenanceCompanyDto> queryForMaintenanceCompanyPage(Page<MaintenanceCompanyDto> page) {
		return this.queryForPage(page, null, false);
	}

	/**
	 * 列表查询 示例
	 */
	public List<MaintenanceCompanyDto> queryForMaintenanceCompanyList() {
		return this.queryForList("", false);
	}

	/**
	 * 添加维保单位基本信息
	 * 
	 * @param maintenanceCompany
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveCompanyDetail(MaintenanceCompany maintenanceCompany) {
		Long instanceId = saveDynamicFormList(maintenanceCompany);
		maintenanceCompany.setCode(OrgUsrServiceImpl.getOrgCodeStr());
		maintenanceCompany.setOrgCode(null);
		maintenanceCompany.setBizCode(sequence.nextId() + "");
		maintenanceCompany.setInstanceId(instanceId);
		maintenanceCompany.setType(maintenanceCompany.getType().toUpperCase());
		maintenanceCompany.setIsDelete(false);
		try {
			this.save(maintenanceCompany);

			saveAttachments(maintenanceCompany);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	@Override
	public boolean savePersonDetail(MaintenanceCompany maintenanceCompany) {
		Long instanceId = saveDynamicFormList(maintenanceCompany);
		Long parentId = maintenanceCompany.getParentId();
		MaintenanceCompany parent = maintenanceCompanyMapper.selectById(parentId);
		if (StringUtils.isBlank(maintenanceCompany.getCode())) {
			// 添加人员时，当前的code 为单位code+6位随机数
			maintenanceCompany.setCode(parent.getCode() + OrgUsrServiceImpl.getOrgCodeStr());
		}
		maintenanceCompany.setOrgCode(null);
		if (ValidationUtil.isEmpty(maintenanceCompany.getBizCode())) {
			maintenanceCompany.setBizCode(sequence.nextId() + "");
		}
		maintenanceCompany.setInstanceId(instanceId);
		maintenanceCompany.setParentId(parentId);
		maintenanceCompany.setIsDelete(false);
		try {
			this.save(maintenanceCompany);

			saveAttachments(maintenanceCompany);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 保存附件
	 */
	public void saveAttachments(MaintenanceCompany maintenanceCompany) {
		if (!ValidationUtil.isEmpty(maintenanceCompany.getAttachments())) {
			List<SourceFile> sourceFiles = Lists.newArrayList();
			Map<String, List<AttachmentDto>> attachmentMap = maintenanceCompany.getAttachments();
			attachmentMap.entrySet().forEach(entry -> {
				List<AttachmentDto> atts = entry.getValue();
				sourceFiles.addAll(attachment2SourceFile(entry.getKey(), atts));
			});
			sourceFileService.saveSourceFile(maintenanceCompany.getSequenceNbr(), sourceFiles);
		}
	}

	private List<SourceFile> attachment2SourceFile(String type, List<AttachmentDto> attachmentDtoList) {
		List<SourceFile> sourceFiles = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(attachmentDtoList)) {
			attachmentDtoList.forEach(a -> {
				SourceFile s = new SourceFile();
				s.setFilePath(a.getUrl());
				s.setFileName(a.getName());
				s.setFileCategory(type);
				sourceFiles.add(s);
			});
		}
		return sourceFiles;
	}

	/**
	 * 添加动态表单信息
	 * 
	 * @param maintenanceCompany
	 * @return
	 */
	public Long saveDynamicFormList(MaintenanceCompany maintenanceCompany) {
		Long instanceId = sequence.nextId();
		List<DynamicFormInstance> dynamicFormInstanceList = maintenanceCompany.getDynamicFormValue();
		for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
			dynamicFormInstance.setInstanceId(instanceId);
			dynamicFormInstanceService.save(dynamicFormInstance);
		}
		return instanceId;
	}

	@Override
	public boolean saveDepartmentDetail(MaintenanceCompany maintenanceCompany) {
		Long instanceId = saveDynamicFormList(maintenanceCompany);
		Long parentId = maintenanceCompany.getParentId();
		MaintenanceCompany parent = maintenanceCompanyMapper.selectById(parentId);
		// 添加人员时，当前的orgcode 为单位code+6位随机数
		maintenanceCompany.setCode(parent.getCode() + OrgUsrServiceImpl.getOrgCodeStr());
		maintenanceCompany.setOrgCode(null);
		maintenanceCompany.setBizCode(sequence.nextId() + "");
		maintenanceCompany.setInstanceId(instanceId);
		maintenanceCompany.setType(maintenanceCompany.getType().toUpperCase());
		maintenanceCompany.setParentId(parentId);
		maintenanceCompany.setIsDelete(false);
		try {
			this.save(maintenanceCompany);

			saveAttachments(maintenanceCompany);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public boolean deleteById(Long sequenceNbr) {

		MaintenanceCompany maintenanceCompany = maintenanceCompanyMapper.selectById(sequenceNbr);
		if (ObjectUtils.isEmpty(maintenanceCompany)) {
			return false;
		}
		maintenanceCompany.setIsDelete(true);
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MaintenanceCompany::getSequenceNbr, sequenceNbr);

		int number = maintenanceCompanyMapper.update(maintenanceCompany, wrapper);
		if (number > 0) {
			// 更新动态表单字段为删除状态
			List<DynamicFormInstance> dyInstance = dynamicFormInstanceService
					.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId,
							maintenanceCompany.getInstanceId()));
			dyInstance.forEach(i -> i.setIsDelete(true));
			dynamicFormInstanceService.updateBatchById(dyInstance);

			return true;
		}

		return false;
	}

	@Override
	public List<Map<String, Object>> getMaintenanceCompanyDropDownList() {
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(MaintenanceCompany::getCode, MaintenanceCompany::getName);
		wrapper.eq(MaintenanceCompany::getType, COMPANY);
		wrapper.eq(MaintenanceCompany::getIsDelete, false);
		return maintenanceCompanyMapper.selectMaps(wrapper);
	}

	@Override
	public boolean checkPersonCodeExists(String code) {
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MaintenanceCompany::getCode, code);
		MaintenanceCompany detail = maintenanceCompanyMapper.selectOne(wrapper);
		if (ObjectUtils.isEmpty(detail)) {
			return true;
		}
		return false;
	}

	@Override
	public List<Map<String, Object>> getAllMaintenanceList(String maintenanceType) {
		String type = null;
		switch (maintenanceType.toUpperCase()) {
		case PERSON:
			type = MAINTENANCE_PERSON;
			break;
		case DEPARTMENT:
			type = MAINTENANCE_DEPARTMENT;
			break;
		default:
			type = MAINTENANCE_COMPANY;
		}
		if (StringUtils.isBlank(type)) {
			return null;
		}
		List<Map<String, Object>> dynamicFormList = dynamicFormInstanceService.listAll(type);
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
		wrapper.eq(MaintenanceCompany::getIsDelete, false);
		List<MaintenanceCompany> maintenanceCompany = this.list(wrapper);

		Map<Long, MaintenanceCompany> maintenanceCompanyMap = maintenanceCompany.stream()
				.collect(Collectors.toMap(MaintenanceCompany::getInstanceId, Function.identity()));
		dynamicFormList.forEach(r -> {
			MaintenanceCompany detail = maintenanceCompanyMap.get(Long.parseLong(r.get("instanceId").toString()));
			if (!ObjectUtils.isEmpty(detail)) {
				if(detail.getParentId()!=null) {
					MaintenanceCompany map = maintenanceCompanyMapper.selectById(detail.getParentId());
					r.put("parentName", map.getName());
				}
				r.putAll(Bean.BeantoMap(detail));
			}
		});
		return dynamicFormList;
		
	}

	@Override
	public List<MaintenancePersonExcleDto> exportToMaintenancePersonExcel() {
		List<Map<String, Object>> list = this.getAllMaintenanceList(PERSON);
		return JSONArray.parseArray(JSONArray.toJSONString(list), MaintenancePersonExcleDto.class);

	}

	/**
	 * 维保单位人员信息分頁信息显示时的字段过滤
	 * 
	 * @param current
	 * @param size
	 * @param list
	 * @param arrayType
	 * @return
	 */
	public IPage<Map<String, Object>> getLegalList(int current, int size, IPage<Map<String, Object>> list,
			String[] arrayType) {
		List<Map<String, Object>> returnlist = new ArrayList<Map<String, Object>>();
		Map<String, Object> legalMap = null;
		for (Map<String, Object> map : list.getRecords()) {
			legalMap = new HashMap<String, Object>();
			for (Entry<String, Object> m : map.entrySet()) {
				if (Arrays.asList(arrayType).contains(m.getKey())) {
					legalMap.putAll(map);
				}
			}
			returnlist.add(legalMap);
		}
		Page<Map<String, Object>> pegaIPage = new Page<Map<String, Object>>();
		pegaIPage.setCurrent(current);
		pegaIPage.setSize(size);
		pegaIPage.setRecords(returnlist);
		return pegaIPage;
	}

	@Override
	public IPage<Map<String, Object>> getPageMaintenanceList(Map<String, Object> paramsMap) {
		if (!paramsMap.containsKey("current") && !paramsMap.containsKey("size")) {
			return null;
		}
		if (!paramsMap.containsKey("maintenanceType")) {
			return null;
		}
		int current = Integer.parseInt(paramsMap.get("current").toString());
		int size = Integer.parseInt(paramsMap.get("size").toString());
		String maintenanceType = paramsMap.get("maintenanceType").toString().toUpperCase();
		Map<String, String> filedParamsMap = null;

		List<MaintenanceCompany> mainTableList;
		String type;
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MaintenanceCompany::getIsDelete, false);
		switch (maintenanceType) {
		case PERSON:
			type = MAINTENANCE_PERSON;
			filedParamsMap = new HashMap<>();
			if (paramsMap.containsKey("status")) {
				filedParamsMap.put("status", paramsMap.get("status").toString());
			}
			mainTableList = this.checkMaintenanceCompanyList(wrapper, paramsMap);
			List<Long> instanceIds = Lists.transform(mainTableList, MaintenanceCompany::getInstanceId);
			filedParamsMap.put("instanceIds", Joiner.on(",").join(instanceIds));
			break;
		case COMPANY:
			type = MAINTENANCE_COMPANY;
			wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
			mainTableList = this.list(wrapper);
			break;
		case DEPARTMENT:
			type = MAINTENANCE_DEPARTMENT;
			wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
			mainTableList = this.list(wrapper);
			break;
		default:
			throw new IllegalStateException("Unexpected maintenanceType: " + maintenanceType);
		}
		if (StringUtils.isBlank(type)) {
			return null;
		}
		IPage<Map<String, Object>> page = dynamicFormInstanceService.pageList(current, size, type, filedParamsMap);

		Map<Long, MaintenanceCompany> maintenanceCompanyMap = mainTableList.stream()
				.collect(Collectors.toMap(MaintenanceCompany::getInstanceId, Function.identity()));

		page.getRecords().forEach(r -> {
			MaintenanceCompany detail = maintenanceCompanyMap.get(Long.parseLong(r.get("instanceId").toString()));
			if (!ObjectUtils.isEmpty(detail)) {
				r.putAll(Bean.BeantoMap(detail));
			}
		});
		return page;
	}

	public List<MaintenanceCompany> checkMaintenanceCompanyList(LambdaQueryWrapper<MaintenanceCompany> wrapper,
			Map<String, Object> paramsMap) {
		if (paramsMap.containsKey("name")) {
			wrapper.like(MaintenanceCompany::getName, paramsMap.get("name").toString());
		}
		if (paramsMap.containsKey("parentId") && !"-1".equals(paramsMap.get("parentId"))) {
			Long parentId = Long.parseLong(paramsMap.get("parentId").toString());
			MaintenanceCompany company = getOne(
					new LambdaQueryWrapper<MaintenanceCompany>().eq(MaintenanceCompany::getSequenceNbr, parentId));
			wrapper.likeRight(MaintenanceCompany::getCode, company.getCode());
		}
		wrapper.eq(MaintenanceCompany::getType, PERSON);

		return maintenanceCompanyMapper.selectList(wrapper);
	}

	@Override
	public Map<String, Object> findBySequenceNbr(Long sequenceNbr) {
		MaintenanceCompany maintenanceCompany = maintenanceCompanyMapper.selectById(sequenceNbr);
		String type;
		switch (maintenanceCompany.getType()) {
		case PERSON:
			type = MAINTENANCE_PERSON;
			break;
		case DEPARTMENT:
			type = MAINTENANCE_DEPARTMENT;
			break;
		default:
			type = MAINTENANCE_COMPANY;
		}
		Map<String, Object> mainMap = Bean.BeantoMap(maintenanceCompany);
		Map<String, Object> dynamicMap = dynamicFormInstanceService.getOneMap(maintenanceCompany.getInstanceId(), type);
		mainMap.put("attachments", getAttachments(maintenanceCompany.getSequenceNbr()));
		mainMap.put("dynamicFormValue", dynamicMap);
		return mainMap;
	}

	private Map<String, List<AttachmentDto>> getAttachments(Long sequenceNbr) {
		Map<String, List<AttachmentDto>> attachmentMap = Maps.newHashMap();
		List<SourceFile> sourceFileList = sourceFileService.findBySourceId(sequenceNbr);
		if (!ValidationUtil.isEmpty(sourceFileList)) {
			List<AttachmentDto> attachmentList = sourceFile2AttachmentList(sourceFileList);
			attachmentMap = attachmentList.stream().collect(Collectors.groupingBy(AttachmentDto::getType));
		}
		return attachmentMap;
	}

	private List<AttachmentDto> sourceFile2AttachmentList(List<SourceFile> sourceFileList) {
		List<AttachmentDto> attachmentDtoList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(sourceFileList)) {
			sourceFileList.forEach(s -> {
				AttachmentDto a = new AttachmentDto();
				a.setName(s.getFileName());
				a.setUrl(s.getFilePath());
				a.setType(s.getFileCategory());
				attachmentDtoList.add(a);
			});
		}
		return attachmentDtoList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateMaintenanceCompanyDetail(MaintenanceCompany model) throws Exception {
		return updateMaintenanceDetail(model, COMPANY);
	}

	public boolean updateMaintenanceDetail(MaintenanceCompany model, String type) throws Exception {
		MaintenanceCompanyDto maintenanceCompany = this.queryBySeq(model.getSequenceNbr());
//		try {
////			if (maintenanceCompany != null) {
////				dynamicFormInstanceService.remove(new LambdaQueryWrapper<DynamicFormInstance>()
////						.eq(DynamicFormInstance::getInstanceId, maintenanceCompany.getInstanceId()));
////			}
//		} catch (Exception e) {
//			return false;
//		}
		this.updateDetail(model, type);
		return true;
	}

	public boolean updateDetail(MaintenanceCompany model, String type) throws Exception {
		// 更新动态表单数据
		iOrgUsrService.updateDynamicFormInstance(model.getInstanceId(), model.getDynamicFormValue());
		// 更新主表数据
		model.setType(type);
		try {
			this.updateById(model);

			// 更新附件
			saveAttachments(model);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateMaintenancePersonDetail(MaintenanceCompany model) throws Exception {
		return updateMaintenanceDetail(model, PERSON);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateMaintenanceDepartmentDetail(MaintenanceCompany model) throws Exception {
		return updateMaintenanceDetail(model, DEPARTMENT);
	}

	@Override
	public List<MaintenanceCompany> getCompanyAndDepartmentTree() {
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
				MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
		wrapper.eq(MaintenanceCompany::getIsDelete, 0);
		wrapper.in(MaintenanceCompany::getType, Arrays.asList(COMPANY, DEPARTMENT));
		List<MaintenanceCompany> list = maintenanceCompanyMapper.selectList(wrapper);
		if (list == null) {
			return new ArrayList<>();
		}
		list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
		return list;
	}

	@Override
	public List<MaintenanceCompany> getDepartmentAndPersonTree(long sequenceNbr) {
		// List<MaintenanceCompany> departmentAllList =new
		// ArrayList<MaintenanceCompany>();
		List<MaintenanceCompany> departmentList = getDepartmentList(sequenceNbr);
		// departmentAllList.addAll(departmentList);
//		departmentAllList = getDepartmentAllList(departmentAllList,departmentList);
//		for (MaintenanceCompany map : departmentList) {
//			Long departmentSequenceNbr=map.getSequenceNbr();
//			departmentAllList.addAll(getPersonList(departmentSequenceNbr));
//		}
//		if (departmentAllList == null) {
//			return new ArrayList<>();
//		}
//		departmentAllList = departmentAllList.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
//		return departmentAllList;
		if (departmentList == null) {
			return new ArrayList<>();
		}
		return departmentList.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
	}
//	public List<MaintenanceCompany> getDepartmentAllList(List<MaintenanceCompany> departmentAllList,List<MaintenanceCompany> departmentList){
//		for (MaintenanceCompany map : departmentList) {
//			long chrildSequenceNbr=map.getSequenceNbr();
//			List<MaintenanceCompany> chrlidList=	getDepartmentList(chrildSequenceNbr);
//			if(chrlidList.size()>0) {
//				departmentAllList.addAll(chrlidList);
//				getDepartmentAllList(departmentAllList,chrlidList);
//			}
//		}
//		return departmentAllList;
//	}

	@Override
	public List<MaintenanceCompany> getDepartmentList(long sequenceNbr) {
		MaintenanceCompany companyDetail = maintenanceCompanyMapper.selectById(sequenceNbr);
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
				MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
		wrapper.eq(MaintenanceCompany::getIsDelete, false);
		wrapper.in(MaintenanceCompany::getType, Arrays.asList(PERSON, DEPARTMENT));
		wrapper.likeRight(MaintenanceCompany::getCode, companyDetail.getCode());
		List<MaintenanceCompany> maintenanceCompanyList = maintenanceCompanyMapper.selectList(wrapper);
		return maintenanceCompanyList;
	}

	public List<MaintenanceCompany> getPersonList(long sequenceNbr) {
		LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
				MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
		wrapper.eq(MaintenanceCompany::getIsDelete, false);
		wrapper.eq(MaintenanceCompany::getType, PERSON);
		wrapper.eq(MaintenanceCompany::getParentId, sequenceNbr);
		return maintenanceCompanyMapper.selectList(wrapper);
	}

	/**
	 * 根据维保单位查询所有机场单位(返回List<Map>类型) 不带分页
	 * 
	 * @param seq
	 * @return
	 */
	public List<Map<String, Object>> queryOrgUsrMsg(Long seq) {
		if (ValidationUtil.isEmpty(this.queryBySeq(seq))) {
			throw new BadRequest("参数校验失败.");
		} else {
			List<Map<String, Object>> companys = new ArrayList<>();
			// 机场单位列表基本信息
			List<OrgUsrDto> orgUsrDtos = this.baseMapper.selectOrgUsrList(seq);
			// 机场组装单位动态表单数据
			orgUsrDtos.forEach(orgUsrDto -> {
				Map<String, Object> map = Bean.BeantoMap(orgUsrDto);
				mapCopy(dynamicFormInstanceService.getOneMap(orgUsrDto.getSequenceNbr(), OrgPersonEnum.公司.getKey()),
						map);

				companys.add(map);
			});
			return companys;
		}
	}

	/**
	 * 根据维保单位查询所有机场单位(返回List<Map>类型) 带分页
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param seq
	 * @param amosUserId
	 * @return
	 */
	public Page<Map<String, Object>> queryOrgUsrMsgPage(int pageNum, int pageSize, Long seq, String amosUserId) {
		MaintenanceCompany maintenanceCompany = new MaintenanceCompany();
		if (ValidationUtil.isEmpty(seq)) {
			maintenanceCompany = getMaintenanceCompany(amosUserId);
		}
		// 机场单位列表基本信息
		if (pageNum == -1 || pageSize == -1) {
			pageSize = Integer.MAX_VALUE;
		}
		Page page = new Page(pageNum, pageSize);
		Page<Map<String, Object>> companys = new Page<>(pageNum, pageSize);
		Page<OrgUsrDto> pageResult = this.baseMapper.selectOrgUsrPageList(page, maintenanceCompany.getSequenceNbr());
		List<Map<String, Object>> finalResultMap = Lists.newArrayList();
		// 机场组装单位动态表单数据
		pageResult.getRecords().forEach(orgUsrDto -> {
			Map<String, Object> map = Bean.BeantoMap(orgUsrDto);
			mapCopy(dynamicFormInstanceService.getOneMap(orgUsrDto.getSequenceNbr(), OrgPersonEnum.公司.getKey()), map);
			finalResultMap.add(map);
		});
		companys.setRecords(finalResultMap);
		companys.setTotal(pageResult.getTotal());
		companys.setPages(pageResult.getPages());
		return companys;
	}

	/**
	 * 根据平台用户id查询登陆人所属维保单位
	 *
	 * @param amosUserId
	 * @return
	 */
	public MaintenanceCompany getMaintenanceCompany(String amosUserId) {
		MaintenanceCompany maintenanceCompany;
		DynamicFormInstance dyFormInstance = dynamicFormInstanceService.getOne(
				new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getFieldCode, "amosAccount")
						.eq(DynamicFormInstance::getFieldValue, amosUserId));
		if (ValidationUtil.isEmpty(dyFormInstance)) {
			throw new BadRequest("维保账号不存在或未关联系统账号.");
		}
		MaintenanceCompany person = this.getOne(new LambdaQueryWrapper<MaintenanceCompany>()
				.eq(MaintenanceCompany::getInstanceId, dyFormInstance.getInstanceId()));
		maintenanceCompany = this.getOne(new LambdaQueryWrapper<MaintenanceCompany>()
				.eq(MaintenanceCompany::getSequenceNbr, person.getParentId()));
		if (ValidationUtil.isEmpty(maintenanceCompany)) {
			throw new BadRequest("维保账号不存在或未关联系统账号.");
		}
		return maintenanceCompany;
	}

	public List<Map<String, Object>> queryCompanyMsg() {
		List<Map<String, Object>> companysMsg = new ArrayList<>();
		// 查询所有维保单位信息
		List<MaintenanceCompany> lists = this.list();
		lists.forEach(list -> {
			Map<String, Object> maintenanceCompany = new HashMap<>();
			maintenanceCompany.put("id", list.getSequenceNbr());
			maintenanceCompany.put("code", list.getCode());
			maintenanceCompany.put("name", list.getName());
			maintenanceCompany.put("type", 1);
			maintenanceCompany.put("parentId", null);
			// 查询该维保单位下的业主信息
			List<OrgUsrDto> orgUsrDtos = this.baseMapper.selectOrgUsrList(list.getSequenceNbr());
			orgUsrDtos.forEach(orgUsrDto -> {
				Map<String, Object> airCompany = new HashMap<>();
				airCompany.put("id", orgUsrDto.getSequenceNbr());
				airCompany.put("code", orgUsrDto.getBizOrgCode());
				airCompany.put("name", orgUsrDto.getBizOrgName());
				airCompany.put("type", 2);
				airCompany.put("parentId", list.getSequenceNbr());
				companysMsg.add(airCompany);
			});
			companysMsg.add(maintenanceCompany);
		});
		return companysMsg;
	}

	/**
	 * 复制map对象
	 * 
	 * @explain 将paramsMap中的键值对全部拷贝到resultMap中；
	 * @param paramsMap 被拷贝对象
	 * @param resultMap 拷贝后的对象
	 */
	private static void mapCopy(Map paramsMap, Map resultMap) {
		if (resultMap == null) {
			return;
		}
		if (paramsMap == null) {
			return;
		}
		Iterator it = paramsMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
		}
	}

	@Override
	public List<DynamicFormInstance> maintenancePersonExcleDtoToDynamicFormInstanceList(List<DynamicFormColumn> columns,
			MaintenancePersonExcleDto maintenancePersonExcleDto, long instanceId, List<DynamicFormInstance> list) {

		Map<String, Object> maintenancePersonExcleDtoMap = Bean.BeantoMap(maintenancePersonExcleDto);
		// 填充动态表单的属性

		columns.stream().forEach(item -> {
			if (maintenancePersonExcleDtoMap.containsKey(item.getFieldCode())) {
				DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
				String valueString = maintenancePersonExcleDtoMap.get(item.getFieldCode()).toString();
				Bean.copyExistPropertis(item, dynamicFormInstance);

				dynamicFormInstance.setAppKey(RequestContext.getAppKey());
				dynamicFormInstance.setInstanceId(instanceId);
				dynamicFormInstance.setSequenceNbr(sequence.nextId());
				dynamicFormInstance.setFormColumnId(item.getSequenceNbr());
				dynamicFormInstance.setFieldValue(maintenancePersonExcleDtoMap.get(item.getFieldCode()) != null
						? maintenancePersonExcleDtoMap.get(item.getFieldCode()).toString()
						: "");
				if (valueString.contains("@")) {
					String[] mapDetailArray = valueString.split("@");
					dynamicFormInstance.setFieldValue(mapDetailArray[0]);
					if (mapDetailArray.length > 1) {
						dynamicFormInstance.setFieldValueLabel(mapDetailArray[1]);
					}
				}
				if (dynamicFormInstance != null && dynamicFormInstance.getSequenceNbr().longValue() > 0) {
					list.add(dynamicFormInstance);
				}
			}

		});

		return list;
	}

	public boolean saveDynamicFormInstanceBatch(List<DynamicFormInstance> list) {
		dynamicFormInstanceService.saveBatch(list);
		return false;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveMaintenanceCompanyBatch(List<MaintenanceCompany> companyList, List<DynamicFormInstance> list) {
		saveDynamicFormInstanceBatch(list);
		this.saveBatch(companyList);
		return false;
	}

	/**
	 * 查询当前登陆用户所在维保单位下的维保人员列表部门列表,不分页
	 *
	 * @param companyId
	 * @param userId
	 * @return
	 */
	public List<Map<String, Object>> getPersonListByCompanyId(Long companyId, String userId) {
		MaintenanceCompany company;
		if (ValidationUtil.isEmpty(companyId)) {
			company = getMaintenanceCompany(userId);
			if (ValidationUtil.isEmpty(company)) {
				throw new BadRequest("用户不存在");
			}
		} else {
			company = this.getById(companyId);
		}
		// 查询公司下人列表
		List<MaintenanceCompany> personList = list(new LambdaQueryWrapper<MaintenanceCompany>()
				.eq(MaintenanceCompany::getIsDelete, false).eq(MaintenanceCompany::getType, PERSON)
				.likeRight(MaintenanceCompany::getCode, company.getCode()));
		List<Long> instanceIdList = Lists.transform(personList, MaintenanceCompany::getInstanceId);
		// 查询手机号
		List<DynamicFormInstance> dynamicFormInstanceList = dynamicFormInstanceService
				.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getFieldCode, "tel")
						.in(DynamicFormInstance::getInstanceId, instanceIdList));
		Map<Long, List<DynamicFormInstance>> dyMap = dynamicFormInstanceList.stream()
				.collect(Collectors.groupingBy(DynamicFormInstance::getInstanceId));
		List<Map<String, Object>> resultList = Lists.newArrayList();
		personList.forEach(person -> {
			Map<String, Object> map = Maps.newHashMap();
			map.put("sequenceNbr", person.getSequenceNbr());
			map.put("name", person.getName());
			map.put("tel", dyMap.get(person.getInstanceId()).get(0).getFieldValue());
			resultList.add(map);
		});
		return resultList;
	}
}