package com.gic.haoban.manage.service.service.impl;

import com.alibaba.fastjson.JSONObject;
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.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.StoreDTO;
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.manage.api.dto.OpenStaffDTO;
import com.gic.haoban.manage.api.dto.OpenStaffListDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StoreClerkDTO;
import com.gic.haoban.manage.api.qdto.OpenStaffPageQDTO;
import com.gic.haoban.manage.service.dao.mapper.OpenStaffMapper;
import com.gic.haoban.manage.service.entity.TabOpenStaff;
import com.gic.haoban.manage.service.service.OpenStaffService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.util.OpenUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("openStaffService")
public class OpenStaffServiceImpl implements OpenStaffService {

    private static final Logger log = LogManager.getLogger(OpenStaffService.class);

    @Autowired
    private OpenStaffMapper openStaffMapper;
    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private StoreGroupService storeGroupService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ClerkService clerkService ;

    @Override
    public TabOpenStaff save(TabOpenStaff tab) {
        tab.setUpdateTime(new Date());
        if (null == tab.getOpenStaffId()) {
            tab.setOpenStaffId(UniqueIdUtils.uniqueLong());
            tab.setDeleteFlag(0);
            tab.setCreateTime(new Date());
            this.openStaffMapper.insert(tab);
        } else {
            this.openStaffMapper.update(tab);
        }
        return tab;
    }

    @Override
    public TabOpenStaff getByUUID(String uuid) {
        TabOpenStaff openStaff = this.openStaffMapper.getByUUID(uuid);
        if (null == openStaff) {
            log.info("通过uuid查不到={}", uuid);
            OpenUtils.logout(uuid);
        }
        return openStaff;
    }

    @Override
    public void logout(String uuid, String loginRemark, int step) {
        TabOpenStaff openStaff = this.getByUUID(uuid);
        if (null == openStaff) {
            return;
        }
        OpenUtils.logout(uuid);
        openStaff.setStep(step);
        openStaff.setStatusFlag(2);
        openStaff.setValidFlag(0);
        openStaff.setValidQrcodeFlag(0);
        openStaff.setQrCode1(null);
        openStaff.setQrCode2(null);
        openStaff.setKey1(null);
        openStaff.setKey2(null);
        openStaff.setUuid(null);
        openStaff.setLoginRemark(loginRemark);
        this.openStaffMapper.update(openStaff);
    }

    @Override
    public ServiceResponse<Page<OpenStaffListDTO>> page(OpenStaffPageQDTO qdto, BasePageInfo basePageInfo) {
        log.info("分页查询条件={}",JSONObject.toJSONString(qdto));
        String wxEnterpriseId = qdto.getWxEnterpriseId();
        String enterpriseId = qdto.getEnterpriseId();
        List<String> storeIdList = null;
        if(CollectionUtils.isNotEmpty(qdto.getStoreGroupIdList())) {
            storeIdList = this.getStoreIdList(enterpriseId,qdto.getStoreGroupIdList()) ;
        }
        if (StringUtils.isNotBlank(qdto.getClerkId()) || CollectionUtils.isNotEmpty(storeIdList)) {
            List<String> staffIds = staffClerkRelationService.listAllStaffIdForOpenStaff(enterpriseId, wxEnterpriseId, qdto.getClerkId(), storeIdList);
            if (CollectionUtils.isEmpty(staffIds)) {
                return ServiceResponse.success(new Page<>());
            }
            qdto.setStaffIds(staffIds);
        }
        PageHelper.startPage(basePageInfo);
        List<OpenStaffListDTO> list = this.openStaffMapper.list(qdto);
        Set<String> staffIdList = list.stream().map(dto -> dto.getStaffId()).collect(Collectors.toSet());
        List<StaffClerkRelationDTO> relationDTOList = staffClerkRelationService.listByWxEnterpriseIdAndStaffId(wxEnterpriseId, staffIdList);
        relationDTOList = relationDTOList.stream().filter(o->o.getEnterpriseId().equals(enterpriseId)).collect(Collectors.toList()) ;
        Map<String, ClerkDTO> clerkMap = new HashMap<>() ;
        if(CollectionUtils.isNotEmpty(relationDTOList)) {
            Set<String> clerkIdSet = relationDTOList.stream().map(o->o.getClerkId()).collect(Collectors.toSet()) ;
            if(CollectionUtils.isNotEmpty(clerkIdSet)) {
                List<ClerkDTO> clerkDTOS = this.clerkService.getClerkByIds(clerkIdSet);
                clerkMap.putAll(clerkDTOS.stream().collect(Collectors.toMap(o -> o.getClerkId(), o -> o, (k1, k2) -> k1)));
            }
        }
        log.info("导购={}", JSONObject.toJSONString(clerkMap));
        for(OpenStaffListDTO item : list) {
            String staffId = item.getStaffId() ;
            List<StoreClerkDTO> clerkList = new ArrayList<>() ;
            for (StaffClerkRelationDTO clerkRelation : relationDTOList){
                if (clerkRelation.getStaffId().equals(staffId)){
                    String storeId = clerkRelation.getStoreId() ;
                    String clerkId = clerkRelation.getClerkId() ;
                    ClerkDTO clerkDTO = clerkMap.get(clerkId) ;
                    if(null != clerkDTO) {
                        StoreClerkDTO cs = new StoreClerkDTO();
                        cs.setClerkId(clerkId);
                        cs.setClerkName(clerkDTO.getClerkName());
                        cs.setClerkCode(clerkDTO.getClerkCode());
                        StoreDTO store = this.storeService.getStore(storeId);
                        if(null != store) {
                            cs.setStoreId(storeId);
                            cs.setStoreName(store.getStoreName());
                            cs.setStoreCode(store.getStoreCode());
                        }
                        clerkList.add(cs) ;
                    }
                }
            }
            item.setClerkList(clerkList);
        }
        Page<OpenStaffListDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, OpenStaffListDTO.class);
        log.info("分页查询结果={}",JSONObject.toJSONString(retPage,true));
        return ServiceResponse.success(retPage);
    }

    @Override
    public List<String> listAllStaffId(String wxEnterpriseId) {
        return this.openStaffMapper.listAllStaffId(wxEnterpriseId);
    }


    private List<String> getStoreIdList(String enterpriseId, List<String> storeGroupIds) {
        StoreSearchDTO storeSearch = new StoreSearchDTO();
        List<String> groupIds = storeGroupService.getStoreGroupIdsByParentGroupId(enterpriseId, storeGroupIds);
        storeSearch.setStoreGroupIdList(groupIds);
        storeSearch.setEnterpriseId(enterpriseId);
        storeSearch.setStatus("2");
        Page pageStore = new Page<>();
        //-1代表不分页
        pageStore.setCurrentPage(-1);
        Page resultPage = storeService.storeListPage(pageStore, storeSearch);
        List<StoreDTO> storeDTOList = resultPage.getResult();
        if (CollectionUtils.isEmpty(storeDTOList)) {
            return new ArrayList<>();
        }
        log.info("门店条件查询,返回={}条", storeDTOList.size());
        List<String> searchStoreIds = storeDTOList.stream().map(StoreDTO::getStoreId).distinct().collect(Collectors.toList());
        return searchStoreIds;
    }

}
