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

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.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.*;
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.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.feign.SupervisionFeign;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 机构/部门/人员表 服务实现类
 *
 * @author tb
 * @date 2021-06-18
 */

@Service
public class OrgUsrServiceImpl extends BaseService<OrgUsrDto, OrgUsr, OrgUsrMapper> implements IOrgUsrService {
	@Autowired
	DynamicFormInstanceServiceImpl alertFormValueServiceImpl;
	@Autowired
	DynamicFormColumnServiceImpl alertFormServiceImpl;
	@Resource
	OrgUsrMapper orgUsrMapper;
	@Autowired
	SupervisionFeign supervisionFeign;
	@Autowired
	ESOrgUsrService eSOrgUsrService;
	@Override
	public String selectUpUnitByParam(String id) {
		return this.baseMapper.selectUpUnitByParam(id);
	}

	public static List<OrgMenuDto> buildTreeParallel(List<OrgUsr> list) {

		List<OrgMenuDto> menuList = list.stream().map(o -> {
			OrgMenuDto menu = new OrgMenuDto(o.getSequenceNbr(), o.getBizOrgName(),
					ObjectUtils.isEmpty(o.getParentId()) ? 0L : Long.valueOf(o.getParentId()), o.getBizOrgType(), false,
					o.getBizOrgCode());
			return menu;
		}).collect(Collectors.toList());

		List<OrgMenuDto> result = new ArrayList<>();
		Map<Long, OrgMenuDto> map = new HashMap<>(menuList.size());
		menuList.forEach(e -> map.put(e.getKey(), e));
		Set<? extends Map.Entry<Long, ? extends OrgMenuDto>> entries = map.entrySet();
		entries.parallelStream().forEach(entry -> {
			OrgMenuDto value = entry.getValue();
			if (value != null) {
				OrgMenuDto treeDto = map.get(value.getParentId());
				if (treeDto != null) {
					List<OrgMenuDto> children = treeDto.getChildren();
					if (children == null) {
						children = new ArrayList<>();
						treeDto.setChildren(children);
					}
					children.add(value);
				} else {
					result.add(value);
				}
			}
		});
		return result;
	}

	@Override
	public List<OrgMenuDto> getTree(Long topId, Collection entityList, String packageURL, String IDMethodName,
			int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName, String OrgTypeMethodName)
			throws Exception {
		List<OrgMenuDto> resultList = new ArrayList<>();
		Class<?> clazz = Class.forName(packageURL);
		Method IDMethodNameme = null;
		switch (IDHierarchy) {
		case 1:
			IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
			break;
		case 2:
			IDMethodNameme = clazz.getSuperclass().getDeclaredMethod(IDMethodName);
			break;
		case 3:
			IDMethodNameme = clazz.getSuperclass().getSuperclass().getDeclaredMethod(IDMethodName);
			break;
		default:
			IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
			break;
		}

		Method NAMEMethodNameme = clazz.getDeclaredMethod(NAMEMethodName);
		Method PARENTIDMethodNameme = clazz.getDeclaredMethod(PARENTIDMethodName);
		Method OrgTypeMethodNameme = clazz.getDeclaredMethod(OrgTypeMethodName);
		// 获取顶层元素集合
		Long parentId;
		for (Object ob : entityList) {

			Object entity = clazz.cast(ob);

			parentId = !ObjectUtils.isEmpty(PARENTIDMethodNameme.invoke(entity))
					? Long.valueOf(String.valueOf(PARENTIDMethodNameme.invoke(entity)))
					: null;
//			if (parentId == null || topId ==parentId ) {
//				OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
//						String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
//						String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
//				resultList.add(menu);
//			}
			/*	*******************topId与parentId的等值判断，修改人陈浩 on 2021/07/21---start******************************/
			if (parentId == null ) {//topId与parentId的等值判断，修改人陈浩 on 2021/07/21
				OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
						String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
						String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
				resultList.add(menu);
			} else if(topId !=null && topId.longValue() ==parentId.longValue())
				 {
					OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
							String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
							String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
					resultList.add(menu);
				}
			/*	*******************topId与parentId的等值判断，修改人陈浩 on 2021/07/21---end******************************/
		}
		// 获取每个顶层元素的子数据集合
		for (OrgMenuDto entity : resultList) {
			entity.setChildren(getSub(entity.getKey(), entityList, packageURL, IDMethodName, IDHierarchy,
					NAMEMethodName, PARENTIDMethodName, OrgTypeMethodName));
		}
		return resultList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrgMenuDto> getSub(Long topId, @SuppressWarnings("rawtypes") Collection entityList, String packageURL,
			String IDMethodName, int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName,
			String OrgTypeMethodName) throws Exception {
		List<OrgMenuDto> childList = new ArrayList<>();
		@SuppressWarnings("rawtypes")
		Class clazz = Class.forName(packageURL);
		Method IDMethodNameme = null;
		switch (IDHierarchy) {
		case 1:
			IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
			break;
		case 2:
			IDMethodNameme = clazz.getSuperclass().getDeclaredMethod(IDMethodName);
			break;
		case 3:
			IDMethodNameme = clazz.getSuperclass().getSuperclass().getDeclaredMethod(IDMethodName);
			break;
		default:
			IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
			break;
		}
		Method OrgTypeMethodNameme = clazz.getDeclaredMethod(OrgTypeMethodName);
		Method NAMEMethodNameme = clazz.getDeclaredMethod(NAMEMethodName);
		Method PARENTIDMethodNameme = clazz.getDeclaredMethod(PARENTIDMethodName);

		Long parentId;
		// 子集的直接子对象
		for (Object ob : entityList) {
			Object entity = clazz.cast(ob);

			parentId = !ObjectUtils.isEmpty(PARENTIDMethodNameme.invoke(entity))
					? Long.valueOf(String.valueOf(PARENTIDMethodNameme.invoke(entity)))
					: null;

			if (parentId == null) {
				if (topId == parentId) {
					OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
							String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
							String.valueOf(OrgTypeMethodNameme.invoke(entity)));
					childList.add(menu);
				}
			} else {
				if (topId.longValue() == parentId.longValue()) {
					OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
							String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
							String.valueOf(OrgTypeMethodNameme.invoke(entity)));
					childList.add(menu);
				}
			}

		}

