package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.TimeUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.qw.domain.QwGroupchatStatistic;
import com.fs.qw.mapper.QwGroupchatStatisticMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwGroupchatStatisticParams;
import com.fs.qw.param.QwUserListParam;
import com.fs.qw.service.IQwGroupchatStatisticService;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwGroupchatStatisticVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.qwApi.Result.QwGroupChatStatisticResult;
import com.fs.qwApi.param.QwGroupChatStatisticParam;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企微群聊数据统计数据Service业务层处理
 *
 * @author qw
 * @date 2024-08-05
 */
@Service
public class QwGroupchatStatisticServiceImpl implements IQwGroupchatStatisticService
{
    @Autowired
    private QwGroupchatStatisticMapper qwGroupchatStatisticMapper;


    @Autowired
    private ICompanyUserService userService;


    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwApiService qwApiService;


    /**
     * 查询企微群聊数据统计数据
     *
     * @param id 企微群聊数据统计数据主键
     * @return 企微群聊数据统计数据
     */
    @Override
    public QwGroupchatStatistic selectQwGroupchatStatisticById(Long id)
    {
        return qwGroupchatStatisticMapper.selectQwGroupchatStatisticById(id);
    }

    /**
     * 查询企微群聊数据统计数据列表
     *
     * @param params 企微群聊数据统计数据
     * @return 企微群聊数据统计数据
     */
    @Override
    public R selectQwGroupchatStatisticList(QwGroupchatStatisticParams params)
    {
        if(StringUtils.isNotEmpty(params.getUserIds())){
            String[] userIds=params.getUserIds().split(",");
            params.setUsers(Arrays.asList(userIds));
        }
        else{
            //获取部门下的所有用户
            CompanyUser usermap=new CompanyUser();
            usermap.setDeptId(params.getDeptId());
            usermap.setCompanyId(params.getCompanyid());
            List<CompanyUserQwVO> userQwVOS = userService.getUserListByDeptIdToQwUserid(usermap);
            List<String> userIds = userQwVOS.stream().map(element -> element.getQwId().trim()).collect(Collectors.toList());
            ArrayList<String> id = new ArrayList<>();
            for (String userId : userIds) {
                String[] split = userId.split(",");
                for (String s : split) {
                    id.add(s);
                }
            }
            params.setUsers(id);
        }

        if(params.getUsers()!=null&&params.getUsers().size()>0){


            List<QwGroupchatStatisticVO> qwGroupchatStatisticVOS = qwGroupchatStatisticMapper.selectQwGroupchatStatisticListVO(params);

            TimeUtils.TimeEntity timeEntity= TimeUtils.parseTime(params.getType().toString(),params.getStartTime(),params.getEndTime());

            timeEntity.setCompanyId(params.getCompanyid());

            Integer cycleNum = timeEntity.getCycleNum();
            Integer beginTime = timeEntity.getBeginTime();
            List<Integer> timeList = new ArrayList<>();
            for (int i = 1; i <= cycleNum; i++) {
                timeList.add(beginTime);
                beginTime = TimeUtils.formatTime(beginTime);
            }

            List<JSONObject> jsonObjectList = qwGroupchatStatisticMapper.selectQwGroupchatStatisticListVOCount(timeEntity.toMap(),params.getUsers());

            return R.ok().put("list",qwGroupchatStatisticVOS).put("charts",jsonObjectList);
        }
        else {
            return R.ok("未查找到数据");
        }
    }

    /**
     * 新增企微群聊数据统计数据
     *
     * @param qwGroupchatStatistic 企微群聊数据统计数据
     * @return 结果
     */
    @Override
    public int insertQwGroupchatStatistic(QwGroupchatStatistic qwGroupchatStatistic)
    {
        return qwGroupchatStatisticMapper.insertQwGroupchatStatistic(qwGroupchatStatistic);
    }

    /**
     * 修改企微群聊数据统计数据
     *
     * @param qwGroupchatStatistic 企微群聊数据统计数据
     * @return 结果
     */
    @Override
    public int updateQwGroupchatStatistic(QwGroupchatStatistic qwGroupchatStatistic)
    {
        return qwGroupchatStatisticMapper.updateQwGroupchatStatistic(qwGroupchatStatistic);
    }

