package com.yuchen.saas.park.service.service.impl;

import com.yuchen.saas.park.api.entity.park.ParkBusinessDataEntity;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.enums.ParkDataTypeEnum;
import com.yuchen.saas.park.api.response.BusinessDataResponse;
import com.yuchen.saas.park.api.response.ParkBusinessDataTreeResponse;
import com.yuchen.saas.park.service.mapper.ParkBusinessDataMapper;
import com.yuchen.saas.park.service.service.ParkBusinessDataService;
import com.yuchen.saas.park.service.service.PmgBatDeviceCategoryService;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName ParkBusinessDataServiceImpl
 * @Description 园区业务数据
 * @Author 肖祥
 * @Date 2022/11/02 14:52
 * @Version 1.0。0
 **/
@Service
public class ParkBusinessDataServiceImpl extends BaseServiceImpl<ParkBusinessDataMapper, ParkBusinessDataEntity>
        implements ParkBusinessDataService {

    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;

    @Resource
    private PmgBatDeviceCategoryService pmgBatDeviceCategoryService;

    @Override
    public R<List<ParkBusinessDataTreeResponse>> getParkingBusinessDataTree(List<Long> parkIdList, Long roleId) {
        if(CollectionUtil.isEmpty(parkIdList)){
            return R.data(null);
        }
        ContextUser user = AuthUtil.getUser();
        List<ParkBusinessDataTreeResponse> responseList = new ArrayList<>();
        List<ParkBusinessDataEntity> pmgBatParkCategoryList = this.lambdaQuery()
                .eq(ParkBusinessDataEntity::getTenantId,user.getTenantId())
                .in(ParkBusinessDataEntity::getParkId,parkIdList)
                .list();
        if(CollectionUtil.isEmpty(pmgBatParkCategoryList)){
            return R.data(Collections.EMPTY_LIST);
        }

        List<ParkBusinessDataTreeResponse> pmgBatDeviceTreeResponseList = pmgBatParkCategoryList.stream()
                .map(businessDataEntity ->{
                            ParkBusinessDataTreeResponse pmgBatDeviceTreeResponse = new ParkBusinessDataTreeResponse();
                            BeanUtils.copyProperties(businessDataEntity,pmgBatDeviceTreeResponse);
                            return pmgBatDeviceTreeResponse;
                        }
                )
                .collect(Collectors.toList());

        List<ParkBusinessDataTreeResponse> treeResponseList =  buildTree(pmgBatDeviceTreeResponseList,roleId);
        responseList.addAll(treeResponseList);
        return R.data(responseList);
    }

    @Override
    public R<List<BusinessDataResponse>> getBusinessDataTable(List<Long> parkIdList) {
        if(CollectionUtil.isEmpty(parkIdList)){
            return R.data(null);
        }
        ContextUser user = AuthUtil.getUser();
        List<BusinessDataResponse> list = new ArrayList<>();
        Map<Integer,List<BusinessDataResponse>> map = new TreeMap<>();
        //返回最全的tab数据
        for(Long parkId : parkIdList){
            if(Objects.isNull(parkId)){
                PmgBatParkInfo pmgBatParkInfo =   pmgBatParkInfoService.lambdaQuery().select(PmgBatParkInfo::getId).one();
                parkId =   pmgBatParkInfo.getId();
            }
            List<ParkBusinessDataEntity> parkBusinessDataEntityList = this.lambdaQuery().eq(ParkBusinessDataEntity::getTenantId,user.getTenantId())
                    .eq(ParkBusinessDataEntity::getParkId,parkId).list();
            list = parkBusinessDataEntityList.stream()
                    .filter(businessDataEntity -> Objects.nonNull(businessDataEntity.getType()))
                    .map(businessDataEntity ->{
                        BusinessDataResponse response = new BusinessDataResponse();
                        response.setName(businessDataEntity.getName());
                        response.setType(businessDataEntity.getType());
                        return response;
                    } ).collect(Collectors.toList());
            map.put(list.size(),list);
        }

        return R.data((List<BusinessDataResponse>)map.values().toArray()[map.size()-1]);
    }


    /**
     * 建立树形结构
     */
    public List<ParkBusinessDataTreeResponse> buildTree(List<ParkBusinessDataTreeResponse> categoryList,Long roleId){
        List<ParkBusinessDataTreeResponse> treeMenus =new ArrayList<ParkBusinessDataTreeResponse>();
        for(ParkBusinessDataTreeResponse categoryNode : getRootNode(categoryList)) {
            categoryNode = buildChildTree(categoryNode,categoryList,roleId);
            treeMenus.add(categoryNode);
        }
        return treeMenus;
    }

    /**
     * 获取根节点(获取所有的父节点)
     */
    public List<ParkBusinessDataTreeResponse> getRootNode(List<ParkBusinessDataTreeResponse> categoryList) {
        List<ParkBusinessDataTreeResponse> rootCategoryLists =new  ArrayList<ParkBusinessDataTreeResponse>();
        for(ParkBusinessDataTreeResponse category : categoryList) {
            if(Objects.equals(category.getParentId(),0L)) {
                rootCategoryLists.add(category);
            }
        }
        return rootCategoryLists;
    }

    /**
     * 递归，建立子树形结构
     */
    public ParkBusinessDataTreeResponse buildChildTree(ParkBusinessDataTreeResponse response,
                                                   List<ParkBusinessDataTreeResponse> treeResponseList,
                                                   Long roleId){
        Map<String,String> dataMap = pmgBatDeviceCategoryService.getParkBusinessDataByRoleId(response.getParkId(),roleId,response.getType());
        List<Object> childCategoryList =new  ArrayList<Object>();
        for(ParkBusinessDataTreeResponse category : treeResponseList) {
            if(Objects.equals(category.getType(), ParkDataTypeEnum.DEVICE_DATA.getType())){
                String deviceKey = String.format("%d%d%d",category.getParkId(),roleId,category.getType());
                category.setDeviceStatics(dataMap.get(deviceKey));
            }
            if(Objects.equals(category.getParentId(),response.getId())) {
                childCategoryList.add(buildChildTree(category,treeResponseList,roleId));
            }
        }
        response.setChildrenVoList(childCategoryList);
        return response;
    }

}
