package com.ningdatech.carapi.datascope.provider.impl;

import com.ningdatech.carapi.datascope.contants.DataScopeEnum;
import com.ningdatech.carapi.datascope.model.DataScopeDto;
import com.ningdatech.carapi.datascope.provider.DataScopeProvider;
import com.ningdatech.carapi.sys.entity.dto.CompanyDTO;
import com.ningdatech.carapi.sys.helper.CompaniesCacheHelper;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.user.entity.NdUserInfo;
import com.ningdatech.carapi.user.service.INdUserInfoService;
import com.ningdatech.carapi.user.util.LoginUserUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 数据权限{@link DataScopeEnum#SELF_REGION}
 * </p>
 *
 * @author WendyYang
 * @since 2022/1/9 23:29
 */
@Slf4j
@RequiredArgsConstructor
@Component("DATA_SCOPE_2")
public class SelfRegionDataScopeProviderImpl implements DataScopeProvider {

    private final INdUserInfoService userInfoService;
    private final CompaniesCacheHelper companiesCacheHelper;

    private final RegionsCacheHelper regionsCacheHelper;

    @Override
    public Optional<DataScopeDto> findDataFieldProperty() {
        Long userId = LoginUserUtil.getUserId();
        NdUserInfo user = userInfoService.getById(userId);
        CompanyDTO company = companiesCacheHelper.getById(user.getCompanyId());
        Long regionId;
        regionId = company.getRegionId();
        List<Long> regionIds = Collections.singletonList(regionId);
        DataScopeDto ds = new DataScopeDto();
        ds.setRegionIds(regionIds);
        //最大的区域权限是 公司所在的区域 用于大屏地图
        ds.setMaxRegion(regionsCacheHelper.getByRegionId(company.getRegionId()));
        return Optional.ofNullable(ds);
    }

}
