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

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
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.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.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContacts;
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;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

/**
 * 消防队员 服务实现类
 *
 * @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;

	@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);
	}

	@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) {
		return firefightersMapper.selectNormalFirePerson(jobId);
	}



	@Override
    @Transactional(rollbackFor = Exception.class)
	public PeopleInfoDto updatePeopleById(PeopleInfoDto peopleInfoDto, Long id) {
		// 1.动态表单
		AgencyUserModel amosUser = Privilege.agencyUserClient.queryByUserId(peopleInfoDto.getFirefighters().getAmosUserId()).getResult();
		peopleInfoDto.getFirefighters().setAmosName(amosUser.getRealName());
		OrgUsr orgUsr = orgUsrService.peopleSaveOrgUsr(peopleInfoDto.getFirefighters());
		OrgPersonDto orgPersonDto = new OrgPersonDto();
		BeanUtils.copyProperties(orgUsr, orgPersonDto);
		List<DynamicFormInstance> dynamicFormInstances = orgUsrService.dynamicFormColumn(peopleInfoDto.getFirefighters());
		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());
		}
		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;
	}
}
