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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
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.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
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.service.StoreService;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.chat.ChatOwnerTotalDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatPlanOwnerLogDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.GroupChatPlanSearchQDTO;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatPlanOwnerLogMapper;
import com.gic.haoban.manage.service.entity.TabHaobanClerkMainStoreRelated;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatPlan;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatPlanOwnerLog;
import com.gic.haoban.manage.service.service.ClerkMainStoreRelatedService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.chat.GroupChatPlanOwnerLogService;
import com.github.pagehelper.PageHelper;

@Service("groupChatPlanOwnerLogService")
public class GroupChatPlanOwnerLogServiceImpl implements GroupChatPlanOwnerLogService {

    private static final Logger logger = LogManager.getLogger(GroupChatPlanOwnerLogService.class);

    @Autowired
    private GroupChatPlanOwnerLogMapper groupChatPlanOwnerLogMapper;
    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StoreService storeService;

    public TabGroupChatPlanOwnerLog getById(Long ownerLogId) {
        TabGroupChatPlanOwnerLog log = this.groupChatPlanOwnerLogMapper.selectById(ownerLogId);
        return log;
    }

    @Override
    public void updateSendCount(Long id, int sendCount, Date sendTime, int failCount) {
        this.groupChatPlanOwnerLogMapper.updateSendCount(id, sendCount, failCount, sendTime);
    }

