package com.gic.haoban.manage.web.controller;

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.enterprise.api.dto.EnterpriseSettingDTO;
import com.gic.enterprise.api.dto.PowerStoreGroupDTO;
import com.gic.enterprise.api.dto.StoreGroupDTO;
import com.gic.enterprise.api.dto.StoreWidgetDTO;
import com.gic.enterprise.api.dto.StoreWidgetRightDataDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreWidgetService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.StoreRangeInfoDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.HaobanStoreGroupVO;
import com.gic.haoban.manage.web.vo.StoreGroupVo;


@RestController
public class GicDepartmentController extends WebBaseController{
	
	private static Logger logger  = LoggerFactory.getLogger(GicDepartmentController.class);
	
	@Autowired
	private StoreGroupService storeGroupService;
	@Autowired
	private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
	@Autowired
	private EnterpriseService enterpriseService ;
	@Autowired
	private ClerkService clerkService ;
	@Autowired
	private StoreWidgetService storeWidgetService ;
	
	@RequestMapping("gic-department-list")
	public HaobanResponse departmentList(String keyWord) {
	    WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser() ;
	    String enterpriseId = loginUser.getEnterpriseId() ;
	    EnterpriseSettingDTO enterpriseSetting = enterpriseService.getEnterpriseSettingByEnterpriseId(enterpriseId) ;
	    List<StoreWidgetRightDataDTO> list = null ;
        if (enterpriseSetting.getEnableAccessControl() != null && enterpriseSetting.getEnableAccessControl() == 1 && !Integer.valueOf(1).equals(loginUser.getSuperAdmin())) {
            String clerkId = loginUser.getClerkId() ;
            ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
            String storeWidgetId = clerk.getStoreWidgetId() ;
            int selectType = 3 ; 
            if(StringUtils.isNotBlank(storeWidgetId)) {
                StoreWidgetDTO storeWidgetDTO = this.storeWidgetService.getStoreWidgetBykey(storeWidgetId);
                if(null != storeWidgetDTO) {
                    selectType = storeWidgetDTO.getSelectType() ;
                }
            }
            if(0 != selectType && 4!=selectType) {
                return this.resultResponse(HaoBanErrCode.ERR_10031) ;
            }
            if(4==selectType) {
                Page page = new Page();
                page.setPageSize(3000);
                page.setCurrentPage(1);
                page = this.storeWidgetService.listRightData(storeWidgetId, page, null) ;
                list = page.getResult() ;
                if(CollectionUtils.isEmpty(list)) {
                    list = new ArrayList<StoreWidgetRightDataDTO>();
                }
            }
        }
        List<HaobanStoreGroupVO> retList = new ArrayList<>();
        List<PowerStoreGroupDTO>  departmentList = storeGroupService.getStoreGroupList(enterpriseId, keyWord);
        if(null != list) {
            List<String> idList = list.stream().map(dto->dto.getId()).collect(Collectors.toList()) ;
            logger.info("有权限的列表={}",idList);
            Set<String> otherList = new HashSet<>();
            for(PowerStoreGroupDTO item : departmentList) {
                if(idList.contains(item.getStoreGroupId())) {
                    HaobanStoreGroupVO vo = EntityUtil.changeEntityByOrika(HaobanStoreGroupVO.class, item) ;
                    vo.setHasRight(true);
                    retList.add(vo) ;
                    String chain = item.getStoreGroupChain() ;
                    String[] arr = chain.split("_") ;
                    for(int i=0;i<arr.length;i++) {
                        String s = arr[i] ;
                        if(StringUtils.isNotBlank(s) && !s.equals(item.getStoreGroupId())) {
                            otherList.add(s) ;
                        }
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(idList)) {
                this.addSubGroup(enterpriseId, idList, retList);
            }
            for(PowerStoreGroupDTO item : departmentList) {
                String groupId = item.getStoreGroupId() ;
                if(idList.contains(groupId)) {
                    continue ;
                }
                if(otherList.contains(groupId)) {
                    HaobanStoreGroupVO vo = EntityUtil.changeEntityByOrika(HaobanStoreGroupVO.class, item) ;
                    idList.add(vo.getStoreGroupId());
                    retList.add(vo) ;
                }
            }
            return resultResponse(HaoBanErrCode.ERR_1,retList) ;
        }else {
            retList = EntityUtil.changeEntityListByOrika(HaobanStoreGroupVO.class, departmentList) ;
            retList.forEach(item->{;
                item.setHasRight(true);
            });
        }
		return resultResponse(HaoBanErrCode.ERR_1,retList);
	}
    // 增加所有子分组
	private void addSubGroup(String enterpriseId , List<String> idList , List<HaobanStoreGroupVO> retList) {
	    String[] arr = new String[idList.size()] ;
	    for(int i=0;i<idList.size();i++) {
	        arr[i] = idList.get(i) ;
	    }
	    List<StoreGroupDTO> list = this.storeGroupService.listStoreGroupAndChildren(arr,enterpriseId) ;
	    if(CollectionUtils.isNotEmpty(list)) {
	        List<HaobanStoreGroupVO> voList = EntityUtil.changeEntityListByOrika(HaobanStoreGroupVO.class, list) ;
	        for(HaobanStoreGroupVO item : voList) {
	            if(!idList.contains(item.getStoreGroupId())) {
	                item.setHasRight(true);
	                retList.add(item) ;
	                idList.add(item.getStoreGroupId()) ;
                }
	        }
	    }
	}

	@RequestMapping("gic-store-group-list")
	public HaobanResponse storeGroupList(String enterpriseId, String keyWord) {
	    WebLoginDTO loginUser =  AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
		List<PowerStoreGroupDTO> departmentList = storeGroupService.getStoreGroupList(enterpriseId, keyWord);
		List<StoreRangeInfoDTO> rangeInfoDTOList = wxEnterpriseRelatedApiService.listAllBindStoreOrGroup(enterpriseId);
		Map<String, StoreRangeInfoDTO> storeRangeMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(rangeInfoDTOList)) {
			List<WxEnterpriseDTO> wxEnterpriseDTOS = wxEnterpriseRelatedApiService.listWxEnterpriseByEid(enterpriseId);
			if (CollectionUtils.isNotEmpty(wxEnterpriseDTOS)) {
				Map<String, WxEnterpriseDTO> wxEnterpriseDTOMap = wxEnterpriseDTOS.stream().collect(Collectors.toMap(WxEnterpriseDTO::getWxEnterpriseId, dto -> dto));
				storeRangeMap = rangeInfoDTOList.stream()
						.filter(dto -> (!dto.getWxEnterpriseId().equals(wxEnterpriseId))
								&& dto.getRelationType() == 1
								&& wxEnterpriseDTOMap.get(dto.getWxEnterpriseId()) != null)
						.peek(dto -> dto.setWxEnterpriseName(wxEnterpriseDTOMap.get(dto.getWxEnterpriseId()).getCorpName()))
						.collect(Collectors.toMap(StoreRangeInfoDTO::getRelationId, dto -> dto));
			}
		}
		Map<String, StoreRangeInfoDTO> finalStoreRangeMap = storeRangeMap;
		List<StoreGroupVo> ret = departmentList.stream().map(dto -> {
			StoreRangeInfoDTO mid = finalStoreRangeMap.get(dto.getStoreGroupId());
			StoreGroupVo storeGroupVo = new StoreGroupVo();
			storeGroupVo.setRelationId(dto.getStoreGroupId());
			storeGroupVo.setParentRelationId(dto.getParentGroupId());
			if (mid != null) {
				storeGroupVo.setIsBind(1);
				storeGroupVo.setWxEnterpriseId(mid.getWxEnterpriseId());
				storeGroupVo.setWxEnterpriseName(mid.getWxEnterpriseName());
			}
			storeGroupVo.setRelationType(1);
			storeGroupVo.setRelationName(dto.getStoreGroupName());
			return storeGroupVo;
		}).collect(Collectors.toList());
		return resultResponse(HaoBanErrCode.ERR_1, ret);

	}

}
