package com.kiisoo.ic.store.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kiisoo.ic.activity.entity.PmnActivityInstance;
import com.kiisoo.ic.activity.entity.PmnActivityStoreRelation;
import com.kiisoo.ic.activity.service.IPmnActivityInstanceService;
import com.kiisoo.ic.activity.service.IPmnActivityStoreRelationService;
import com.kiisoo.ic.customer.service.CustomerViewService;
import com.kiisoo.ic.domain.entity.PrivilageDomainEntityDO;
import com.kiisoo.ic.domain.mapper.PrivilageDomainEntityDOMapper;
import com.kiisoo.ic.domain.service.PrivilageDomainService;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizationalDomain;
import com.kiisoo.ic.generalize.mapper.PrivilageOrganizationalDomainMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.generalize.service.RetailCompanyService;
import com.kiisoo.ic.store.bean.PoiStoreDTO;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 店铺
 */
@Service
public class PoiStoreService {

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private PrivilageDomainService privilageDomainService;

    @Autowired
    private RetailCompanyService retailCompanyService;

    @Autowired
    private CustomerViewService customerViewService;

    @Autowired
    private PrivilageDomainEntityDOMapper privilageDomainEntityDOMapper;

    @Autowired
    private PrivilageOrganizationalDomainMapper privilageOrganizationalDomainMapper;
    @Autowired
    private RetailCompanyMapper retailCompanyMapper;
    @Autowired
    private IPmnActivityInstanceService pmnActivityInstanceService;
    @Autowired
    private IPmnActivityStoreRelationService storeRelationService;

    /**
     * 根据区域id找到店铺集合
     *
     * @param regionId
     */
    public List<PoiStore> getRegionShop(long regionId) {
        List<PoiStore> poiStores = poiStoreDOMapper.selectRegionShop(regionId);
        return poiStores;
    }

    /**
     * 根据区域id找到店铺集合，若没有，则查用户所有店铺
     */
    public List<PoiStore> getRegionShop(long userId, List<Long> customerIds) {
        List<PoiStore> poiStores = new ArrayList<>();
        //找到店铺集合
        List<Long> shopsIds = privilageDomainService.listUserDatePermission(userId);
        if (null != customerIds && customerIds.size() > 0) {
            Set<Long> shopIds = new HashSet<>();
            customerIds.forEach(customerId -> {
                Set<Long> shops = customerViewService.getCompanyShop(customerId, userId);
                if (CollectionUtils.isNotEmpty(shops)) {
                    shopIds.addAll(shops);
                }
            });
            if (shopIds.size() > 0) {
                List<PoiStore> regionPoiStores = poiStoreDOMapper.selectBatchIds(shopIds);
                for (PoiStore item : regionPoiStores) {
                    if (shopsIds.contains(item.getId())) {
                        poiStores.add(item);
                    }
                }
            }
        } else {
            poiStores = poiStoreDOMapper.selectBatchIds(shopsIds);
        }
        return poiStores;
    }

    /**
     * 根据区域id找到店铺集合，若没有，则查用户所有店铺
     */
    public List<PoiStoreDTO> getRegionShopDTO(long userId, List<Long> customerIds, Long scheduleId) {
        List<PoiStoreDTO> poiStores = new ArrayList<>();
        //找到店铺集合
        if (null != customerIds && customerIds.size() > 0) {
            Set<Long> cs = new HashSet<>();
            cs.addAll(customerIds);
            Set<Long> joined = new HashSet<>();
            if (scheduleId != null) {
                List<PmnActivityInstance> instances = pmnActivityInstanceService.list(Wrappers.<PmnActivityInstance>lambdaQuery().eq(PmnActivityInstance::getScheduleId, scheduleId).select(PmnActivityInstance::getId));
                if(instances.size() > 0) {
                    Set<Long> instanceIds = instances.stream().map(PmnActivityInstance::getId).collect(Collectors.toSet());
                    List<PmnActivityStoreRelation> relations = storeRelationService.list(Wrappers.<PmnActivityStoreRelation>lambdaQuery().in(PmnActivityStoreRelation::getInstanceId, instanceIds).select(PmnActivityStoreRelation::getStoreId));
                    joined = relations.stream().map(PmnActivityStoreRelation::getStoreId).collect(Collectors.toSet());
                }
            }
            Set<Long> childs = retailCompanyMapper.selectChildList(cs);
            List<PrivilageOrganizationalDomain> domains = privilageOrganizationalDomainMapper.selectList(Wrappers.<PrivilageOrganizationalDomain>lambdaQuery().in(PrivilageOrganizationalDomain::getOrgId, childs).select(PrivilageOrganizationalDomain::getDomainId));
            Set<Long> domainIds = domains.stream().map(PrivilageOrganizationalDomain::getDomainId).collect(Collectors.toSet());
            List<PrivilageDomainEntityDO> entityDOS = privilageDomainEntityDOMapper.selectList(Wrappers.<PrivilageDomainEntityDO>lambdaQuery().in(PrivilageDomainEntityDO::getDomainId, domainIds).eq(PrivilageDomainEntityDO::getType, 3).select(PrivilageDomainEntityDO::getEntityId));
            Set<Long> shopIds = entityDOS.stream().map(PrivilageDomainEntityDO::getEntityId).collect(Collectors.toSet());
            if (joined.size() > 0) {
                shopIds.removeAll(joined);
            }
            if (shopIds.size() > 0) {
                poiStores = poiStoreDOMapper.selectDTOBatchIds(shopIds);
            }
        } else {
            poiStores = poiStoreDOMapper.selectDTOBatchIds(privilageDomainService.listUserDatePermission(userId));
        }
        return poiStores;
    }

    /**
     * 查询所有店铺
     *
     * @return
     */
    public List<PoiStore> listAllShop() {
        List<PoiStore> baseShopDOS = poiStoreDOMapper.selectList(null);
        return baseShopDOS;
    }

    /**
     * 根据区域id找到店铺集合，若没有，则查用户所有店铺
     *
     * @param companyId 零售公司ID
     */
    public List<PoiStore> getStoreByCompanyId(long userId, Long companyId) {
        List<PoiStore> poiStores = new ArrayList<>();
        //找到店铺集合
        List<Long> shopsIds = privilageDomainService.listUserDatePermission(userId);
        if (!companyId.equals(0L)) {
            Set<Long> shops = customerViewService.getCompanyShop(companyId, userId);
            if (shops.size() > 0) {
                List<PoiStore> regionPoiStores = poiStoreDOMapper.selectBatchIds(shops);
                List<PoiStore> intersection = regionPoiStores.stream().filter(item -> shops.contains(item.getId())).collect(toList());
                return intersection;
            }
        } else {
            poiStores = poiStoreDOMapper.selectBatchIds(shopsIds);
        }
        return poiStores;
    }


    public List<PoiStore> organizationalList(String organizationalIdList) {

        return poiStoreDOMapper.organizationalList(organizationalIdList);
    }
}
