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

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.ningdatech.pmapi.common.constant.RegionConst;
import com.ningdatech.pmapi.common.helper.RegionCacheHelper;
import com.ningdatech.pmapi.common.helper.UserInfoHelper;
import com.ningdatech.pmapi.datascope.model.DataScopeDTO;
import com.ningdatech.pmapi.datascope.provider.DataScopeProvider;
import com.ningdatech.pmapi.user.entity.enumeration.RoleEnum;
import com.ningdatech.pmapi.user.security.auth.model.UserFullInfoDTO;
import com.ningdatech.pmapi.user.util.LoginUserUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

/**
 * <p>
 * 数据权限
 * </p>
 *
 * @author ZPF
 * @since 2023/3/27 23:29
 */
@Slf4j
@RequiredArgsConstructor
@Component("REGION_MANAGER")
public class RegionAdminDataScopeProviderImpl implements DataScopeProvider {

    private final RegionCacheHelper regionCacheHelper;
    private final UserInfoHelper userInfoHelper;

    @Override
    public Optional<DataScopeDTO> findDataFieldProperty() {
        UserFullInfoDTO userFullInfo = userInfoHelper.getUserFullInfo(LoginUserUtil.getUserId());
        //借由 丽水市的code 来映射市本级的regionCode
        Collection<String> regionCodes = regionCacheHelper.listChildRegionCodeList(userFullInfo.getRegionCode(),
                RegionConst.RL_CITY);
        //如果不是市本级的话 就直接放入本区域的县就好了
        if(CollUtil.isEmpty(regionCodes)){
            regionCodes = Lists.newArrayList();
            regionCodes.add(userFullInfo.getRegionCode());
        }

        DataScopeDTO ds = new DataScopeDTO();
        ds.setRegionCodes(new ArrayList<>(regionCodes));
        ds.setUserId(userFullInfo.getUserId());
        ds.setEmployeeCode(userFullInfo.getEmployeeCode());
        ds.setRole(RoleEnum.REGION_MANAGER);
        return Optional.of(ds);
    }

}
