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

import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.*;

import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDataSyncService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.commons.lang3.ObjectUtils;
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.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.Menu;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.mapper.FirefightersMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFirefightersService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;

/**
 * 消防队员 服务实现类
 *
 * @author tb
 * @date 2021-06-07
 */
@Service
public class FirefightersServiceImpl extends BaseService<FirefightersDto, Firefighters, FirefightersMapper>
		implements IFirefightersService {

	@Autowired
	FirefightersMapper firefightersMapper;
	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;
	@Autowired
	FirefightersContactsServiceImpl firefightersContactsService;
	@Autowired
	DataDictionaryMapper dataDictionaryMapper;
	@Autowired
	OrgUsrServiceImpl orgUsrService;
	@Autowired
	FirefightersContactsServiceImpl ifirefightersContactsService;
	@Autowired
	private OrgUsrMapper orgUsrMapper;

	@Autowired
	private IDataSyncService dataSyncService;

	@Override
	public List<FirefightersZhDto> getFirefighters(int pageNum, int pageSize, FirefightersDto par) {
		return firefightersMapper.getFirefighters(pageNum, pageSize, par);
	}

	@Override
	public Map<String, Long> getFirefightersCount(int pageNum, int pageSize, FirefightersDto par) {
		// TODO Auto-generated method stub
		return firefightersMapper.getFirefightersCount(pageNum, pageSize, par);
	}

	@Override
	public Map<String, Object> listToSelectById(Long id) {
		// TODO Auto-generated method stub
		return firefightersMapper.listToSelectById(id);
	}

	@Override
	public void saveFirefighters(FirefightersInfoDto firefighters) {
		Firefighters firefighter = firefighters.getFirefighters();
		// 现居住地保存地址信息 户籍所在地信息 BUG3553 bykongfm
		// BUG2168 居住地户籍所在地为空判断 bykongfm
		if (ObjectUtils.isNotEmpty(firefighter.getResidenceDetails())) {
			FeignClientResult<RegionModel> region = Systemctl.regionClient
					.getRegion(Long.parseLong(firefighter.getResidenceDetails()));
			firefighter.setResidence(region.getResult().getRegionName());
		}
		if (ObjectUtils.isNotEmpty(firefighter.getNativePlace())) {
			FeignClientResult<RegionModel> nativePlace = Systemctl.regionClient
					.getRegion(Long.parseLong(firefighter.getNativePlace()));
			firefighter.setNativePlaceValue(nativePlace.getResult().getRegionName());
		}
		save(firefighter);
		if(ObjectUtils.isNotEmpty(firefighters.getFirefightersContacts())){
			FirefightersContacts firefightersContact = firefighters.getFirefightersContacts();
			firefightersContact.setFirefightersId(firefighter.getSequenceNbr());
			if (ObjectUtils.isNotEmpty(firefightersContact.getSequenceNbr())) {
				firefightersContactsService.updateById(firefightersContact);
			} else {
				firefightersContactsService.save(firefightersContact);
			}
			firefighters.setFirefightersContacts(firefightersContact);
		}
		firefighters.setFirefighters(firefighter);
	}

	@Override
	public Firefighters selectByAmosOrgId(Long id) {
		QueryWrapper<Firefighters> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("amos_user_id", id);
		queryWrapper.eq("is_delete", 0);
		Firefighters firefighters = firefightersMapper.selectOne(queryWrapper);
		return firefighters;
	}

    /**
	 * 导出列表
	 */
	public List<FirefightersExcelDto> exportToExcel(@Condition(Operator.eq) Boolean isDelete, Map par) {
		if (par == null || par.size() < 1) {
			return firefightersMapper.exportToExcel(isDelete, null, null, null, null, null, null,null);
		}
		String name = par.containsKey("name") ? par.get("name").toString() : null;
		String postQualification = par.containsKey("postQualification") ? par.get("postQualification").toString()
				: null;
		String fireTeamId = par.containsKey("fireTeamId") ? par.get("fireTeamId").toString() : null;
		String state = par.containsKey("state") ? par.get("state").toString() : null;
		String areasExpertise = par.containsKey("areasExpertise") ? par.get("areasExpertise").toString() : null;
		String jobTitle = par.containsKey("jobTitle") ? par.get("jobTitle").toString() : null;
		String bizOrgCode = par.containsKey("bizOrgCode") ?  par.get("bizOrgCode").toString() : null;
		return firefightersMapper.exportToExcel(isDelete, name, postQualification, fireTeamId, state, areasExpertise,
				jobTitle,bizOrgCode);
	}

	/**
	 * 导出列表
	 */
	public List<OrgUsrFireExcelDto> exportToExcelNew(@Condition(Operator.eq) Boolean isDelete, Map par) {
		if (par == null || par.size() < 1) {
			return firefightersMapper.exportToExcelNew(isDelete, null, null, null, null, null, null,null);
		}
		String name = par.containsKey("name") ? par.get("name").toString() : null;
		String postQualification = par.containsKey("postQualification") ? par.get("postQualification").toString()
				: null;
		String fireTeamId = par.containsKey("fireTeamId") ? par.get("fireTeamId").toString() : null;
		String state = par.containsKey("state") ? par.get("state").toString() : null;
		String areasExpertise = par.containsKey("areasExpertise") ? par.get("areasExpertise").toString() : null;
		String jobTitle = par.containsKey("jobTitle") ? par.get("jobTitle").toString() : null;
		String bizOrgCode = par.containsKey("bizOrgCode") ?  par.get("bizOrgCode").toString() : null;
		return firefightersMapper.exportToExcelNew(isDelete, name, postQualification, fireTeamId, state, areasExpertise,
				jobTitle,bizOrgCode);
	}

	@Override
	public List<Menu> getFirefightersJobTitleCount(String bizOrgCode) throws Exception {

//		QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("type", "GWMC");
//		queryWrapper.orderByAsc("sort_num");
//		Collection<DataDictionary> list = iDataDictionaryService.list(queryWrapper);
		Collection<DataDictionary> list =dataDictionaryMapper.getFirefightersJobTitle("GWMC");

		List<Menu> menus = TreeParser.getTree(null, list, DataDictionary.class.getName(), "getCode", 0, "getName",
				"getParent", firefightersMapper.getFirefightersJobTitleCount(bizOrgCode),"getTreeCode");
		for (Menu m:menus
			 ) {
			if( null != m.children) {
				List<Menu> children = m.getChildren();
				int count = m.num;
				for (Menu mm:children
					 ) {
					count = count + mm.num;
				}
				m.setNum(count == 0 ? m.getNum() : count);
			}
		}
		return menus;
	}

	public List<Map<String,String>> getFirefightersName() {

		return firefightersMapper.getFirefightersName();
	}

	public List<FirefightersDto> queryById(String[] gw,String name){


		return firefightersMapper.queryById(gw,name);
	}
    /**
     * 获取指定岗位名称下的队伍人员电话号码信息
     * @param teamId
     * @param jobTitleArray
     * @return
     */
	public List<Map<String, Object>> getDetailByTeamIdAndJobTitle(Long teamId,List<String> jobTitleArray) {
		LambdaQueryWrapper<Firefighters> wrapper = new LambdaQueryWrapper<Firefighters>();
		if(jobTitleArray!=null && jobTitleArray.size()>0) {
			wrapper.in(Firefighters::getJobTitleCode, jobTitleArray);
		}
		wrapper.eq(Firefighters::getIsDelete, false);
		wrapper.eq(Firefighters::getFireTeamId, teamId);
		wrapper.select(Firefighters::getMobilePhone);
		return	this.baseMapper.selectMaps(wrapper);
	}
	 /**
     * 获取指定用户ID下的队伍人员电话号码信息
     * @return
     */
	public List<Map<String, Object>> getDetailByIds(List<Long> ids) {
		LambdaQueryWrapper<Firefighters> wrapper = new LambdaQueryWrapper<Firefighters>();
		wrapper.in(Firefighters::getSequenceNbr, ids);
		wrapper.eq(Firefighters::getIsDelete, false);
		wrapper.select(Firefighters::getMobilePhone);
		return	this.baseMapper.selectMaps(wrapper);
	}

	public Object getAllFirefightersPerson(String jobId,String bizOrgCode) {
		return firefightersMapper.selectNormalFirePerson(jobId,bizOrgCode);
	}



	@Override
    @Transactional(rollbackFor = Exception.class)
	public PeopleInfoDto updatePeopleById(PeopleInfoDto peopleInfoDto, Long id) {
		// 1.动态表单
		if(!ValidationUtil.isEmpty(peopleInfoDto.getFirefighters().getAmosUserId())) {
			AgencyUserModel amosUser = Privilege.agencyUserClient.queryByUserId(peopleInfoDto.getFirefighters().getAmosUserId()).getResult();
			peopleInfoDto.getFirefighters().setAmosName(amosUser.getRealName());
		} else {
			peopleInfoDto.getFirefighters().setAmosUserId(null);
			peopleInfoDto.getFirefighters().setAmosName(null);
		}
		OrgUsr orgUsr = orgUsrService.peopleSaveOrgUsr(peopleInfoDto.getFirefighters());

		OrgPersonDto orgPersonDto = new OrgPersonDto();
		BeanUtils.copyProperties(orgUsr, orgPersonDto);
		List<DynamicFormInstance> dynamicFormInstances = orgUsrService.dynamicFormColumn(peopleInfoDto, false);
		orgPersonDto.setDynamicFormValue(dynamicFormInstances);
		try {
			orgUsrService.updateByIdOrgPerson(orgPersonDto, id);
		} catch (Exception e) {
			log.error("动态表单更新出错");
		}

		// 2.更新岗位
		orgUsrService.saveFirefightersPost(peopleInfoDto.getPostEduDtoObj(), id);

		// 3.消防人员更新消防表
		if ("1".equals(peopleInfoDto.getFirefighters().getPeopleType())){
			// 更新紧急联系人
			ifirefightersContactsService.updateById(peopleInfoDto.getFirefightersContacts());
		}
		//  巡检站端与中心级数据同步
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			@Override
			public void afterCommit() {
				// 事物提交后业务逻辑
				dataSyncService.OrgUsrSyncDtoDataSync(id);
			}
		});
		return peopleInfoDto;
	}

	@Override
	public Firefighters getFirefightersByUserId(String sequenceNbr) {
		LambdaQueryWrapper<Firefighters> wrapper = new LambdaQueryWrapper<Firefighters>();
		wrapper.eq(Firefighters::getOrgUsrId, sequenceNbr);
		wrapper.eq(Firefighters::getIsDelete, false);
		return this.baseMapper.selectOne(wrapper);
	}

	@Override
	public void saveFirefightersByUser(PeopleInfoDto firefighters) {
		orgUsrService.saveFirefighters(firefighters);
	}

	public Map<String, String> getPersonByCodes(List<String> list) {
		List<Firefighters> personByCodes = firefightersMapper.getPersonByCodes(list);
		Map<String, String> personGenderMap = new HashMap<>();
		for (Firefighters personByCode : personByCodes) {
			personGenderMap.put(personByCode.getEmployeeNumber(), personByCode.getGender());
		}
		return personGenderMap;
	}

	@Override
	public BigScreen1VO getFireForceInfoByCode(String companyCode) {
		String bizOrgCode = null;
		if (StringUtils.isNotEmpty(companyCode)) {
			OrgUsr orgUsr = orgUsrMapper.queryByCompanyCode(companyCode);
			if (ObjectUtils.isNotEmpty(orgUsr)) {
				bizOrgCode = orgUsr.getBizOrgCode();
			}
		}
		BigScreen1VO bigScreen1VO = new BigScreen1VO();
//		Integer teamCount = firefightersMapper.getTeamCountByCode(companyCode);
		Map<String, Object> fireForceInfoByCode = firefightersMapper.getFireForceInfoByCode(bizOrgCode);
		List<Map<String, Object>> personInfoList = new ArrayList<>();
		HashMap<String, Object> fireInfo = new HashMap<>();
		fireInfo.put("fireCer", fireForceInfoByCode.get("fireCer"));
		fireInfo.put("unfireCer", fireForceInfoByCode.get("unfireCer"));
		fireInfo.put("firefightersNum", fireForceInfoByCode.get("firefightersNum"));
		fireInfo.put("fireAbs", fireForceInfoByCode.get("fireAbs"));
		personInfoList.add(fireInfo);
		HashMap<String, Object> operInfo = new HashMap<>();
		operInfo.put("operCer", fireForceInfoByCode.get("operCer"));
		operInfo.put("unoperCer", fireForceInfoByCode.get("unoperCer"));
		operInfo.put("opertNum", fireForceInfoByCode.get("opertNum"));
		operInfo.put("operAbs", fireForceInfoByCode.get("operAbs"));
		personInfoList.add(operInfo);
		bigScreen1VO.setPersonList(personInfoList);
		List<Map<String, Object>> teamInfoList = new ArrayList<>();
		HashMap<String, Object> teamInfoMap = new HashMap<>();
//		teamInfoMap.put("teamNum", teamCount);
		teamInfoList.add(teamInfoMap);
		bigScreen1VO.setTeamNumInfo(teamInfoList);
//		bigScreen1VO.setTeamNum(teamCount);
//		bigScreen1VO.setFirefightersInfo(fireForceInfoByCode);
		List<Map<String, Object>> stationSignInfo = firefightersMapper.getStationSignInfo(bizOrgCode);
		bigScreen1VO.setUsrSignInfo(stationSignInfo);
		List<Map<String, Object>> usrSignInfoByBizOrgCode = firefightersMapper.getUsrSignInfoByBizOrgCode(bizOrgCode);
		bigScreen1VO.setUsrSignInfoByCode(usrSignInfoByBizOrgCode);
		return bigScreen1VO;
	}

	@Override
	public Map<String,Object> getCompanyName(String bizOrgCode) {
		LambdaQueryWrapper<OrgUsr> lambda = new QueryWrapper<OrgUsr>().lambda();
		lambda.eq(OrgUsr::getBizOrgCode, bizOrgCode);
		lambda.eq(OrgUsr::getIsDelete, false);
		OrgUsr orgUsr = orgUsrMapper.selectList(lambda).get(0);
		if (!ObjectUtils.isEmpty(orgUsr.getBizOrgType()) && "COMPANY".equals(orgUsr.getBizOrgType())) {
			Map<String,Object> map = new HashMap<>();
			map.put("bizOrgCode",orgUsr.getBizOrgCode());
			map.put("bizOrgName",orgUsr.getBizOrgName());
			return map;
		} else {
			return getCompanyNameById(orgUsr.getParentId());
		}

	}

	private Map<String,Object> getCompanyNameById(String id) {
		LambdaQueryWrapper<OrgUsr> lambda = new QueryWrapper<OrgUsr>().lambda();
		lambda.eq(OrgUsr::getSequenceNbr, id);
		lambda.eq(OrgUsr::getIsDelete, false);
		OrgUsr orgUsr = orgUsrMapper.selectList(lambda).get(0);
		if (!ObjectUtils.isEmpty(orgUsr.getBizOrgType()) && "COMPANY".equals(orgUsr.getBizOrgType())) {
			Map<String,Object> map = new HashMap<>();
			map.put("bizOrgCode",orgUsr.getBizOrgCode());
			map.put("bizOrgName",orgUsr.getBizOrgName());
			return map;
		} else {
			return getCompanyNameById(orgUsr.getParentId());
		}

	}

	@Override
	public List<Map<String, Object>> getUserInfoByYJYA(String bizOrgCode) {
		return firefightersMapper.getUserInfoByYJYA(bizOrgCode);
	}

	@Override
	public IPage<Map<String, Object>> signPersonPageList(int current, int size, String bizOrgCode) {
		Page page = new Page();
		page.setCurrent(current);
		page.setSize(size);
		return firefightersMapper.selectSignPersonList(page, bizOrgCode);
	}
}