    @Override
    public Page<GroupChatPlanOwnerLogDTO> listPage(Long planId, GroupChatPlanSearchQDTO qdto,
            BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo);
        qdto.setPlanId(planId);
        List<GroupChatPlanOwnerLogDTO> list = this.groupChatPlanOwnerLogMapper.listPage(qdto);
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> clerkIdList = list.stream().filter(dto -> StringUtils.isNotBlank(dto.getClerkId()))
                    .map(dto -> dto.getClerkId()).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(clerkIdList)) {
                List<ClerkDTO> clerkList = this.clerkService.getClerkByClerkIds(clerkIdList);
                if (CollectionUtils.isNotEmpty(clerkList)) {
                    Map<String, ClerkDTO> map = clerkList.stream()
                            .collect(Collectors.toMap(ClerkDTO::getClerkId, dto -> dto, (k1, k2) -> k1));
                    list.forEach(dto -> {
                        String clerkId = dto.getClerkId();
                        if (StringUtils.isNotBlank(clerkId) && null != map.get(clerkId)) {
                            dto.setClerkCode(map.get(clerkId).getClerkCode());
                            dto.setClerkName(map.get(clerkId).getClerkName());
                        }
                    });
                }
            }
            List<String> storeIdList = list.stream().filter(dto -> StringUtils.isNotBlank(dto.getStoreId()))
                    .map(dto -> dto.getStoreId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(storeIdList)) {
                String[] arr = new String[storeIdList.size()];
                for (int i = 0; i < storeIdList.size(); i++) {
                    arr[i] = storeIdList.get(i);
                }
                List<StoreDTO> storeList = this.storeService.getStores(arr);
                Map<String, StoreDTO> map = storeList.stream()
                        .collect(Collectors.toMap(StoreDTO::getStoreId, dto -> dto, (k1, k2) -> k1));
                list.forEach(dto -> {
                    String storeId = dto.getStoreId();
                    if (StringUtils.isNotBlank(storeId) && null != map.get(storeId)) {
                        dto.setStoreCode(map.get(storeId).getStoreCode());
                        dto.setStoreName(map.get(storeId).getStoreName());
                    }
                });
            }
        }
        Page<GroupChatPlanOwnerLogDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list,
                GroupChatPlanOwnerLogDTO.class);
        return retPage;
    }

    @Override
    public void batchAdd(String staffIdList, TabGroupChatPlan entity) {
        if (StringUtils.isBlank(staffIdList)) {
            return;
        }
        String[] arr = staffIdList.split(",");
        List<TabGroupChatPlanOwnerLog> logList = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            String staffId = arr[i];
            TabGroupChatPlanOwnerLog log = new TabGroupChatPlanOwnerLog();
            log.setOwnerLogId(UniqueIdUtils.uniqueLong());
            log.setWxEnterpriseId(entity.getWxEnterpriseId());
            log.setEnterpriseId(entity.getEnterpriseId());
            log.setPlanId(entity.getPlanId());
            log.setSendStatus(1);
            log.setCreateTime(new Date());
            log.setUpdateTime(new Date());
            log.setSendCount(0);
            log.setStaffId(staffId);
            logList.add(log);
        }
        this.groupChatPlanOwnerLogMapper.batchInsert(logList);
    }

    @Override
    public void update(TabGroupChatPlanOwnerLog entity) {
        String staffId = entity.getStaffId();
        TabHaobanClerkMainStoreRelated mainStore = this.clerkMainStoreRelatedService.getMainStoreByStaffId(staffId,
                entity.getWxEnterpriseId());
        if (null == mainStore) {
            entity.setRemark("区经/未配置主门店");
        } else {
            String storeId = mainStore.getStoreId();
            StaffClerkRelationDTO clerk = this.staffClerkRelationService.getOneBindByStoreId(staffId, storeId);
            if (null != clerk) {
                if (!clerk.getEnterpriseId().equals(entity.getEnterpriseId())) {
                    entity.setRemark("主门店不在任务商户下");
                } else {
                    entity.setClerkId(clerk.getClerkId());
                    entity.setStoreId(mainStore.getStoreId());
                }
            } else {
                entity.setRemark("无关联导购");
                logger.info("导购关联数据不存在,staffid={},storeid={}", staffId, mainStore.getStoreId());
            }
        }
        this.groupChatPlanOwnerLogMapper.update(entity);
    }

    @Override
    public List<Long> listForTimer(Long planId) {
        List<Long> list = this.groupChatPlanOwnerLogMapper.listForTimer(planId);
        return list;
    }

    @Override
    public void deleteByStaffIds(Long planId, String delStaffIds) {
        if (StringUtils.isBlank(delStaffIds)) {
            return;
        }
        String[] arr = delStaffIds.split(",");
        List<String> delStaffIdList = Arrays.asList(arr);
        if (CollectionUtils.isEmpty(delStaffIdList)) {
            return;
        }
        this.groupChatPlanOwnerLogMapper.deleteByStaffIds(planId, delStaffIdList);
    }

    @Override
    public Page<ChatOwnerTotalDTO> listOwnerLogPageForWxaTotal(GroupChatPlanSearchQDTO qdto,
            BasePageInfo basePageInfo) {
        String clerkId = qdto.getClerkId();
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId);
        if (null == clerk) {
            logger.info("导购不存在");
            return new Page<ChatOwnerTotalDTO>();
        }
        int clerkType = clerk.getClerkType();
        String storeId = null;
        if (clerkType == 1) {
            storeId = clerk.getStoreId();
            clerkId = null;
            qdto.setClerkId(null);
            if (StringUtils.isNotBlank(qdto.getSearchClerkId())) {
                qdto.setClerkId(qdto.getSearchClerkId());
            }
        }
        qdto.setStoreId(storeId);
        PageHelper.startPage(basePageInfo);
        List<ChatOwnerTotalDTO> list = this.groupChatPlanOwnerLogMapper.listOwnerLogPageForWxaTotal(qdto);
        Page<ChatOwnerTotalDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, ChatOwnerTotalDTO.class);
        return retPage;
    }

    @Override
    public Page<GroupChatPlanOwnerLogDTO> listOwnerLogPageForWxa(GroupChatPlanSearchQDTO qdto,
            BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo);
        String clerkId = qdto.getClerkId();
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId);
        int clerkType = clerk.getClerkType();
        String storeId = null;
        if (clerkType == 1) {
            storeId = clerk.getStoreId();
            clerkId = null;
            qdto.setClerkId(null);
            if (StringUtils.isNotBlank(qdto.getSearchClerkId())) {
                qdto.setClerkId(qdto.getSearchClerkId());
            }
        }
        qdto.setStoreId(storeId);
        List<GroupChatPlanOwnerLogDTO> list = this.groupChatPlanOwnerLogMapper.listOwnerLogPageForWxa(qdto);
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> clerkIdList = list.stream().filter(dto -> StringUtils.isNotBlank(dto.getClerkId()))
                    .map(dto -> dto.getClerkId()).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(clerkIdList)) {
                List<ClerkDTO> clerkList = this.clerkService.getClerkByClerkIds(clerkIdList);
                if (CollectionUtils.isNotEmpty(clerkList)) {
                    Map<String, ClerkDTO> map = clerkList.stream()
                            .collect(Collectors.toMap(ClerkDTO::getClerkId, dto -> dto, (k1, k2) -> k1));
                    list.forEach(dto -> {
                        String clerkIdTemp = dto.getClerkId();
                        if (StringUtils.isNotBlank(clerkIdTemp) && null != map.get(clerkIdTemp)) {
                            dto.setClerkCode(map.get(clerkIdTemp).getClerkCode());
                            dto.setClerkName(map.get(clerkIdTemp).getClerkName());
                        }
                    });
                }
            }
        }
        Page<GroupChatPlanOwnerLogDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list,
                GroupChatPlanOwnerLogDTO.class);
        return retPage;
    }

    @Override
    public GroupChatPlanOwnerLogDTO getOwnerInfo(Long planId, String staffId, String clerkId, String wxEnterpriseId) {
        GroupChatPlanOwnerLogDTO dto = this.groupChatPlanOwnerLogMapper.getOwnerInfo(planId, staffId, clerkId,
                wxEnterpriseId);
        if (null != dto && StringUtils.isNotBlank(dto.getClerkId())) {
            ClerkDTO clerk = this.clerkService.getclerkById(dto.getClerkId());
            dto.setClerkName(clerk.getClerkName());
        }
        return dto;
    }

    @Override
    public Integer getTotalCount(String enterpriseId, String clerkId, String storeId) {
        return groupChatPlanOwnerLogMapper.getTotalCount(enterpriseId,clerkId,storeId);
    }

}