    /**
     * 批量删除企微群聊数据统计数据
     *
     * @param ids 需要删除的企微群聊数据统计数据主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupchatStatisticByIds(Long[] ids)
    {
        return qwGroupchatStatisticMapper.deleteQwGroupchatStatisticByIds(ids);
    }

    /**
     * 删除企微群聊数据统计数据信息
     *
     * @param id 企微群聊数据统计数据主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupchatStatisticById(Long id)
    {
        return qwGroupchatStatisticMapper.deleteQwGroupchatStatisticById(id);
    }

    /**
     * 定时任务，每天定时从企业微信获取「联系客户统计」数据的更新数据
     */
    @Override
    public void updateQwGroupchatStatisticByTimer() {

        //复用 空的QwUserParam
        QwUserListParam qwUserParam=new QwUserListParam();


        //请求API参数
        QwGroupChatStatisticParam param= new QwGroupChatStatisticParam();

        QwGroupchatStatistic qwGroupchatStatistic = new QwGroupchatStatistic();

        // 获取当前时区的昨天的同一时间的时间戳
        long timestamp = ZonedDateTime.now().minusDays(1).toEpochSecond();

        param.setDay_begin_time(String.valueOf(timestamp));
        param.setDay_end_time(String.valueOf(timestamp));

        List<QwUserVO> list = qwUserMapper.selectQwUserListVO(qwUserParam);

        for (QwUserVO qwUserVO : list) {

            QwGroupChatStatisticParam.OwnerFilter ownerFilter = new QwGroupChatStatisticParam.OwnerFilter();
                ownerFilter.setUserid_list(Collections.singletonList(qwUserVO.getQwUserId()));

            param.setOwner_filter(ownerFilter);


            QwGroupChatStatisticResult groupChatStatistic = qwApiService.getGroupChatStatistic(param, qwUserVO.getCorpId());
            if (groupChatStatistic.getErrcode() == 0) {
                 groupChatStatistic.getItems().stream().forEach(item -> {

                     qwGroupchatStatistic.setOwner(qwUserVO.getQwUserId());
                     qwGroupchatStatistic.setDayTime(Long.valueOf(item.getStat_time()));
                     qwGroupchatStatistic.setNewChatCnt(Long.valueOf(item.getData().getNew_chat_cnt()));
                     qwGroupchatStatistic.setChatTotal(Long.valueOf(item.getData().getChat_total()));
                     qwGroupchatStatistic.setChatHasMsg(Long.valueOf(item.getData().getChat_has_msg()));
                     qwGroupchatStatistic.setNewMemberCnt(Long.valueOf(item.getData().getNew_member_cnt()));
                     qwGroupchatStatistic.setMemberTotal(Long.valueOf(item.getData().getMember_total()));
                     qwGroupchatStatistic.setMemberHasMsg(Long.valueOf(item.getData().getMember_has_msg()));
                     qwGroupchatStatistic.setMsgTotal(Long.valueOf(item.getData().getMsg_total()));
                     //qwGroupchatStatistic.setCompanyid(qwUserVO.getCompanyId());

                   qwGroupchatStatisticMapper.updateOrInsertQwGroupchatStatistic(qwGroupchatStatistic);

                 });


            }
        }

    }

    /**
     *  定时任务，每天定时从企业微信获取「联系客户统计」数据的更新数据 按群主聚合 (二选一)
     */
    @Override
    public void updateQwGroupchatStatisticByTimerOwner() {
        //复用 空的QwUserParam
        QwUserListParam qwUserParam=new QwUserListParam();
        List<QwUserVO> list = qwUserMapper.selectQwUserListVO(qwUserParam);

        int batchSize = 100;

        // 获取当前时区
        ZoneId zoneId = ZoneId.systemDefault();

        // 获取昨天的日期
        LocalDateTime yesterdayStart = LocalDateTime.now().minusDays(1).toLocalDate().atStartOfDay();

        // 获取时间戳（秒）
        long timestamp= ZonedDateTime.of(yesterdayStart, zoneId).toEpochSecond();

        //请求API参数
        QwGroupChatStatisticParam param= new QwGroupChatStatisticParam();


        QwGroupchatStatistic qwGroupchatStatistic = new QwGroupchatStatistic();


        Map<String, List<QwUserVO>> companyGroups = new HashMap<>();
        for (QwUserVO qwUserVO : list) {
            companyGroups.computeIfAbsent(String.valueOf(qwUserVO.getCorpId()), k -> new ArrayList<>()).add(qwUserVO);
        }

        //最多100个为一组list
        for (Map.Entry<String, List<QwUserVO>> entry : companyGroups.entrySet()) {
            List<QwUserVO> userList = entry.getValue();

            String corpId = entry.getKey();

            List<String> userIdBatch = new ArrayList<>();

            for (int i = 0; i < userList.size(); i++) {
                QwUserVO qwUserVO = userList.get(i);
                userIdBatch.add(qwUserVO.getQwUserId());

                if (userIdBatch.size() == batchSize || i == userList.size() - 1) {

                    QwGroupChatStatisticParam.OwnerFilter ownerFilter = new QwGroupChatStatisticParam.OwnerFilter();

                    ownerFilter.setUserid_list(new ArrayList<>(userIdBatch));

                    param.setOwner_filter(ownerFilter);
                    param.setDay_begin_time(String.valueOf(timestamp));
                    param.setDay_end_time(String.valueOf(timestamp));

                    QwGroupChatStatisticResult byOwner = qwApiService.getGroupChatStatisticByOwner(param, corpId);
                    if (byOwner.getErrcode()==0){
                        for (QwGroupChatStatisticResult.Item item : byOwner.getItems()) {

                            qwGroupchatStatistic.setOwner(item.getOwner());
                            qwGroupchatStatistic.setDayTime(Long.valueOf(item.getStat_time()));
                            qwGroupchatStatistic.setNewChatCnt(Long.valueOf(item.getData().getNew_chat_cnt()));
                            qwGroupchatStatistic.setChatTotal(Long.valueOf(item.getData().getChat_total()));
                            qwGroupchatStatistic.setChatHasMsg(Long.valueOf(item.getData().getChat_has_msg()));
                            qwGroupchatStatistic.setNewMemberCnt(Long.valueOf(item.getData().getNew_member_cnt()));
                            qwGroupchatStatistic.setMemberTotal(Long.valueOf(item.getData().getMember_total()));
                            qwGroupchatStatistic.setMemberHasMsg(Long.valueOf(item.getData().getMember_has_msg()));
                            qwGroupchatStatistic.setMsgTotal(Long.valueOf(item.getData().getMsg_total()));
                           // qwGroupchatStatistic.setCompanyid(qwUserVO.getCompanyId());

                            qwGroupchatStatisticMapper.updateOrInsertQwGroupchatStatistic(qwGroupchatStatistic);
                        }

                    }

                    userIdBatch.clear();
                }
            }
        }

    }
}
