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

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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.constants.BizConstant;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;
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 org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.itextpdf.text.log.SysoCounter;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.FireStationDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireStationzhDto;
import com.yeejoin.amos.boot.module.common.api.dto.RequestData;
import com.yeejoin.amos.boot.module.common.api.entity.FireStation;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.FireStationMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFireStationService;

/**
 * 微型消防站服务实现类
 *
 * @author system_generator
 * @date 2021-06-28
 */
@Service
public class FireStationServiceImpl extends BaseService<FireStationDto, FireStation, FireStationMapper>
        implements IFireStationService {


    @Autowired
    FireStationMapper fireStationMapper;
    @Autowired
    OrgUsrMapper orgUsrMapper;
    
    @Autowired
    OrgUsrServiceImpl orgUsrService;
    
    @Autowired
	EquipFeignClient equipFeignClient;
    
    
    /**
     * 分页查询
     */
    public Page<FireStationDto> queryForFireStationPage(Page<FireStationDto> page,String bizOrgCode) {
        return this.queryForPage(page, null, false,bizOrgCode);
    }

    /**
     * 列表查询 示例
     */
    public List<FireStationDto> queryForFireStationList(@Condition(Operator.eq) Boolean isDelete,@Condition(Operator.eq) Long bizCompanyId,@Condition(Operator.like) String name,@Condition(Operator.like) String bizOrgCode) {
    	if ("null".equals(bizOrgCode)) {
    		bizOrgCode = null;
		}
    	if ("null".equals(name)) {
    		name = null;
		}
    	return this.queryForList("", false, isDelete,bizCompanyId,name,bizOrgCode);
    }

    /**
     * 删除
     */
    public Boolean updateisDelete(Long sequenceNbr) {

        return this.update(new UpdateWrapper<FireStation>().eq("sequence_nbr", sequenceNbr).set("is_delete", 1));
    }

    @Override
    public Page<FireStationDto> getFirefighters(int pageNum, int pageSize, FireStationDto par) {
    	List<String> ids=null;
    	if(par.getWhereBuildingId()!=null && !"-1".equals(par.getWhereBuildingId())) {
    		ids= getNodeAllnodeIds(par.getWhereBuildingId());
    	}
        List<FireStationDto> list = fireStationMapper.getFireStation((pageNum - 1) * pageSize, pageSize, par,ids);
        Map<String, Long> num = fireStationMapper.getFireStationCount(par,ids);
        Page<FireStationDto> pageBean = new Page<>(pageNum, pageSize, num.get("num"));
        return pageBean.setRecords(list);
    }

    @Override
    public List<FireStationzhDto> getStationList(Integer pageNum, Integer pageSize, RequestData requestData) {
        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        }else{
            pageNum=(pageNum - 1) * pageSize;
        }
        return fireStationMapper.getStationList(pageNum,pageSize,requestData);
    }

    @Override
    public Integer getStationListCount(RequestData requestData) {
        return fireStationMapper.getStationListCount(requestData);
    }

    @Override
    public FireStationDto selectBySequenceNbr(Long id) {
        return fireStationMapper.getFireStationDetails(id);
    }


    /**
     * 新增
     ***/
    public FireStationDto add(FireStationDto model) {
        /*bug 3072 微型消防站，新增页面多次点击保存报主键重复错误 2021-10-13 chenzhao */
        if (model.getSequenceNbr() != null){
            Update(model);
        }
        /*bug 3072 微型消防站，新增页面多次点击保存报主键重复错误 2021-10-13 chenzhao */

        if (model.getBizCompanyId() != null) {
            OrgUsr orgUsr = orgUsrMapper.selectById(model.getBizCompanyId());
            model.setBizCompany(orgUsr.getBizOrgName());
            model.setBizCompanyCode(orgUsr.getBizOrgCode());

            // 地址处理
            if (model.getAddress() != null) {
                JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
                model.setAddress(address.getString(BizConstant.ADDRESS));
                if(!"0".equals(address.getString(BizConstant.LONGITUDE))) {
                    model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
                }
                if(!"0".equals(address.getString(BizConstant.LATITUDE))) {
                    model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
                }
            }
        }
        FireStation entity = this.prepareEntity(model);
        this.save(entity);
        return Bean.toModel(entity, model);
    }

    /**
     * 修改
     ***/
    public FireStationDto Update(FireStationDto model) {
        if (model.getBizCompanyId() != null) {
            OrgUsr orgUsr = orgUsrMapper.selectById(model.getBizCompanyId());
            model.setBizCompany(orgUsr.getBizOrgName());
            model.setBizCompanyCode(orgUsr.getBizOrgCode());
        }

        // 地址处理
        if (model.getAddress() != null) {
            JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
            model.setAddress(address.getString(BizConstant.ADDRESS));
            if(!"0".equals(address.getString(BizConstant.LONGITUDE))) {
                model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
            }
            if(!"0".equals(address.getString(BizConstant.LATITUDE))) {
                model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
            }
        }

        FireStation entity = this.prepareEntity(model);
        this.updateById(entity);
        return Bean.toModel(entity, model);
    }
    /**
     * 列表查询 示例
     */
    public List<FireStation> queryForFireStationList(List<String> companyIdList) {
    	LambdaQueryWrapper<FireStation> wrapper =new LambdaQueryWrapper<FireStation>();
    	wrapper.eq(FireStation::getIsDelete, false);
    	wrapper.in(FireStation::getBizCompanyId, companyIdList);
        return this.baseMapper.selectList(wrapper);
    }
    /**
     * 查询当前公司下的所有微型消防站信息
     * @param companyId
     * @return
     */
    public List<Map<String , Object>> queryForFireStationListByCompanyId(Long companyId) {
    	LambdaQueryWrapper<FireStation> wrapper =new LambdaQueryWrapper<FireStation>();
    	wrapper.eq(FireStation::getIsDelete, false);
    	wrapper.eq(FireStation::getBizCompanyId, companyId);
    	wrapper.select(FireStation::getSequenceNbr,FireStation::getName);
    	return  this.baseMapper.selectMaps(wrapper);
    }

    /**
     * 获取机场单位树
     * chenzhao 2021-10-14
     * @return
     */
    public List<MenuFrom> getCompanyTeamTree() throws Exception {
        MenuFrom root = new MenuFrom("-1", "微型消防站", null, null);

        List<OrgUsr> companyDeptList = orgUsrService.selectCompanyList();
        List<MenuFrom> companyDeptMenuList = Lists.newArrayList();
        companyDeptList.forEach(o -> {
            if (ValidationUtil.isEmpty(o.getParentId())) {
                o.setParentId("-1");
            }
            companyDeptMenuList.add(new MenuFrom(o.getSequenceNbr().toString(), o.getBizOrgName(), o.getParentId(),
                    "1"));
        });

        List<MenuFrom> menuList = TreeParser.getTreexin("-1", companyDeptMenuList, MenuFrom.class.getName(), "getKey",
                1, "getName", "getParentId", "getNodeType");
        root.setChildren(menuList);
        return Lists.newArrayList(root);
    }

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> fireStationCountAndBuildingTree(String bizOrgCode) {
		Map<String, Integer> FireStationCountMap = parseFireStationCount(bizOrgCode);
		ResponseModel<Object> response = equipFeignClient.getBuildingTree();
		List<Map<String, Object>> buildingMapList = (List<Map<String, Object>>) response.getResult();
		if(buildingMapList==null || buildingMapList.size()<1) {
			return null;
		}
		List<Map<String, Object>> childrens  = ((List<Map<String, Object>>) buildingMapList.get(0).get("children")).stream().filter(i-> i.containsKey("bizOrgCode") && i.get("bizOrgCode").toString().contains(bizOrgCode)).collect(Collectors.toList());
		return parseTree(childrens,FireStationCountMap);
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> parseTree(List<Map<String, Object>> children,
			Map<String, Integer> keySiteCountMap) {
		
		if (!ValidationUtil.isEmpty(children)) {
			for (Map<String, Object> child : children) {
				if (child.get("id") != null) {
					if (keySiteCountMap.containsKey(child.get("id").toString())) {
						child.put("count",keySiteCountMap.get(child.get("id").toString()));
					}else {
						child.put("count",0);
					}
				}else {
					child.put("count",0);
				}
				if (!ValidationUtil.isEmpty(child.get("children"))) {
				   parseTree((List<Map<String, Object>>) child.get("children"), keySiteCountMap);
				} 
			}
		}
		return children;
	}
	private Map<String, Integer> parseFireStationCount(String bizOrgCode) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		List<Map<String, Object>> list = fireStationMapper.getfireStatioCount(bizOrgCode);
		for (Map<String, Object> map2 : list) {
			Object parentBuilingIdString = map2.get("parent_building_id");
			if (ObjectUtils.isEmpty(parentBuilingIdString)) {
				continue;
			}
			String[] parentBuilingIdArray = parentBuilingIdString.toString().split(",");
			for (int i = 0; i < parentBuilingIdArray.length; i++) {
				if (map.containsKey(parentBuilingIdArray[i])) {
					int num = map.get(parentBuilingIdArray[i]).intValue();
					num = num + Integer.parseInt(map2.get("count").toString());
					map.put(parentBuilingIdArray[i], num);
				} else {
					map.put(parentBuilingIdArray[i], Integer.parseInt(map2.get("count").toString()));
				}
			}
		}
		return map;

	}

	public Map<String, String> getNodeAllParentIds(List<String> ids) {
		Map<String, String> map =new HashMap<String, String>();
		ResponseModel<List<Map<String, Object>>>  response=	equipFeignClient.getBuildingTreeList();
		List<Map<String, Object>>  responseList =response.getResult();
		if(response.getStatus()!=200 && response.getResult().size()<1) {
			return null;
		}
		ids.stream().forEach(i->{
			
			 String	tegartString = getNodeAllParentIds( responseList,i,i);
			 map.put(i, tegartString);
		});
		return map;
	}
	
	private String getNodeAllParentIds(List<Map<String, Object>> list , String id,String tegartString){
		for (Map<String, Object> map : list) {
		 if(map.get("id").toString().equals(id) && map.get("parentId")!=null ) {
			 tegartString=tegartString+","+map.get("parentId").toString();
			  getNodeAllParentIds(list,map.get("parentId").toString(),tegartString);
		 }
		}
		return tegartString;
	}
	public List<String> getNodeAllnodeIds(String id) {
		List<String> resultList = new ArrayList<String>();
		resultList.add(id);
		ResponseModel<List<Map<String, Object>>>  response=	equipFeignClient.getBuildingTreeList();
		List<Map<String, Object>>  responseList =response.getResult();
		if(response.getResult()==null && response.getResult().size()<1) {
			return null;
		}
		return getNodeAllnodeIds(resultList, responseList,id.toString());
	}
	
	private List<String> getNodeAllnodeIds(List<String> resultList,List<Map<String, Object>> list,String id){
		for (Map<String, Object> map : list) {
		 if(map.get("parentId").toString().equals(id) && map.get("parentId")!=null ) {
			 resultList.add(map.get("id").toString());
			  getNodeAllnodeIds(resultList,list,map.get("id").toString());
		 }
		}
		return resultList;
	}
}
