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

import com.alibaba.fastjson.JSONObject;
import com.gic.haoban.manage.api.dto.CommonDataMQDTO;
import com.gic.haoban.manage.api.service.HaobanCommonMQApiService;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanExternalClerkRelatedMapper;
import com.gic.haoban.manage.service.dao.mapper.hm.WxUserAddLogMapper;
import com.gic.haoban.manage.service.entity.TabHaobanExternalClerkRelated;
import com.gic.haoban.manage.service.entity.hm.TabWxUserAddLog;
import com.gic.haoban.manage.service.service.*;
import com.gic.haoban.manage.service.service.chat.GroupChatDataService;
import com.gic.haoban.manage.service.util.DingUtils;
import com.gic.haoban.manage.service.util.HBQwMonitorUtils;
import com.gic.redis.data.util.RedisUtil;
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.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gic.api.base.commons.ServiceResponse;
import com.gic.haoban.manage.api.service.HaobanTimerApiService;
import com.gic.haoban.manage.service.service.chat.GroupChatService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeTempService;

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

@Service("haobanTimerApiService")
public class HaobanTimerApiServiceImpl implements HaobanTimerApiService {
    private static final Logger log = LogManager.getLogger(HaobanTimerApiService.class);

    @Autowired
    private HmQrcodeTempService hmQrcodeTempService;
    @Autowired
    private ExternalClerkRelatedService externalClerkRelatedService;
    @Autowired
    private StaffDepartmentRelatedService staffDepartmentRelatedService;
    @Autowired
    private GroupChatService groupChatService;
    @Autowired
    private ExternalMemberService externalMemberService ;
    @Autowired
    private GroupChatDataService groupChatDataService ;
    @Autowired
    private QywxErrorLogService qywxErrorLogService ;
    @Autowired
    private TabHaobanExternalClerkRelatedMapper  externalClerkRelatedMapper ;
    @Autowired
    private WxUserAddLogMapper wxUserAddLogMapper ;
    @Autowired
    private HaobanCommonMQApiService haobanCommonMQApiService ;
    @Autowired
    private OpenStaffService openStaffService ;
    

    @Override
    public ServiceResponse<Void> deleteTempWxHm(String params) {
        this.hmQrcodeTempService.deleteForTimer();
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> repairExternalUserId(String wxEnterpriseId) {
        this.externalClerkRelatedService.repairExternalUserId(wxEnterpriseId);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> repairStaffDepart(String params) {
        this.staffDepartmentRelatedService.repairAllStaffDepart(params);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> handChatNotice(String params) {
        this.groupChatService.handChatNotice(params);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> initGroupChat(String params) {
        this.groupChatService.initGroupChatForTimer(params);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> initHaobaonGroupChat(String params) {
        this.groupChatService.initHaobaonGroupChat(params);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> handleHmChatFull(String params) {
        this.groupChatService.handleHmChatFull(params);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> ownerDimission(String params) {
        this.groupChatService.ownerDimission();
        return ServiceResponse.success();
    }
    
    @Override
    public ServiceResponse<Void> welcomeForMember(String params) {
        this.externalMemberService.welcomeForMember() ;
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> groupChatQuitTimer(String params) {
        this.groupChatDataService.groupChatQuitTimer(params) ;
        return ServiceResponse.success();
    }

    @Override
    public void addFrientMonitorTimer(String params) {
        HBQwMonitorUtils.addByTimer();
    }

    @Override
    public void doErrorFriendTimer(String params) {
        this.qywxErrorLogService.doFriendTimer(params);
    }

    @Override
    public void halfTimer(String wxEnterpriseId) {
        log.info("开始单向数据={}",wxEnterpriseId);
        int pageSize = 1000 ;
        int pageNum = 0;
        RMap<String, String> mapCache = RedisUtil.getRedisClient().getMap("halfTimer_wxenterpriseId");
        while (true) {
            List<TabHaobanExternalClerkRelated> list = this.externalClerkRelatedMapper.halfDelFriendPage(wxEnterpriseId,pageNum*pageSize);
            List<String> idList =  new ArrayList<>() ;
            if(CollectionUtils.isNotEmpty(list)) {
                pageNum++;
                for(TabHaobanExternalClerkRelated dto : list) {
                    if(StringUtils.isNotBlank(dto.getExternalUserId())) {
                        idList.add(dto.getExternalUserId()) ;
                    }else {
                        this.externalClerkRelatedMapper.updateHalfTime(dto.getExternalClerkRelatedId(),dto.getUpdateTime());
                    }
                }
                if(CollectionUtils.isNotEmpty(idList)) {
                   List<TabWxUserAddLog> logList= this.wxUserAddLogMapper.listHalfDelTime(idList);
                    Map<String, Date> map = new HashMap<>() ;
                   if(CollectionUtils.isNotEmpty(logList)) {
                       map = logList.stream().collect(Collectors.toMap(TabWxUserAddLog::getExternalUserid, o -> o.getCreateTime(), (k1, k2) -> k1));
                   }
                   List<JSONObject> jsonList = new ArrayList<>() ;
                   for(TabHaobanExternalClerkRelated dto : list) {
                        JSONObject json = new JSONObject() ;
                       json.put("id",dto.getExternalClerkRelatedId()) ;
                       if(null != map.get(dto.getExternalUserId())) {
                            //this.externalClerkRelatedMapper.updateHalfTime(dto.getExternalClerkRelatedId(),map.get(dto.getExternalUserId()));
                            json.put("delTime",map.get(dto.getExternalUserId())) ;
                        }else {
                           // this.externalClerkRelatedMapper.updateHalfTime(dto.getExternalClerkRelatedId(),dto.getUpdateTime());
                           json.put("delTime",dto.getUpdateTime()) ;
                        }
                        jsonList.add(json) ;
                   }
                   CommonDataMQDTO data = new CommonDataMQDTO() ;
                   data.setType(1);
                   data.setParams(jsonList);
                   this.haobanCommonMQApiService.putDataMessage(data);
                }
            }else {
                break;
            }
        }
        mapCache.put(wxEnterpriseId,"1") ;
        DingUtils.send("halfTimer告警,wxEnterpriseId="+wxEnterpriseId, null, false);
        log.info("结束单向数据={}",wxEnterpriseId);
    }

    @Override
    public void openStaffTimer(String params) {
        this.openStaffService.openStaffTimer() ;
    }

    @Override
    public void openStaffServiceTimer(String params) {
        this.openStaffService.openStaffServiceTimer() ;
    }
}
