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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.stereotype.Service;

import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatDataDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatOwnerDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.ChatDataSearchQDTO;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.dao.mapper.WxEnterpriseMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatDataMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatOwnerMapper;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterprise;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatData;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.chat.GroupChatDataService;
import com.gic.wechat.api.dto.qywx.chat.GroupChatQwDataDTO;
import com.gic.wechat.api.dto.qywx.chat.GroupChatQwDataItemDTO;
import com.gic.wechat.api.service.qywx.QywxChatApiService;
import com.github.pagehelper.PageHelper;

@Service("groupChatDataService")
public class GroupChatDataServiceImpl implements GroupChatDataService {

    private static final Logger logger = LoggerFactory.getLogger(GroupChatDataService.class);

    // 每次成员数
    private int pageSize = 100;

    @Autowired
    private QywxChatApiService qywxChatApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private Config config;
    @Autowired
    private GroupChatOwnerMapper groupChatOwnerMapper;
    @Autowired
    private GroupChatDataMapper groupChatDataMapper;
    @Autowired
    private WxEnterpriseMapper wxEnterpriseMapper;

    @Override
    public List<GroupChatDataDTO> listForChat(ChatDataSearchQDTO qdto) {
        return this.groupChatDataMapper.listForChat(qdto);
    }

    @Override
    public Page<GroupChatDataDTO> listStaffData(ChatDataSearchQDTO qdto, BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo);
        List<GroupChatDataDTO> list = this.groupChatDataMapper.listStaffData(qdto);
        Page<GroupChatDataDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, GroupChatDataDTO.class);
        return retPage;
    }

    @Override
    public GroupChatDataDTO listTotalData(ChatDataSearchQDTO qdto) {
        return this.groupChatDataMapper.listTotalData(qdto);
    }

    @Override
    public void chatDataTimer(String params) {
        logger.info("群统计定时开始,params={}", params);
        if (StringUtils.isEmpty(params) || "-1".equals(params)) {
            List<TabHaobanWxEnterprise> wxEnterpriseList = this.wxEnterpriseMapper.listByIds(null);
            for (TabHaobanWxEnterprise item : wxEnterpriseList) {
                try {
                    this.getDataFormQw(item.getWxEnterpriseId());
                } catch (Exception e) {
                    logger.info("统计异常,wxeid={}", item.getWxEnterpriseId());
                    e.printStackTrace();
                }
            }
        } else {
            this.getDataFormQw(params);
        }
    }

    private void getDataFormQw(String wxEnterpriseId) {
        logger.info("群统计开始wxEnterpriseId={}", wxEnterpriseId);
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (null == qwDTO) {
            logger.info("企业不存在,id={}", wxEnterpriseId);
            return;
        }
        if (qwDTO.getWxSecurityType() == 0) {
            logger.info("wxSecurityType=0,不处理,id={}", wxEnterpriseId);
            return;
        }
        int pageNum = 0;
        List<GroupChatOwnerDTO> list = null;
        while (true) {
            list = this.groupChatOwnerMapper.listOwnerForStatistic(wxEnterpriseId, pageNum * pageSize, pageSize);
            if (CollectionUtils.isEmpty(list)) {
                logger.info("无群主记录,不处理,wxeid={}", wxEnterpriseId);
                break;
            }
            pageNum++;
            List<String> userIdList = null;
            Map<String, String> staffIdMap = new HashMap<>();
            if (qwDTO.needOpenUserId3th()) {
                userIdList = list.stream().map(dto -> dto.getWxOpenUserId()).collect(Collectors.toList());
                staffIdMap = list.stream().collect(Collectors.toMap(GroupChatOwnerDTO::getWxOpenUserId,
                        GroupChatOwnerDTO::getStaffId, (k1, k2) -> k1));
            } else {
                userIdList = list.stream().map(dto -> dto.getWxUserId()).collect(Collectors.toList());
                staffIdMap = list.stream().collect(Collectors.toMap(GroupChatOwnerDTO::getWxUserId,
                        GroupChatOwnerDTO::getStaffId, (k1, k2) -> k1));
            }

            Date date = DateUtil.addDay(DateUtil.getStartTimeOfDay(), -1);
            Long time = date.getTime() / 1000;
            ServiceResponse<List<GroupChatQwDataDTO>> resp = this.qywxChatApiService.statistic(qwDTO.getThirdCorpid(),
                    config.getWxSuiteid(), userIdList, time, time);
            List<GroupChatQwDataDTO> dataList = resp.getResult();
            if (CollectionUtils.isEmpty(dataList)) {
                if (list.size() < pageSize) {
                    break;
                }
                continue;
            }
            List<TabGroupChatData> addList = new ArrayList<>();
            for (GroupChatQwDataDTO dto : dataList) {
                String userId = dto.getOwner();
                if (StringUtils.isEmpty(staffIdMap.get(userId))) {
                    continue;
                }
                GroupChatQwDataItemDTO item = dto.getData();
                TabGroupChatData entity = new TabGroupChatData();
                entity.setDataId(UniqueIdUtils.uniqueLong());
                entity.setDate(date);
                entity.setWxEnterpriseId(wxEnterpriseId);
                entity.setStaffId(staffIdMap.get(userId));
                entity.setMsgTotal(item.getMsg_total());
                entity.setChatHasMsg(item.getChat_has_msg());
                entity.setChatTotal(item.getChat_total());
                entity.setNewChatCnt(item.getNew_chat_cnt());
                entity.setMigrateTraineeChatCnt(item.getMigrate_trainee_chat_cnt());
                entity.setMemberHasMsg(item.getMember_has_msg());
                entity.setMemberTotal(item.getMember_total());
                entity.setNewMemberCnt(item.getNew_member_cnt());
                addList.add(entity);
            }
            if (CollectionUtils.isNotEmpty(addList)) {
                this.groupChatDataMapper.batchInsert(addList);
            }
            if (list.size() < pageSize) {
                break;
            }
        }
    }
}