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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkStoreListDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.StoreGroupDTO;
import com.gic.enterprise.api.dto.StoreSearchDTO;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.hm.HmQrcodeStoreDTO;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.service.hm.HmQrcodeApiService;
import com.gic.haoban.manage.web.vo.hm.ClerkListVO;
import com.gic.haoban.manage.web.vo.hm.ClerkStoreListVO;
import com.gic.haoban.manage.web.vo.hm.StoreVO;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("hm")
public class HmStoreController {

    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(HmStoreController.class);

    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private HmQrcodeApiService hmQrcodeApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private StoreGroupService storeGroupService ;

    /**
     * 
    * @Title: listStoreClerk
    * @Description: 活码选择导购
    * @author xugh
    * @param request
    * @param basePageInfo
    * @return
    * @throws
     */
    @RequestMapping("store-clerk-list")
    @ResponseBody
    public RestResponse<Object> listStoreClerk(HttpServletRequest request, BasePageInfo basePageInfo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String enterpriseId = loginUser.getEnterpriseId();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        // 分组id [多个,号分割]
        String storeGroupId = request.getParameter("storeGroupId");
        // 门店参数
        String storeSearchParams = request.getParameter("storeSearchParams");
        // 导购参数
        String clerkSearchParams = request.getParameter("clerkSearchParams");
        Map<String, Object> params = new HashMap<>();
        params.put("enterpriseId", enterpriseId);
        // 2线上
        params.put("status", 2);
        if(StringUtils.isNotBlank(storeGroupId)) {
            boolean flag = true ;
            if(!storeGroupId.contains(",")) {
              StoreGroupDTO groupDTO = this.storeGroupService.getStoreGroupById(storeGroupId) ;
                if(null != groupDTO && groupDTO.getParentGroupId().equals("0")) {
                    flag = false ;
                }
            }
            if(flag) {
                List<String> storeGroupIds = Arrays.asList(storeGroupId.split(",")) ;
                List<String> groupIds = storeGroupService.getStoreGroupIdsByParentGroupId(enterpriseId, storeGroupIds);
                logger.info("分组的数量={}",groupIds.size());
                params.put("storeGroupIdList", groupIds);
            }
        }
        // 只获取导购和店长
        params.put("clerkTypeList", Arrays.asList(1, 0));
        if (StringUtils.isNotBlank(storeSearchParams)) {
            params.put("storeSearchParams", "%" + storeSearchParams + "%");
        }
        if (StringUtils.isNotBlank(clerkSearchParams)) {
            params.put("clerkSearchParams", "%" + clerkSearchParams + "%");
        }
        // 如果有权限控制,进行管辖门店过0滤
        List<String> authStoreIdList = this.staffApiService.getHaoBanStoreIdsRolesByClerkId(loginUser.getClerkId(),
                loginUser.getWxEnterpriseId());
        if (CollectionUtils.isEmpty(authStoreIdList)) {
            return RestResponse.failure("-1", "无授权门店");
        }
        if (!(authStoreIdList.size() == 1 && authStoreIdList.contains("-1"))) {
            params.put("storeIdList", authStoreIdList);
        }
        Page<ClerkStoreListDTO> page = new Page<>();
        page.setPageSize(basePageInfo.getPageSize());
        page.setCurrentPage(basePageInfo.getPageNum());
        page.setParams(params);
        logger.info("查询条件:{}", JSON.toJSONString(params));
        page = this.clerkService.listStoreClerkByPage(page);
        Page<ClerkStoreListVO> retPage = new Page<>();
        retPage.setPageSize(basePageInfo.getPageSize());
        retPage.setCurrentPage(basePageInfo.getPageNum());
        retPage.setParams(params);
        retPage.setTotalCount(page.getTotalCount());
        retPage.setTotalPage(page.getTotalPage());
        List<ClerkStoreListVO> result = EntityUtil.changeEntityListByJSON(ClerkStoreListVO.class, page.getResult());
        // 好办状态
        this.haobanStatus(result, wxEnterpriseId, enterpriseId);
        retPage.setResult(result);
        return RestResponse.successResult(retPage);
    }

