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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.WaterResourceTypeDto;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.MaintenanceCompanyMapper;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.WaterResourceServiceImpl;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@Service
public class EquipmentServiceImpl {

    @Autowired
    EquipFeignClient equipFeignClient;

    @Autowired
    WaterResourceServiceImpl waterResourceServiceImpl;

    @Autowired
    private MaintenanceCompanyMapper maintenanceCompanyMapper;

    @Autowired
    private RedisUtils redisUtils;

    public List<MenuFrom> getFireSystemList() {
        // 导出模板增加权限
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule("fire_water_info");
        ResponseModel<Object> response = equipFeignClient.getFireSystemListAll();
        List<Map<String, Object>> fireSystemMapList = (List<Map<String, Object>>) response.getResult();
        List<MenuFrom> fireSystemDtoList = Lists.newArrayList();
        fireSystemMapList.stream().forEach(
                system -> {
            MenuFrom menuFrom = new MenuFrom((String) system.get("id"), (String) system.get("name"), "0", "0");
            fireSystemDtoList.add(menuFrom);
        });
        return fireSystemDtoList;
    }

    public List<MenuFrom> getBuildingList() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ResponseModel<Object> response = equipFeignClient.getBuildingTree();
        stopWatch.stop();
        System.out.printf("耗时%f秒/n", stopWatch.getTotalTimeSeconds());
        List<Map<String, Object>> buildingMapList = (List<Map<String, Object>>) response.getResult();
        List<MenuFrom> buildingTreeList = Lists.newArrayList();
        buildingMapList.forEach(building -> {

            MenuFrom menuFrom = new MenuFrom((String) building.get("id"), "全部建筑", (String) building.get("parentId"),
                    "0");
            List<Map<String, Object>> children = (List<Map<String, Object>>) building.get("children");
            menuFrom.setChildren(parseTree(menuFrom, children));
            menuFrom.setIsLeaf(false);
            buildingTreeList.add(menuFrom);
        });
        return buildingTreeList.get(0).getChildren();
    }

    private List<MenuFrom> parseTree(MenuFrom parent, List<Map<String, Object>> children) {
        List<MenuFrom> menuFromList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(children)) {
            children.forEach(child -> {
                MenuFrom menuFrom = new MenuFrom((String) child.get("id"), (String) child.get("name"),
                        (String) child.get("parentId"), "0");
                if (!ValidationUtil.isEmpty(child.get("children"))) {
                    parseTree(menuFrom, (List<Map<String, Object>>) child.get("children"));
                    if(parent!=null){
                        parent.setIsLeaf(false);
                    }

                } else {
                    parent.setIsLeaf(false);
                }
                menuFromList.add(menuFrom);
                parent.setChildren(menuFromList);
            });
        }
        return menuFromList;
    }

    public List<MenuFrom> getFireSystemWaterResourceList() {
        // 获取消防系统列表
        List<MenuFrom> fireSystemDtoList = getFireSystemList();
        //  其他系统
        MenuFrom fireSystem = new MenuFrom("-1", "其他系统", "0", "0");
        fireSystemDtoList.add(fireSystem);
        // 获取消防水源类型列表，包含消防系统和消防水源类型，去重
        List<WaterResourceTypeDto> waterResourceTypeList = waterResourceServiceImpl.getWaterResourceTypeList(true);

        // 组装消防水资源树
        fireSystemDtoList.forEach(item -> {
            List<MenuFrom> children = Lists.newArrayList();
            waterResourceTypeList.forEach(r -> {
                if (r.getBelongFightingSystemId() != null && item.getKey().equals(r.getBelongFightingSystemId().toString())) {
                    MenuFrom menuFrom = new MenuFrom(r.getResourceType(), r.getResourceTypeName(), item.getKey(), "0");
                    children.add(menuFrom);
                }
            });
            item.setChildren(children);
        });
        List<MenuFrom> children = Lists.newArrayList();
        waterResourceTypeList.forEach(r -> {
            if (r.getBelongFightingSystemId() == null) {
                MenuFrom menuFrom = new MenuFrom(r.getResourceType(), r.getResourceTypeName(), "-1", "0");
                children.add(menuFrom);
            }
        });
        fireSystem.setChildren(children);
        return fireSystemDtoList;
    }
    public Long getMaintenanceId(String userId){
        List<MaintenanceCompany> maintenanceCompanies = maintenanceCompanyMapper.selectList(new QueryWrapper<MaintenanceCompany>()
                .lambda().eq(MaintenanceCompany::getAmosId, userId).eq(MaintenanceCompany::getIsDelete, 0));
        if (!CollectionUtils.isEmpty(maintenanceCompanies)){
            return maintenanceCompanies.get(0).getParentId();
        }else {
            return null;
        }
    }

    public List<Map<String, Object>> getWaterResourceInfoList(String bizOrgCode){
        return waterResourceServiceImpl.getWaterResourceInfoList(bizOrgCode);
    }

    public Map<String, Object> getResourcesCount() {
        return waterResourceServiceImpl.getResourcesCount();
    }
}
