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

import java.util.ArrayList;
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.feign.EquipFeignClient;
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;

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



			}
		}
		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("id") + "@" + detailObject.getString("name"));
			}
			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;
	}
}