    private void haobanStatus(List<ClerkStoreListVO> list, String wxEnterpriseId, String enterpriseId) {
        List<String> clerkIdList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (ClerkStoreListVO store : list) {
            if (CollectionUtils.isNotEmpty(store.getClerkList())) {
                List<String> tempList = store.getClerkList().stream().map(dto -> dto.getClerkId())
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(tempList)) {
                    clerkIdList.addAll(tempList);
                }
            }
        }
        logger.info("导购列表={}", clerkIdList);
        // 未开启客户联系的
        List<String> status2List = new ArrayList<>();
        // 已有单人活码的
        List<String> status3List = new ArrayList<>();
        // 可以创建单人活码的
        List<String> status4List = new ArrayList<>();
        // 已关联企微号的,且开启客户联系
        List<String> statusList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(clerkIdList)) {
            List<StaffClerkRelationDTO> clerkRelationList = this.staffClerkRelationApiService
                    .listByClerkIdsWxEnterpriseId(clerkIdList, wxEnterpriseId);
            if (CollectionUtils.isNotEmpty(clerkRelationList)) {
                status2List.addAll(clerkRelationList.stream().filter(dto -> dto.getOpenConcatFlag() == 0)
                        .map(dto -> dto.getClerkId()).collect(Collectors.toList()));
                statusList.addAll(clerkRelationList.stream().filter(dto -> dto.getOpenConcatFlag() == 1)
                        .map(dto -> dto.getClerkId()).collect(Collectors.toList()));
            }
        }
        if (CollectionUtils.isNotEmpty(statusList)) {
            ServiceResponse<List<String>> hmClerkResp = this.hmQrcodeApiService.listHasQrcodeClerk(enterpriseId,
                    statusList);
            if (CollectionUtils.isNotEmpty(hmClerkResp.getResult())) {
                status3List.addAll(hmClerkResp.getResult());
            }
            status4List
                    .addAll(statusList.stream().filter(id -> (!status3List.contains(id)))
                            .collect(Collectors.toList()));
        }
        logger.info("导购列表未开启客户联系的={} , 已有单人活码的={}, 可以创建单人活码的={}", status2List, status3List, status4List);
        list.stream().forEach(item -> {
            for (ClerkListVO clerk : item.getClerkList()) {
                if (status2List.contains(clerk.getClerkId())) {
                    clerk.setHmStatus(2);
                }
                if (status3List.contains(clerk.getClerkId())) {
                    clerk.setHmStatus(3);
                }
                if (status4List.contains(clerk.getClerkId())) {
                    clerk.setHmStatus(4);
                }
            }
        });
    }

    /**
     * 
    * @Title: listStore
    * @Description: 链接-推荐门店查询
    * @author xugh
    * @param request
    * @param basePageInfo
    * @return
    * @throws
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("store-list")
    @ResponseBody
    public RestResponse<Object> listStore(HttpServletRequest request, BasePageInfo basePageInfo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        String clerkId = loginUser.getClerkId();
        // 如果有权限控制,进行管辖门店过0滤
        List<String> authStoreIdList = this.staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        if (CollectionUtils.isEmpty(authStoreIdList)) {
            return RestResponse.failure("-1", "无授权门店");
        }
        StoreSearchDTO searchDTO = new StoreSearchDTO();
        // 上线门店
        searchDTO.setStatus("2");
        searchDTO.setRecycleStoreCount(0);
        searchDTO.setMemberCountFlag(0);
        String storeSearchParams = request.getParameter("storeSearchParams");
        searchDTO.setSearchName(storeSearchParams);
        // 企业ID
        searchDTO.setEnterpriseId(enterpriseId);
        List<HmQrcodeStoreDTO> hmStoreList = this.hmQrcodeApiService.getHmStoreByEnterpriseId(wxEnterpriseId , enterpriseId);
        if (CollectionUtils.isEmpty(hmStoreList)) {
            return RestResponse.failure("-1", "无活码门店");
        }
        Map<String, Integer> map = hmStoreList.stream()
                .collect(Collectors.toMap(HmQrcodeStoreDTO::getStoreId, HmQrcodeStoreDTO::getOverFlag, (k1, k2) -> k1));
        List<String> hmStoreIdList = hmStoreList.stream().map(dto -> dto.getStoreId()).collect(Collectors.toList());
        logger.info("活码门店={}",hmStoreIdList);
        if(!authStoreIdList.contains("-1")) {
            Sets.SetView<String> setView = Sets.intersection(Sets.newHashSet(authStoreIdList),
                    Sets.newHashSet(hmStoreIdList));
            hmStoreIdList = setView.stream().collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(hmStoreIdList)) {
            return RestResponse.failure("-1", "无符合门店");
        }
        // 授权门店 且有活码的门店
        if (CollectionUtils.isNotEmpty(hmStoreIdList)) {
            searchDTO.setAuthStoreIdList(hmStoreIdList);
        }
        // 门店参数
        Page page = new Page();
        page.setPageSize(basePageInfo.getPageSize());
        page.setCurrentPage(basePageInfo.getPageNum());
        Map<String, Object> params = new HashMap<>();
        params.put("searchDto", searchDTO);
        page.setParams(params);
        logger.info("查询条件={}", JSON.toJSONString(page));
        Map<String, Object> result = storeService.getStoreListPage(page);
        page = (Page) result.get("page");
        List<StoreDTO> storeList = (List<StoreDTO>) result.get("list");
        List<StoreVO> retList = new ArrayList<StoreVO>();
        StoreVO vo = null;
        for (StoreDTO dto : storeList) {
            vo = new StoreVO();
            vo.setStoreId(dto.getStoreId());
            vo.setStoreCode(dto.getStoreCode());
            vo.setStoreName(dto.getStoreName());
            vo.setIsOver(map.get(dto.getStoreId()) == null ? 0 : map.get(dto.getStoreId()));
            retList.add(vo);
        }
        page.setResult(retList);
        return RestResponse.successResult(page);
    }
}
