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

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.yeejoin.amos.boot.module.common.api.dto.LinkageUnitDto;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.service.ILinkageUnitService;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.module.common.api.dto.FireTeamCardDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireTeamListDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersZhDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.ExcelSelectData;
import com.yeejoin.amos.boot.module.common.api.excel.DataSources;
import com.yeejoin.amos.boot.module.common.api.service.IKeySiteService;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;

@Service
public class DataSourcesImpl implements DataSources {

	@Resource
	DataDictionaryMapper dataDictionaryMapper;
	@Autowired
	EquipmentServiceImpl equipmentService;
	@Autowired
	OrgUsrServiceImpl orgUsrService;
	@Autowired
	FirefightersServiceImpl firefightersService;
	@Autowired
	FireTeamServiceImpl fireTeamService;
	@Autowired
	EquipFeignClient equipFeignClient;

	@Autowired
	IMaintenanceCompanyService maintenanceCompanyService;

	@Autowired
	IKeySiteService keySiteService;
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	ILinkageUnitService linkageUnitServiceImpl;


	@Autowired
	OrgUsrServiceImpl iOrgUsrService;

	@Value("${security.systemctl.name}")
	private String systemctl;

	@Override
	public String[] selectList(String type, String method) throws Exception {
		String[] str = {};
		if (StringUtils.isNotEmpty(type)) {
			str = getDataDictionary(type);
		} else {
			switch (method) {
			case "getNations":
				str = ExcelSelectData.NATION;
				break;
			case "getPoliticalOutlook":
				str = ExcelSelectData.POLITICAL_OUTLOOK;
				break;
			case "getAdministrativeDivisions":
				// 设置请求头
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.valueOf("application/json; charset=utf-8"));
				// 用HttpEntity封装整个请求报文
				HttpEntity<Object> httpEntity = new HttpEntity<>(null, headers);
				ResponseEntity<String> responseEntity = restTemplate.exchange(
						"http://" + systemctl + "/systemctl" + "/v1" + "/region/tree/parent", HttpMethod.GET,
						httpEntity, String.class);
				String body = responseEntity.getBody();
				break;
			case "getBuildingList":
				str = getBuildingList();
				break;
			case "getFireSystemList":
				str = getFireSystemList();
				break;
			case "getCompanyList":
				str = getCompanyList();
				break;
			case "getFirefighters":
				str = getFirefighters();
				break;
			case "getBizCompanyList":
				str = getBizCompanyList();
				break;
			case "getFireTeam":
				str = getFireTeam();
				break;
			case "getMaritalStatus":
				str = ExcelSelectData.MARITAL_STATUS;
				break;
			case "getCarList":
				str = getCarList();
				break;
			case "getCompanyAndDeparementTree":
				str = getCompanyAndDeparementTree();
				break;
			case "getBuildTree":
				str = getBuildTree();
				break;
			case "getCompanyDetailTree":
				str =getCompanyDetailTree();
				break;
			case "getparent":
				str =getparent();
				break;
			case "getUnitTeam":
				str =getUnitTeam();
				break;
			case "getCompany":
				str =getCompany();
				break;
			case "getCitys":
				str =getCitys();
				break;
			case "getDutyArea":
				str =getDutyArea();
				break;
			case "getEquipCategory":
				str =getEquipCategory();
				break;
			case "getEquipDefinition":
				str =getEquipDefinition();
				break;
			}
		}
		return str;
	}

	private String[] getCarList() {
		ResponseModel<Object> response = equipFeignClient.getFireCarListAll();
		List<Map<String, Object>> carList = (List<Map<String, Object>>) response.getResult();
		List<String> carNameList = Lists.newArrayList();
		carList.forEach(car -> {
			carNameList.add(car.get("name") + "(" + car.get("carNum") + ")" + "@" + car.get("id"));
		});
		String[] str = carNameList.toArray(new String[carNameList.size()]);
		return str;
	}

	private String[] getFireTeam() {
		Page<FireTeamCardDto> pageBean = new Page<>(1, Integer.MAX_VALUE);
		IPage<FireTeamCardDto> fireTeamCardDtoIPage = fireTeamService.listFireTeamByPage(pageBean,
				new FireTeamListDto());
		List<FireTeamCardDto> records = fireTeamCardDtoIPage.getRecords();
		List<String> names = records.stream().map(item -> {
			return item.getName() + "@" + item.getSequenceNbr();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	private String[] getBizCompanyList() throws Exception {
		List<OrgMenuDto> orgUsrTree = orgUsrService.getTree(null, orgUsrService.selectCompanyDepartmentMsg(),
				OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId", "getBizOrgType");
		List<String> stringList = new ArrayList<String>();
		initBizCompanyList(orgUsrTree, stringList);
		String[] str = stringList.toArray(new String[stringList.size()]);
		return str;
	}

	private void initBizCompanyList(List<OrgMenuDto> orgUsrTree, List<String> stringList) {
		for (OrgMenuDto orgMenuDto : orgUsrTree) {
			stringList.add(orgMenuDto.getName() + "@" + orgMenuDto.getKey() + "@" + orgMenuDto.getBizOrgCode());
			List<OrgMenuDto> children = orgMenuDto.getChildren();
			if (children != null && children.size() > 0) {
				initCompanyList(children, stringList);
			}
		}
	}

	private String[] getFirefighters() {
		List<FirefightersZhDto> firefighters = firefightersService.getFirefighters(1, Integer.MAX_VALUE,
				new FirefightersDto());
		List<String> names = firefighters.stream().map(item -> {
			return item.getName() + "@" + item.getSequenceNbr();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	private String[] getCompanyList() throws Exception {
		List<OrgMenuDto> orgUsrTree = orgUsrService.getTree(null, orgUsrService.selectCompanyDepartmentMsg(),
				OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId", "getBizOrgType");
		List<String> stringList = new ArrayList<String>();
		initCompanyList(orgUsrTree, stringList);
		String[] str = stringList.toArray(new String[stringList.size()]);
		return str;
	}

	private void initCompanyList(List<OrgMenuDto> orgUsrTree, List<String> stringList) {
		for (OrgMenuDto orgMenuDto : orgUsrTree) {
			stringList.add(orgMenuDto.getName() + "@" + orgMenuDto.getKey());
			List<OrgMenuDto> children = orgMenuDto.getChildren();
			if (children != null && children.size() > 0) {
				initCompanyList(children, stringList);
			}
		}
	}

	private String[] getFireSystemList() {
		List<MenuFrom> fireSystemList = equipmentService.getFireSystemList();
		List<String> names = fireSystemList.stream().map(item -> {
			return item.getName() + "@" + item.getKey();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	private String[] getBuildingList() {
		List<MenuFrom> buildingList = equipmentService.getBuildingList();
		List<String> buildingNames = buildingList.stream().map(item -> {
			return item.getName() + "@" + item.getKey();
		}).collect(Collectors.toList());
		String[] str = buildingNames.toArray(new String[buildingNames.size()]);
		return str;
	}

	private String[] getDataDictionary(String type) {
		QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", type);
		queryWrapper.orderByAsc("sort_num");
		List<DataDictionary> list = dataDictionaryMapper.selectList(queryWrapper);
		List<String> names = list.stream().map(dataDictionary -> {
			return dataDictionary.getName() + "@" + dataDictionary.getCode();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	private String[] getCompanyAndDeparementTree() throws Exception {
		List<OrgMenuDto> menus = orgUsrService.getTree(null, maintenanceCompanyService.getCompanyAndDepartmentTree(),
				MaintenanceCompany.class.getName(), "getSequenceNbr", 2, "getName", "getParentId", "getType");
		List<String> stringList = new ArrayList<String>();
		initCompanyList(menus, stringList);
		String[] str = stringList.toArray(new String[stringList.size()]);
		return str;

	}

	private String[] getBuildTree() throws Exception {
		List<Object> menus = keySiteService.getBuildTree();
		List<String> stringList = new ArrayList<String>();
		initBuildTreeList(menus, stringList);
		String[] str = stringList.toArray(new String[stringList.size()]);
		return str;

	}

	private void initBuildTreeList(List<Object> menus, List<String> stringList) {
		for (Object orgMenuDto : menus) {
			JSONObject detailObject = JSONObject.parseObject(orgMenuDto.toString());
			if (detailObject.containsKey("id")) {
				stringList.add(detailObject.getString("name") + "@" + detailObject.getString("id")); // 任务3527 重点部位导出模板 id name 未正常配置 by kongfm
			}
			JSONArray children = detailObject.getJSONArray("children");
			if (children != null && children.size() > 0) {
				initBuildTreeList(children, stringList);
			}
		}
	}
	
	 private String[] getCompanyDetailTree() throws Exception {
	        List<OrgMenuDto> orgUsrTree = orgUsrService.getTree(null, orgUsrService.getCompanyDetailTree(),
	                OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId", "getBizOrgType");
	        List<String> stringList = new ArrayList<String>();
	        initCompanyList(orgUsrTree, stringList);
	        String[] str = stringList.toArray(new String[stringList.size()]);
	        return str;
	    }


	private String[] getparent() throws Exception {
		String[] str=null;
		List<Map<String ,Object>> orgUsrTree = orgUsrService.getparent();
         if(orgUsrTree!=null&&orgUsrTree.size()>0){
			 List<String> buildingNames = orgUsrTree.stream().map(item -> {
				 return item.get("name") + "@" + item.get("id");
			 }).collect(Collectors.toList());

			 str = buildingNames.toArray(new String[buildingNames.size()]);
		 }

		return str;
	}

	/**
	 * 特岗人员模板及救援车辆模板获取联动单位   BUG 2455 相关代码 bykongfm
	 * @return
	 */
	private String[] getUnitTeam() {
		List<LinkageUnitDto> units = linkageUnitServiceImpl.queryForLinkageUnitList(false);
		List<String> names = units.stream().map(item -> {
			return item.getUnitName() + "@" + item.getSequenceNbr();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	/**
	 * 消防队员模板获取所属部门
	 * @return
	 */
	private String[] getCompany() {
		List<OrgMenuDto> menus = OrgUsrServiceImpl.buildTreeParallel(iOrgUsrService.selectCompanyDepartmentMsg());
		List<String> names = menus.stream().map(item -> {
			return item.getName() + "@" + item.getKey();
		}).collect(Collectors.toList());
		String[] str = names.toArray(new String[names.size()]);
		return str;
	}

	/**
	 * 消防队员模板获取地址
	 * @return
	 */
	private String[] getCitys() {
		FeignClientResult<java.util.Collection<RegionModel>> region =  Systemctl.regionClient.queryForTreeParent(null);
		java.util.Collection<RegionModel> regions = region.getResult();// 以及地址
		List<String> address = new ArrayList<>();
		setAddress("",address,regions);
		String[] str = address.toArray(new String[address.size()]);
		return str;
	}

	private void setAddress(String  name,List<String> address, Collection<RegionModel> regions) {

		for (RegionModel item : regions) {
			//添加自己的

			address.add(name+" "+item.getRegionName() + "@" + item.getSequenceNbr());
			if(item.getChildren() != null && item.getChildren().size() > 0) {
				setAddress(name+" "+item.getRegionName()  ,address,item.getChildren());
			}
		}

//		regions.stream().forEach(item -> {
//			//添加自己的
//			name =name+item.getRegionName();
//			address.add(name + "@" + item.getSequenceNbr());
//			if(item.getChildren() != null && item.getChildren().size() > 0) {
//				setAddress(name ,address,item.getChildren());
//			}
//		});
	}

	private String[] getDutyArea() {
		ResponseModel<List<LinkedHashMap<String, Object>>> response = equipFeignClient.getAllBuilding();
		List<LinkedHashMap<String, Object>> buildingList = response.getResult();
		List<String> areaList = Lists.newArrayList();
		buildingList.forEach(building -> {
			areaList.add(building.get("buildName") + "@" + building.get("instanceId"));
		});
		String[] str = areaList.toArray(new String[buildingList.size()]);
		return str;
	}

	/**
	 * 获取设施分类// BUG 2935 优化项 分类从93060000 取得字典数据 by kongfm 2021-09-17
	 * @return
	 */
	private String[] getEquipCategory() {
		String type = "1";
		ResponseModel<List<LinkedHashMap<String, Object>>> response = equipFeignClient.getEquipmentCategory(type);
		// 筛选第一层
		String categoryCode = "90000000";
		List<LinkedHashMap<String, Object>> categoryList = response.getResult();
		// 筛选第二层
		String fireCode = "93000000";
		List<LinkedHashMap<String, Object>> fireList = Lists.newArrayList();
		// 筛选第三层
		String waterCode = "93060000";
		List<LinkedHashMap<String, Object>> waterList = Lists.newArrayList();
		List<LinkedHashMap<String, Object>> category = Lists.newArrayList();
		List<String> resultList = Lists.newArrayList();
		for(LinkedHashMap<String, Object> t :categoryList) {
			if(categoryCode.equals(t.get("code").toString())){
				fireList = (List<LinkedHashMap<String, Object>>) t.get("children");
			}
		}
		// 筛选第二层
		for(LinkedHashMap<String, Object> t : fireList) {
			if(fireCode.equals(t.get("code").toString())){
				waterList = (List<LinkedHashMap<String, Object>>) t.get("children");
			}
		}
		// 筛选第三层
		for(LinkedHashMap<String, Object> t : waterList) {
			if(waterCode.equals(t.get("code").toString())){
				category = (List<LinkedHashMap<String, Object>>) t.get("children");
			}
		}
		category.forEach(t -> {
			resultList.add(t.get("name") + "@" + t.get("id"));
		});
		String[] str = resultList.toArray(new String[category.size()]);
		return str;
	}


	private String[] getEquipDefinition() {
		String type = "9306";
		ResponseModel<List<LinkedHashMap<String, Object>>> response = equipFeignClient.listLikePage(type);
		List<LinkedHashMap<String, Object>> categoryList = response.getResult();
		String[] str = null;

		List<String> resultList = Lists.newArrayList();

		if(categoryList!=null&&categoryList.size()>0){
			categoryList.forEach(t -> {
				resultList.add(t.get("name") + "@" + t.get("id")+ "@" +t.get("categoryId")+ "@" +t.get("unitName"));
			});

			str = resultList.toArray(new String[resultList.size()]);
		}
		return str;
	}


}
