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

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.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.LinkageUnitDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
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.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.excel.DataSources;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.service.IKeySiteService;
import com.yeejoin.amos.boot.module.common.api.service.ILinkageUnitService;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import net.sf.cglib.beans.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@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
    private RedisUtils redisUtils;


    @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 "getWaterBuildingList":
                    str = getWaterBuildingList();
                    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;
                case "getEquipCompany":
                    str = getEquipCompany();
                    break;
                case "getWaterCompanyList":
                    str = getWaterCompanyList();
                    break;
                case "getEquipFireTeam":
                    str =  getEquipFireTeam();
                    break;
                case "getContactUser":
                    str = getContactUser();
                    break;
                case "getKeySiteCompanyDetailTree":
                    str = getKeySiteCompanyDetailTree();
                    break;
                case "getFireTeamContactUser":
                    str = getFireTeamContactUser();
                    break;
                case "getFireStationContactUser":
                    str = getFireStationContactUser();
                    break;
                case "getFireTeamList":
                    str =  getFireTeamList();
                    break;
                case "getListByEquipmentCode":
                    str =  getListByEquipmentCode();
                    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[] getContactUser() {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_water_info");

        Map<String, Object> map = new HashMap<>();
        map.put("OrgCode",reginParams.getPersonIdentity().getBizOrgCode());
        IPage<Map<String, Object>> mapIPage = iOrgUsrService.pagePerson(null, null, map);
        List<Map<String, Object>> records = mapIPage.getRecords();
        List<String> carNameList = Lists.newArrayList();
        records.forEach(result -> {
            carNameList.add(result.get("bizOrgName") + "@" + result.get("sequenceNbr"));
        });
        String[] str = carNameList.toArray(new String[carNameList.size()]);
        return str;
    }

    private String[] getFireStationContactUser() {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_station_info");

        Map<String, Object> map = new HashMap<>();
        map.put("OrgCode",reginParams.getPersonIdentity().getBizOrgCode());
        IPage<Map<String, Object>> mapIPage = iOrgUsrService.pagePerson(null, null, map);
        List<Map<String, Object>> records = mapIPage.getRecords();
        List<String> carNameList = Lists.newArrayList();
        records.forEach(result -> {
            carNameList.add(result.get("bizOrgName") + "@" + result.get("sequenceNbr"));
        });
        String[] str = carNameList.toArray(new String[carNameList.size()]);
        return str;
    }

    private String[] getFireTeamContactUser() {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_team_info");

        Map<String, Object> map = new HashMap<>();
        map.put("OrgCode",reginParams.getPersonIdentity().getBizOrgCode());
        IPage<Map<String, Object>> mapIPage = iOrgUsrService.pagePerson(null, null, map);
        List<Map<String, Object>> records = mapIPage.getRecords();
        List<String> carNameList = Lists.newArrayList();
        records.forEach(result -> {
            carNameList.add(result.get("bizOrgName") + "@" + result.get("sequenceNbr"));
        });
        String[] str = carNameList.toArray(new String[carNameList.size()]);
        return str;
    }


    private String[] getFireTeam() {
//			Page<FireTeamCardDto> pageBean = new Page<>(0, Integer.MAX_VALUE);
//		IPage<FireTeamCardDto> fireTeamCardDtoIPage = fireTeamService.listFireTeamByPage(pageBean,
//				new FireTeamListDto());
//		List<FireTeamCardDto> records = fireTeamCardDtoIPage.getRecords();
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_water_info");
        List<FireTeam> records = fireTeamService.getExcelFireTeamList(reginParams.getPersonIdentity().getBizOrgCode());
        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[] getFireTeamList() {
//			Page<FireTeamCardDto> pageBean = new Page<>(0, Integer.MAX_VALUE);
//		IPage<FireTeamCardDto> fireTeamCardDtoIPage = fireTeamService.listFireTeamByPage(pageBean,
//				new FireTeamListDto());
//		List<FireTeamCardDto> records = fireTeamCardDtoIPage.getRecords();
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_team_info");
        List<FireTeam> records = fireTeamService.getExcelFireTeamList(reginParams.getPersonIdentity().getBizOrgCode());
        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[] getEquipFireTeam() {
//			Page<FireTeamCardDto> pageBean = new Page<>(0, Integer.MAX_VALUE);
//		IPage<FireTeamCardDto> fireTeamCardDtoIPage = fireTeamService.listFireTeamByPage(pageBean,
//				new FireTeamListDto());
//		List<FireTeamCardDto> records = fireTeamCardDtoIPage.getRecords();
        ResponseModel<ReginParams> result = equipFeignClient.getPermissions();
        ReginParams reginParams = result.getResult();

        List<FireTeam> records = fireTeamService.getExcelFireTeamList(reginParams.getPersonIdentity().getBizOrgCode());
        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 {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_station_info");

        List<OrgMenuDto> orgUsrTree = iOrgUsrService.companyTreeByUserAndType(reginParams, OrgPersonEnum.公司.getKey(), null);
        //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() {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_fighters_info");
        FirefightersDto firefightersDto = new FirefightersDto();
        firefightersDto.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
        List<FirefightersZhDto> firefighters = firefightersService.getFirefighters(1, Integer.MAX_VALUE,
                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 String[] getWaterCompanyList() throws Exception {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_water_info");
        List<OrgMenuDto> orgUsrTree = iOrgUsrService.companyTreeByUserAndType(reginParams, OrgPersonEnum.公司.getKey(), null);
        //       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() {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
        ResponseModel<Object> response = equipFeignClient.getBuildingTree();
        List<Map<String, Object>> buildingMapList = (List<Map<String, Object>>) response.getResult();
        List<Map<String, Object>> children = (List<Map<String, Object>>) buildingMapList.get(0).get("children");
        List<String> collect = children.stream().filter(result -> result.get("bizOrgCode").toString().startsWith(bizOrgCode)).map(itme -> {
            return itme.get("name") + "@" + itme.get("id");
        }).collect(Collectors.toList());
        String[] str = collect.toArray(new String[collect.size()]);
        return str;
    }


    private String[] getWaterBuildingList() {

        ResponseModel<Object> response = equipFeignClient.getBuildingTree();
        List<Map<String, Object>> buildingMapList = (List<Map<String, Object>>) response.getResult();
        List<Map<String, Object>> children = (List<Map<String, Object>>) buildingMapList.get(0).get("children");
        List<String> collect = children.stream().map(itme -> {
            return itme.get("name") + "@" + itme.get("id");
        }).collect(Collectors.toList());
        String[] str = collect.toArray(new String[collect.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 {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
        List<Object> menus = keySiteService.getBuildTree();
        List<String> stringList = new ArrayList<String>();
        initBuildTreeList(menus, stringList,bizOrgCode);
        String[] str = stringList.toArray(new String[stringList.size()]);
        return str;

    }

    private void initBuildTreeList(List<Object> menus, List<String> stringList,String bizOrgCode) {
        for (Object orgMenuDto : menus) {
            JSONObject detailObject = JSONObject.parseObject(orgMenuDto.toString());
            if (detailObject.containsKey("id") && detailObject.get("bizOrgCode") != null && detailObject.get("bizOrgCode").toString().startsWith(bizOrgCode)) {
                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,bizOrgCode);
            }
        }
    }

    private String[] getCompanyDetailTree() throws Exception {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_team_info");
        List<OrgMenuDto> orgUsrTree = iOrgUsrService.companyTreeByUserAndType(reginParams, OrgPersonEnum.公司.getKey(), null);

//        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[] getKeySiteCompanyDetailTree() throws Exception {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("key_site_info");
        // 修改bug6829 查询单位和部门数据
        List<OrgMenuDto> orgUsrTree = iOrgUsrService.companyTreeByUserAndType(reginParams, null, null);

//        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 {

        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("org_user_info");
        List<OrgUsr> orgMenuDtoList = iOrgUsrService.companyTreeByUserAndTypeNoTree(reginParams, null);
        List<Map<String, Object>> orgUsrTree  = new ArrayList<>();
        for (OrgUsr org: orgMenuDtoList
             ) {
            Map<String, Object> map = Maps.newHashMap();
            BeanMap beanMap = BeanMap.create(org);
            map.put("name",beanMap.get("bizOrgName"));
            map.put("id",beanMap.get("sequenceNbr"));
            orgUsrTree.add(map);
        }

        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());
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_fighters_info");

        List<OrgUsr> menus = iOrgUsrService.companyTreeByUserAndTypeNoTree(reginParams, null);
        List<String> names = menus.stream().map(item -> {
            return item.getBizOrgName() + "@" + item.getSequenceNbr() + "@" + item.getBizOrgCode();
        }).collect(Collectors.toList());
        String[] str = names.toArray(new String[names.size()]);
        return str;
    }

    /**
     * 消防装备模板获取所属部门
     *
     * @return
     */
    private String[] getEquipCompany() {

      //  List<OrgUsr> menus = iOrgUsrService.selectCompanyDepartmentMsg();
        ResponseModel<ReginParams> result = equipFeignClient.getPermissions();
        ReginParams reginParams = result.getResult();


        List<OrgUsr> menus = iOrgUsrService.equipCompanyExport(reginParams, null);
        List<String> names = menus.stream().map(item -> {
            return item.getBizOrgName() + "@" + item.getSequenceNbr() + "@" + item.getBizOrgCode();
        }).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;
    }

    private String[] getListByEquipmentCode() {
        String code = "92010700,92011500";
        //ResponseModel<List<Map<String, Object>>> response = equipFeignClient.getListByEquipmentCode(code);
        ResponseModel<List<Map<String, Object>>> response = equipFeignClient.getListByEquipmentCodeEQ(code);

        List<Map<String, Object>> equipmentList = response.getResult();
        String[] str = null;
        List<String> resultList = Lists.newArrayList();
        if (equipmentList != null && equipmentList.size() > 0) {
            equipmentList.forEach(t -> {
                resultList.add(t.get("name") + "@" + t.get("id"));
            });
            str = resultList.toArray(new String[resultList.size()]);
        }
        return str;
    }

}