		// 子集的间接子对象
		for (OrgMenuDto entity : childList) {
			entity.setChildren(getSub(entity.getKey(), entityList, packageURL, IDMethodName, IDHierarchy,
					NAMEMethodName, PARENTIDMethodName, OrgTypeMethodName));
			if (entity.getChildren() != null) {
				entity.setLeaf(false);
			}
		}

		// 递归退出条件
		if (childList.size() == 0) {
			return null;
		}

		return childList;
	}

	@Override
	public List<Map<String, Object>> returnCompanyPersonMsg(List<Long> ids) throws Exception {
		List<Map<String, Object>> companyPersonMsg = new ArrayList<>();
		for (int i = 0; i < ids.size(); i++) {
			Map<String, Object> resultMap = new HashMap<>();
			// 查询出单位基本信息
			OrgUsr company = getById(ids.get(i));
			resultMap.put("id", company.getSequenceNbr());
			// 上级单位
			resultMap.put("upUnit", selectUpUnitByParam(company.getSequenceNbr() + ""));
			// 当前单位
			resultMap.put("currentUnit", company.getBizOrgName());
			// 下级单位
			Map<String, Object> downUnitColumnMap = new HashMap<>();
			downUnitColumnMap.put("is_delete", CommonConstant.IS_DELETE_00);
			downUnitColumnMap.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_COMPANY);
			downUnitColumnMap.put("parent_id", company.getSequenceNbr());
			QueryWrapper<OrgUsr> downUnitWrapper = new QueryWrapper<OrgUsr>();
			downUnitWrapper.allEq(downUnitColumnMap);
			List<OrgUsr> downList = list(downUnitWrapper);
			if (downList.size() == 0) {
				resultMap.put("downUnit", false);
			} else {
				resultMap.put("downUnit", true);
			}
			// 人员数量
			Map<String, Object> countPerson = new HashMap<>();
			countPerson.put("parent_id", company.getSequenceNbr());
			countPerson.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_PERSON);
			QueryWrapper<OrgUsr> personNumWrapper = new QueryWrapper<OrgUsr>();
			personNumWrapper.allEq(countPerson);
			int personNum = count(personNumWrapper);
			resultMap.put("personNum", personNum);
			if (0 == personNum) {
				continue;
			}
			List<Map<String, Object>> personList = new ArrayList<>();
			// 查询动态表单Phone
			Map<String, Object> phone = new HashMap<>();
			phone.put("instance_id", company.getSequenceNbr());
			phone.put("field_code", "companyPhone");
			QueryWrapper<DynamicFormInstance> phoneWrapper = new QueryWrapper<DynamicFormInstance>();
			phoneWrapper.allEq(phone);
			DynamicFormInstance phoneValue = alertFormValueServiceImpl.getOne(phoneWrapper);
			if (phoneValue == null) {
				resultMap.put("tel", "");
			} else {
				resultMap.put("tel", phoneValue.getFieldValue());
			}

			// 获取单位人员列表信息
			personList = listPerson(company.getSequenceNbr() + "").stream().map(p -> {
				Map<String, Object> person = new HashMap<>();
				person.put("tel", getValue(p.get("telephone"), null));
				person.put("img", getValue(p.get("personImg"), null));
				person.put("id", getValue(p.get("sequenceNbr"), null));
				person.put("name", getValue(p.get("bizOrgName"), null));
				person.put("zhiwei", getValue(p.get("administrativePositionCode"), null));
				person.put("unit", getValue(p.get("fireManagementPostCode"), null));
				return person;
			}).collect(Collectors.toList());
			resultMap.put("children", personList);
			companyPersonMsg.add(resultMap);
		}
		return companyPersonMsg;
	}

	private Object getValue(Object obj, Object defaultValue) {
		return ObjectUtils.isEmpty(obj) ? defaultValue : obj;
	}

	public List<Map<String, Object>> listPerson(String parentId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fields", alertFormServiceImpl.queryListByFormId(OrgPersonEnum.人员.getCode()));
		map.put("bizOrgType", OrgPersonEnum.人员.getKey());
		map.put("parentId", parentId);
		List<Map<String, Object>> list = this.baseMapper.selectPersonAllList(map);
		return list == null ? new ArrayList<Map<String, Object>>() : list;
	}

	public IPage<Map<String, Object>> pagePerson(String pageNum, String pageSize, Map<String, Object> req) {
		IPage<Map<String, Object>> pageBean = null;
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		Map<String, Object> map = new HashMap<>();
		map.put("bizOrgType", OrgPersonEnum.人员.getKey());
		if (!ObjectUtils.isEmpty(req.get("bizOrgName"))) {
			map.put("bizOrgName", req.get("bizOrgName"));
		}
		OrgUsr parent = this.getById(Long.valueOf(req.get("parentId").toString()));
		map.put("bizOrgCode", ObjectUtils.isEmpty(parent) ? null : parent.getBizOrgCode());
		req.remove("bizOrgName");
		req.remove("pageSize");
		req.remove("pageNum");
		req.remove("parentId");
		map.put("fieldsValue", req);
		map.put("fields", alertFormServiceImpl.queryListByFormId(OrgPersonEnum.人员.getCode()));
		pageBean.setTotal(this.baseMapper.selectPersonListCount(map));
		map.put("pageNum", (pageBean.getCurrent() - 1) * pageBean.getSize());
		map.put("pageSize", pageBean.getSize());

		List<Map<String, Object>> list = this.baseMapper.selectPersonList(map);

		pageBean.setRecords(list);
		return pageBean;
	}

	@Override
	public List<FormValue> getFormValue(Long id) throws Exception {
		// 动态表单数据
		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
		List<FormValue> formValue = new ArrayList<>();
		for (DynamicFormInstanceDto alertFormValue : list) {
			if (alertFormValue.getFieldValue() != null) {
				FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
						alertFormValue.getFieldType(), alertFormValue.getFieldValue(), alertFormValue.getBlock());
				formValue.add(value);
			} else {
				FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
						alertFormValue.getFieldType(), alertFormValue.getFieldValueLabel(), alertFormValue.getBlock());
				formValue.add(value);
			}
		}
		return formValue;
	}

	public List<FormValue> getFormValueDetail(Long id) throws Exception {
		// 动态表单数据
		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
		List<FormValue> formValue = new ArrayList<>();
		for (DynamicFormInstanceDto alertFormValue : list) {
			FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
					alertFormValue.getFieldType(), alertFormValue.getFieldValue(), alertFormValue.getBlock());
			formValue.add(value);
		}
		return formValue;
	}

	@Override
	public void saveOrgUsr(OrgUsr orgUsr, OrgUsr oriOrgUsr) throws Exception {

		if (oriOrgUsr.getParentId() != oriOrgUsr.getParentId()) {
			OrgUsr parent = getById(orgUsr.getParentId());
			if (parent != null && !ObjectUtils.isEmpty(parent.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
			updateChildOrgCode(oriOrgUsr.getBizOrgCode(), orgUsr.getBizOrgCode());
			orgUsr.setParentId(oriOrgUsr.getParentId());
		} 
		AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
		orgUsr.setRecDate(new Date());
		orgUsr.setRecUserId(me.getUserId());
		orgUsr.setRecUserName(me.getRealName());
		updateById(orgUsr);
	}

	private void updateChildOrgCode(String oriOrgCode, String targetOrgCode) {
		List<OrgUsr> list = queryOrgUsrList(oriOrgCode);
		if (ObjectUtils.isEmpty(list)) {
			return;
		}
		list.forEach(action -> {
			action.setBizOrgCode(action.getBizOrgCode().replace(oriOrgCode, targetOrgCode));
			updateById(action);
		});
	}

	public List<OrgUsr> queryOrgUsrList(String bizOrgCode) {
		return this.baseMapper.queryOrgUsrListByBizOrgCode(bizOrgCode);
	}

	@Override
	public void saveOrgUsrDynamicFormInstance(OrgUsr orgUsr, List<DynamicFormInstance> alertFromValuelist) throws Exception {
		orgUsr.setRecDate(new Date());
		AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
		orgUsr.setRecUserName(user.getRealName());
		orgUsr.setRecUserId(user.getUserId());
		// 单位新增情况
		save(orgUsr);
		// 填充主键
		alertFromValuelist.stream().forEach(alertFromValue -> {
			if (OrgPersonEnum.公司.getKey().equals(orgUsr.getBizOrgType())) {
				alertFromValue.setGroupCode(OrgPersonEnum.公司.getCode());
			} else if (OrgPersonEnum.部门.getKey().equals(orgUsr.getBizOrgType())) {
				alertFromValue.setGroupCode(OrgPersonEnum.部门.getCode());
			}
			alertFromValue.setInstanceId(orgUsr.getSequenceNbr());
		});
		// 保存动态表单数据
		alertFormValueServiceImpl.saveBatch(alertFromValuelist);
		OrgUsrFormDto formDto = this.selectCompanyById(orgUsr.getSequenceNbr());
		if (OrgPersonEnum.公司.getKey().equals(orgUsr.getBizOrgType())) {
			supervisionFeign.asyncOwner(formDto);
		}
	}

	@Override
	public void updateDynamicFormInstance(Long instanceId, List<DynamicFormInstance> fromValueList) {
		// 填充主键
		fromValueList.forEach(alertFromValue -> {
			alertFromValue.setInstanceId(instanceId);
		});
		List<DynamicFormInstanceDto> formList = alertFormValueServiceImpl.queryByCalledId(instanceId);

		Map<Long, DynamicFormInstanceDto> resourceMap = new HashMap<>();
		Map<Long, DynamicFormInstance> newResourceMap = new HashMap<>();
		formList.parallelStream().forEach(form -> {
			resourceMap.put(form.getFormColumnId(), form);
		});
		
		List<DynamicFormInstance> updateList = new ArrayList<>();
		List<DynamicFormInstance> addList = new ArrayList<>();
		List<Long> deleteList = new ArrayList<>();
		
		fromValueList.parallelStream().forEach(submitFormItem -> {
			if ( resourceMap.containsKey(submitFormItem.getFormColumnId())) {
				DynamicFormInstanceDto oldForm = resourceMap.get(submitFormItem.getFormColumnId());
				submitFormItem.setSequenceNbr(oldForm.getSequenceNbr());
				updateList.add(submitFormItem);
			}else {
				addList.add(submitFormItem);
			}
			newResourceMap.put(submitFormItem.getFormColumnId(), submitFormItem);
		});
		

		newResourceMap.keySet().parallelStream().forEach(form -> {
			resourceMap.remove(form);
		});
		
		resourceMap.keySet().parallelStream().forEach(action -> {
			deleteList.add(resourceMap.get(action).getSequenceNbr());
		});
		
		if (deleteList.size() > 0) {
			alertFormValueServiceImpl.deleteBatchSeq(deleteList);
		}
		
		if (updateList.size() > 0) {
			alertFormValueServiceImpl.updateBatchById(updateList);
		}
		
		if (addList.size() > 0) {
			alertFormValueServiceImpl.saveBatch(addList);
		}
	}

	@Override
	public Map<String, Object> selectForShowById(OrgUsr orgUsr, Long id) throws Exception {
		QueryWrapper<DynamicFormColumn> queryWrapper = new QueryWrapper<DynamicFormColumn>();
		queryWrapper.eq("group_code", OrgPersonEnum.人员.getCode());
		List<DynamicFormColumn> alertForms = alertFormServiceImpl.list(queryWrapper);
		// 动态表单数据
		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
		Map<String, Object> result = new HashMap<>();
		result = Bean.BeantoMap(orgUsr);
		result.put("parenName", getById(orgUsr.getParentId()).getBizOrgName());
		// 放入所有动态表单数据
		for (DynamicFormColumn alertForm : alertForms) {
			result.put(alertForm.getFieldCode(), null);
		}
		for (DynamicFormInstanceDto alertFormValue : list) {
			result.put(alertFormValue.getFieldCode(),
					ObjectUtils.isEmpty(alertFormValue.getFieldValueLabel()) ? alertFormValue.getFieldValue()
							: alertFormValue.getFieldValueLabel());
		}
		return result;
	}

	@Override
	public List<OrgUsr> selectCompanyDepartmentMsg() {
		List<OrgUsr> list = this.baseMapper.selectCompanyDepartmentMsg();
		if (list == null) {
			return new ArrayList<>();
		}
		list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
		return list;
	}

    public List<OrgUsr> selectCompanyList() {
        List<OrgUsr> list =
                list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete, false).eq(OrgUsr::getBizOrgType,
                        "COMPANY"));
        if (list == null) {
            return new ArrayList<>();
        }
        list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
        return list;
    }

	@Override
	public void saveOrgUsr(OrgUsrDto OrgUsrVo) throws Exception {
		OrgUsr orgUsr = new OrgUsr();
		BeanUtils.copyProperties(OrgUsrVo, orgUsr);
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
		if (OrgUsrVo.getParentId() != null) {
			OrgUsr parent = getById(OrgUsrVo.getParentId());
			if (parent != null && ObjectUtils.isEmpty(OrgUsrVo.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
		} else {
			orgUsr.setBizOrgCode(getOrgCodeStr());
		}
		saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.getDynamicFormValue());
		
		 /**
         * 同步保存ES
         */
		eSOrgUsrService.saveAlertCalledToES(orgUsr);
	}

	@Override
	public void saveOrgPerson(OrgPersonDto OrgPersonVo) throws Exception {
		OrgUsr orgUsr = new OrgUsr();
		BeanUtils.copyProperties(OrgPersonVo, orgUsr);
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
		if (OrgPersonVo.getParentId() != null) {
			OrgUsr parent = getById(OrgPersonVo.getParentId());
			if (parent != null && ObjectUtils.isEmpty(OrgPersonVo.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
		} else {
			orgUsr.setBizOrgCode(getOrgCodeStr());
		}

		if (!ObjectUtils.isEmpty(OrgPersonVo.getAmosOrgId())) {
			AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
			OrgPersonVo.setAmosOrgCode(user.getRealName());
		}

		saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
	}





	public void saveOrgPersonExcel(OrgUsrExcelDto OrgPersonVo) throws Exception {
		OrgUsr orgUsr = new OrgUsr();
		BeanUtils.copyProperties(OrgPersonVo, orgUsr);
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
		if (OrgPersonVo.getParentId() != null) {
			OrgUsr parent = getById(OrgPersonVo.getParentId());
			if (parent != null && ObjectUtils.isEmpty(OrgPersonVo.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
		} else {
			orgUsr.setBizOrgCode(getOrgCodeStr());
		}



		if (!ObjectUtils.isEmpty(OrgPersonVo.getAmosOrgId())) {
			AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
			OrgPersonVo.setAmosOrgCode(user.getRealName());
		}

		saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
	}

	@Override
	public void updateByIdOrgUsr(OrgUsrDto OrgUsrVo, Long id) throws Exception {
		// 修改单位信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oriOrgUsr = getById(id);
		BeanUtils.copyProperties(OrgUsrVo, orgUsr);
		saveOrgUsr(orgUsr, oriOrgUsr);
		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgUsrVo.getDynamicFormValue());
		 /**
         * 同步保存ES
         */
		eSOrgUsrService.saveAlertCalledToES(orgUsr);
	}

	@Override
	public void updateByIdOrgPerson(OrgPersonDto OrgPersonVo, Long id) throws Exception {
		// 修改人员信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oriOrgUsr = getById(id);
		BeanUtils.copyProperties(OrgPersonVo, orgUsr);
		orgUsr.setSequenceNbr(id);
		if (!ObjectUtils.isEmpty(OrgPersonVo.getAmosOrgId())) {
			AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
			oriOrgUsr.setAmosOrgCode(user.getRealName());
			oriOrgUsr.setAmosOrgId(user.getUserId());
			orgUsr.setAmosOrgCode(user.getRealName());
			orgUsr.setAmosOrgId(user.getUserId());
		}

		saveOrgUsr(orgUsr, oriOrgUsr);
		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgPersonVo.getDynamicFormValue());
	}

	@Override
	public OrgUsrFormDto selectCompanyById(Long id) throws Exception {
		OrgUsr orgUsr = getById(id);
		// 动态表单数据
		List<FormValue> formValue = getFormValue(id);
		OrgUsrFormDto orgUsrFormVo = new OrgUsrFormDto();
		orgUsrFormVo.setDynamicFormAlert(formValue);
		BeanUtils.copyProperties(orgUsr, orgUsrFormVo);
		return orgUsrFormVo;
	}

	@Override
	public IPage<OrgUsr> bizOrgTypeListPage(String pageNum, String pageSize, String bizOrgType) throws Exception {

		Map<String, Object> columnMap = new HashMap<>();
		columnMap.put("is_delete", CommonConstant.IS_DELETE_00);
		columnMap.put("biz_org_type", bizOrgType);
		Page<OrgUsr> pageBean = new Page<OrgUsr>();
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		QueryWrapper<OrgUsr> queryWrapper = new QueryWrapper<OrgUsr>();
		queryWrapper.allEq(columnMap);
		queryWrapper.orderByAsc("sequence_nbr");
		return page(pageBean, queryWrapper);
	}

	@Override
	public void saveDepartment(List<OrgDepartmentDto> OrgDepartmentVo, Long id) throws Exception {
		for (int i = 0; i < OrgDepartmentVo.size(); i++) {
			// 导入部门信息的前提条件：单位信息已经存在
			if (getById(id) != null) {
				OrgUsr orgUsr = new OrgUsr();
				BeanUtils.copyProperties(OrgDepartmentVo.get(i), orgUsr);
				orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_DEPARTMENT);
				saveOrgUsrDynamicFormInstance(orgUsr, OrgDepartmentVo.get(i).getDynamicFormValue());
			}
		}
	}

	@Override
	public void saveCompany(List<OrgUsrDto> OrgUsrVo) throws Exception {
		for (int i = 0; i < OrgUsrVo.size(); i++) {
			OrgUsr orgUsr = new OrgUsr();
			BeanUtils.copyProperties(OrgUsrVo.get(i), orgUsr);
			orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
			saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.get(i).getDynamicFormValue());
		}
	}

	@Override
	public OrgPersonFormDto selectPersonById(Long id) throws Exception {
		OrgUsr orgUsr = getById(id);
		// 动态表单数据
		List<FormValue> formValue = getFormValue(id);
		OrgPersonFormDto orgPersonFormVo = new OrgPersonFormDto(formValue);
		BeanUtils.copyProperties(orgUsr, orgPersonFormVo);
		OrgUsr parent = getById(orgUsr.getParentId());
		if (!ObjectUtils.isEmpty(parent)) {
			orgPersonFormVo.setParentName(parent.getBizOrgName());
		}

		return orgPersonFormVo;
	}

	@Override
	public OrgPersonFormDto selectPersonByIdDetail(Long id) throws Exception {
		OrgUsr orgUsr = getById(id);
		// 动态表单数据
		List<FormValue> formValue = getFormValueDetail(id);
		OrgPersonFormDto orgPersonFormVo = new OrgPersonFormDto(formValue);
		BeanUtils.copyProperties(orgUsr, orgPersonFormVo);
		orgPersonFormVo.setParentName(getById(orgUsr.getParentId()).getBizOrgName());
		return orgPersonFormVo;
	}

	@Override
	public List<OrgMenuDto> selectPersonTree() throws Exception {
		Map<String, Object> columnMap = new HashMap<>();
		columnMap.put("is_delete", CommonConstant.IS_DELETE_00);
		columnMap.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_PERSON);
		Collection<OrgUsr> list = listByMap(columnMap);
		return getTree(null, list, OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId",
				"getBizOrgType");
	}

	@Override
	public void savePersonList(List<OrgPersonDto> OrgPersonVo) throws Exception {
		for (int i = 0; i < OrgPersonVo.size(); i++) {
			OrgUsr orgUsr = new OrgUsr();
			BeanUtils.copyProperties(OrgPersonVo.get(i), orgUsr);
			orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
			saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.get(i).getDynamicFormValue());
		}
	}

	@Override
	public void saveOrgDepartment(OrgDepartmentDto OrgDepartmentVo) throws Exception {
		OrgUsr orgUsr = new OrgUsr();
		BeanUtils.copyProperties(OrgDepartmentVo, orgUsr);
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_DEPARTMENT);
		if (OrgDepartmentVo.getParentId() != null) {
			OrgUsr parent = getById(OrgDepartmentVo.getParentId());
			if (parent != null && ObjectUtils.isEmpty(OrgDepartmentVo.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
		} else {
			orgUsr.setBizOrgCode(getOrgCodeStr());
		}
		saveOrgUsrDynamicFormInstance(orgUsr, OrgDepartmentVo.getDynamicFormValue());
	}

	@Override
	public void updateByIdOrgDepartment(OrgDepartmentDto OrgDepartmentVo, Long id) throws Exception {
		// 修改部门信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oriOrgUsr = getById(id);
		BeanUtils.copyProperties(OrgDepartmentVo, orgUsr);
		saveOrgUsr(orgUsr, oriOrgUsr);
		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgDepartmentVo.getDynamicFormValue());
	}

	@Override
	public OrgDepartmentFormDto selectDepartmentById(Long id) throws Exception {
		OrgUsr orgUsr = getById(id);
		// 动态表单数据
		List<FormValue> formValue = getFormValue(id);
		OrgDepartmentFormDto orgDepartmentFormVo = new OrgDepartmentFormDto(formValue);
		BeanUtils.copyProperties(orgUsr, orgDepartmentFormVo);
		return orgDepartmentFormVo;
	}

	@Override
	public List<Map<String, Object>> selectForShowByListId(List<Long> ids) throws Exception {
		List<Map<String, Object>> personResult = new ArrayList<>();
		for (int i = 0; i < ids.size(); i++) {
			OrgUsr orgUsr = getById(ids.get(i));
			Map<String, Object> result = selectForShowById(orgUsr, ids.get(i));
			personResult.add(result);
		}
		return personResult;
	}





	@Override
	public List<CompanyDto> listContractDto(Integer pageNum, Integer pageSize, RequestData requestData) {
		if (null == pageNum || null == pageSize) {
			pageNum = 1;
			pageSize = Integer.MAX_VALUE;
		} else {
			pageNum = (pageNum - 1) * pageSize;
		}
		return orgUsrMapper.listContractDto(pageNum, pageSize, requestData);
	}

	@Override
	public Integer listContractDtoCount(RequestData par) {
		return orgUsrMapper.listContractDtoCount( par);
	}






	public static String getOrgCodeStr() {
		return TreeParser.genTreeCode();
	}

	public void importByExcel(List<OrgPersonExcelDto> list) {
		list.forEach(item -> {
			OrgPersonDto orgPersonDto = new OrgPersonDto();
			orgPersonDto = Bean.toPo(item, orgPersonDto);
			List<DynamicFormInstance> alertFormValueList = new ArrayList<>();
			if (item.getPersonNumber() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(102L, OrgPersonEnum.人员.getCode(), "员工编号",
						"personNumber", item.getPersonNumber(), null, false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getCertificatesType() != null) {
				String certificatesType = item.getCertificatesType();
				String[] split = certificatesType.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(23L, OrgPersonEnum.人员.getCode(), "证件类型",
						"certificatesTypeCode", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getGender() != null) {
				String gender = item.getGender();
				String[] split = gender.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(22L, OrgPersonEnum.人员.getCode(), "性别",
						"gender", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getCertificatesNumber() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(100L, OrgPersonEnum.人员.getCode(), "证件号码",
						"certificatesNumber", item.getCertificatesNumber(), null, false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getTelephone() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(24L, OrgPersonEnum.人员.getCode(), "联系电话",
						"telephone", item.getTelephone(), null, false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getState() != null) {
				String state = item.getState();
				String[] split = state.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(25L, OrgPersonEnum.人员.getCode(), "人员状态",
						"stateCode", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getSafetyTraining() != null) {
				String safetyTraining = item.getSafetyTraining();
				String[] split = safetyTraining.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(29L, OrgPersonEnum.人员.getCode(),
						"是否进行安全培训", "safetyTraining", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getAdministrativePosition() != null) {
				String administrativePosition = item.getAdministrativePosition();
				String[] split = administrativePosition.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(28L, OrgPersonEnum.人员.getCode(), "行政职务",
						"administrativePositionCode", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getInternalPosition() != null) {
				String internalPosition = item.getInternalPosition();
				String[] split = internalPosition.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(26L, OrgPersonEnum.人员.getCode(),
						"消防管理组织机构内部职务", "internalPositionCode", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getFireManagementPost() != null) {
				String fireManagementPost = item.getFireManagementPost();
				String[] split = fireManagementPost.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(27L, OrgPersonEnum.人员.getCode(), "消防管理岗位",
						"fireManagementPostCode", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getPositionType() != null) {
				String positionType = item.getPositionType();
				String[] split = positionType.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(30L, OrgPersonEnum.人员.getCode(), "岗位类型",
						"positionType", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getCertificateType() != null) {
				String certificateType = item.getCertificateType();
				String[] split = certificateType.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(31L, OrgPersonEnum.人员.getCode(), "持证类别",
						"certificateType", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getHoldingTime() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(32L, OrgPersonEnum.人员.getCode(), "持证时间",
						"holdingTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.getHoldingTime()), null,
						false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getAuditCycle() != null) {
				String auditCycle = item.getAuditCycle();
				String[] split = auditCycle.split("@");
				DynamicFormInstance alertFormValue = new DynamicFormInstance(33L, OrgPersonEnum.人员.getCode(), "审核周期",
						"auditCycle", split[0], split[1], false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getPersonImg() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(34L, OrgPersonEnum.人员.getCode(), "人员照片",
						"personImg", item.getPersonImg(), null, false);
				alertFormValueList.add(alertFormValue);
			}
			if (item.getCertificateImg() != null) {
				DynamicFormInstance alertFormValue = new DynamicFormInstance(101L, OrgPersonEnum.人员.getCode(),
						"重点工种资质证书", "certificateImg", item.getCertificateImg(), null, false);
				alertFormValueList.add(alertFormValue);
			}
			try {
				orgPersonDto.setDynamicFormValue(alertFormValueList);
				this.saveOrgPerson(orgPersonDto);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}

	public List<OrgPersonExcelDto> queryOrgPersonDtoList(boolean isDelete) {

		List<OrgPersonExcelDto> excelOrgPersonDtoList = orgUsrMapper.queryOrgPersonDtoList(isDelete);

		return excelOrgPersonDtoList;
	}

	/**
	 * 根据id查询当前单位下的所有子单位、部门
	 *
	 * @param orgUserId
	 * @return
	 */
	public List<OrgUsr> listOrgUserById(Long orgUserId) {
		return this.baseMapper.listOrgUserById(orgUserId);
	}

	public List<CompanyPerson> returnCompanyPerson(List<Long> ids) {
		if (ObjectUtils.isEmpty(ids)) {
			return null;
		}
		return ids.stream().map(m -> {
			OrgUsr org = getById(m);
			if (ObjectUtils.isEmpty(org)) {
				return null;
			}
			CompanyPerson company = new CompanyPerson();
			BeanUtils.copyProperties(org, company);
			company.setPersons(this.queryForListByParentIdAndOrgType(org.getSequenceNbr(), OrgPersonEnum.人员.getKey()));
			return company;
		}).filter(c -> {
			return c != null;
		}).collect(Collectors.toList());
	}

	public List<OrgUsrDto> queryForListByParentIdAndOrgType( Long parentId, String bizOrgType) {
		return this.queryForList(null, false, parentId, bizOrgType);
	}

	public OrgUsrDto getOrg(String amosUserId) {
		OrgUsrDto person = queryForListByParentIdAndOrgType(amosUserId);
		if (ObjectUtils.isEmpty(person)) {
			return null;
		}
		return this.queryBySeq(Long.valueOf(person.getParentId()));
	}
	
	public OrgUsrDto queryForListByParentIdAndOrgType( String amosOrgId) {
		return this.queryModelByParams( amosOrgId );
	}

	@Override
	public List<OrgUsrzhDto> getOrgUsrzhDto(String  name) {
		// TODO Auto-generated method stub
		List<OrgUsrzhDto> list=orgUsrMapper.getOrgUsrzhDto(name);
		return list;
	}

	@Override
	public List<ESOrgUsrDto> selectByIddata(String name) {
		//获取所有单位
  	  QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();
  	  
  	  wrapper.in("biz_org_type", "DEPARTMENT","COMPANY");
  	  wrapper.eq("is_delete", 0);
  	  if(name!=null&&!"".equals(name)) {
  		 wrapper.like("biz_org_name", name);
  	  }
     
  	  List<OrgUsr>  list = this.list(wrapper);
  	  List<ESOrgUsrDto> lidataDtos=new ArrayList();
    	list.forEach(orgUsr->{
  		ESOrgUsrDto data=new ESOrgUsrDto();
  		data.setSequenceNbr(orgUsr.getSequenceNbr());
  		data.setBizOrgName(orgUsr.getBizOrgName());
  		lidataDtos.add(data);
  	});  	  
	  return lidataDtos;
	}

	@Override
	public List<Map<String, Object>> getparent() {
		return orgUsrMapper.getparent();
	}

	@Override
	public List<OrgUsrExcelDto> exportToExcel() {
		return orgUsrMapper.exportToExcel();
	}

	public List<OrgUsr> getCompanyDetailTree() {
		LambdaQueryWrapper<OrgUsr> wrapper= new LambdaQueryWrapper<OrgUsr>(); 
		wrapper.eq(OrgUsr::getBizOrgType, "COMPANY");
		wrapper.eq(OrgUsr::getIsDelete, false);
		return	this.baseMapper.selectList(wrapper);
	}
	
	
}


	