package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dto.buser.UserPositionAndUserScopeDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.UserPositionEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.service.EnterpriseUserService;
import com.cool.store.service.ZoneService;
import com.cool.store.vo.EnterpriseUserSingleInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangchenbiao
 * @FileName: EnterpriseUserServiceImpl
 * @Description:
 * @date 2023-05-29 19:58
 */
@Slf4j
@Service
public class EnterpriseUserServiceImpl implements EnterpriseUserService {


    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private EnterpriseUserRoleDAO enterpriseUserRoleDAO;
    @Resource
    private ZoneService zoneService;
    @Resource
    private RegionDAO regionDAO;
    @Resource
    private UserRegionMappingDAO userRegionMappingDAO;
    @Resource
    private HyIntendDevZoneInfoDAO hyIntendDevZoneInfoDAO;



    @Override
    public EnterpriseUserDO getUserInfoByUserId(String userId) {
        return enterpriseUserDAO.getUserInfoById(userId);
    }

    @Override
    public List<EnterpriseUserSingleInfoVO> getInvestmentManagerList(String type,String userId, String keyword) {
        //查询当前人员信息
        EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);

        //当前登录人所在组织机构
        List<String> regionIds = userRegionMappingDAO.getRegionIdsByUserId(userId);

        //所有绑定了战区的组织机构
        List<String> list = zoneService.queryAllBingZoneRegionList("intent");
        HashSet<String> regionList = new HashSet<>();
        regionIds.forEach(x->{
            if (list.contains(x)){
                regionList.add(x);
            }
        });
        //分配
        //如果是招商经理 只能分配给自己
        //如果是负责人 分配给负责人所在战区人员
        List<EnterpriseUserDO> enterpriseUserDOS = new ArrayList<>();
        if (CommonConstants.ALLOCATION.equals(type)){
            if (userInfo.getIsLeader()){
                 enterpriseUserDOS = enterpriseUserDAO.searchUserByRegionIdsAndKeyword(new ArrayList<>(regionList), keyword, JSONObject.parseArray(userInfo.getLeaderDeptIds(), String.class));
            }
            if (CollectionUtils.isNotEmpty(regionList)){
                //只有招商经理本人
                enterpriseUserDOS.add(userInfo);
            }
        }
        //转交 所有的招商经理
        if (CommonConstants.TRANSFER.equals(type)){
            enterpriseUserDOS = enterpriseUserDAO.searchUserByRegionIdsAndKeyword(new ArrayList<>(list), keyword, null);
        }
        if (CollectionUtils.isEmpty(enterpriseUserDOS)){
            enterpriseUserDOS.add(userInfo);
        }
        return EnterpriseUserSingleInfoVO.convertVO(enterpriseUserDOS);
    }

    @Override
    public UserPositionAndUserScopeDTO getUserIdsByScope(String userId) {
        EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);
        if(Objects.isNull(userInfo)){
            throw new ServiceException(ErrorCodeEnum.USER_NOT_EXIST);
        }
        UserPositionAndUserScopeDTO result = new UserPositionAndUserScopeDTO();
        if(!userInfo.getIsLeader()){
            result.setDevelopmentUserIds(Arrays.asList(userId));
            result.setInvestmentUserIds(Arrays.asList(userId));
            return result;
        }
        List<String> leadDeptIds = JSONObject.parseArray(userInfo.getLeaderDeptIds()).stream().map(String::valueOf).collect(Collectors.toList());
        //获取这些区域的子节点
        List<String> subRegionIds = regionDAO.getSubRegionIds(leadDeptIds);
        //这些部门是否关联了意向区域
        List<HyIntendDevZoneInfoDO> zoneInfoList = hyIntendDevZoneInfoDAO.getZoneInfoByRegionIds(subRegionIds);
        if(CollectionUtils.isEmpty(zoneInfoList)){
            result.setDevelopmentUserIds(Arrays.asList(userId));
            result.setInvestmentUserIds(Arrays.asList(userId));
            return result;
        }
        //意向区域
        List<String> intendList = zoneInfoList.stream().filter(o -> "intent".equals(o.getType())).flatMap(o->JSONObject.parseArray(o.getAssociatedRegionId(), String.class).stream()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(intendList)){
            //获取负责的区域
            intendList.retainAll(subRegionIds);
            List<String> userList = userRegionMappingDAO.getUserListByRegionIds(intendList);
            userList.add(userId);
            result.setInvestmentUserIds(userList);
        }
        //开发区域
        List<String> developmentList = zoneInfoList.stream().filter(o -> "dev".equals(o.getType())).flatMap(o->JSONObject.parseArray(o.getAssociatedRegionId(), String.class).stream()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(developmentList)){
            //获取负责的区域
            developmentList.retainAll(subRegionIds);
            List<String> userList = userRegionMappingDAO.getUserListByRegionIds(developmentList);
            userList.add(userId);
            result.setDevelopmentUserIds(userList);
        }
        return result;
    }

    @Override
    public List<EnterpriseUserSingleInfoVO> getDevelopmentDirectorList(String wantShopArea) {
        List<HyIntendDevZoneInfoDO> devList = hyIntendDevZoneInfoDAO.getHyIntendDevZoneInfoList("dev");
        List<String> regionIds = ListUtils.emptyIfNull(devList).stream().flatMap(o -> JSONObject.parseArray(o.getAssociatedRegionId(), String.class).stream()).collect(Collectors.toList());
        List<EnterpriseUserDO> userList = enterpriseUserDAO.getUserListByDeptLeaders(regionIds);
        return EnterpriseUserSingleInfoVO.convertVO(userList);
    }

    @Override
    public EnterpriseUserDO getDevelopmentByZoneId(Long zoneId) {
        HyIntendDevZoneInfoDO zoneInfo = hyIntendDevZoneInfoDAO.selectById(zoneId);
        if(Objects.isNull(zoneInfo)){
            throw new ServiceException(ErrorCodeEnum.ZONE_NOT_EXIST);
        }
        List<String> regionIds = JSONObject.parseArray(zoneInfo.getAssociatedRegionId(), String.class);
        List<EnterpriseUserDO> userList = enterpriseUserDAO.getUserListByDeptLeaders(regionIds);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }
        return userList.stream().findAny().get();
    }
}
