package com.gic.haoban.manage.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DataApiUtils;
import com.gic.commons.util.DateUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.web.handle.*;
import com.gic.haoban.manage.web.qo.chat.*;
import com.gic.haoban.manage.web.qo.wechatwork.StoreGroupCommonQO;
import com.gic.haoban.manage.web.qo.wechatwork.WechatWorkLostClerkQO;
import com.gic.haoban.manage.web.qo.wechatwork.WechatWorkLostStoreGroupQO;
import com.gic.haoban.manage.web.utils.AuthorizedUserUtils;
import com.gic.haoban.manage.web.utils.data.ConcurrencyUtils;
import com.gic.haoban.manage.web.utils.data.MapThreadHandlerRequest;
import com.gic.haoban.manage.web.utils.data.StoreAuthUtils;
import com.gic.haoban.manage.web.vo.chat.*;
import com.gic.haoban.manage.web.vo.wechatwork.*;
import com.gic.qcloud.BucketNameEnum;
import com.gic.web.common.controller.NewBaseController;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会话数据统计
 * *
 * *
 *
 * @author shangfeng
 * @date 2024-06-19 10:58:42
 */
@Slf4j
@RestController
@RequestMapping("chat-data")
public class ChatDataController extends NewBaseController {

    @Autowired
    private StoreAuthUtils storeAuthUtils;

    @Autowired
    private GroupChatDetailsHandle groupChatDetailsHandle;

    @Autowired
    private GroupClerkDataHandle groupClerkDataHandle;

    @Autowired
    private GroupDetailsHandle groupDetailsHandle;

    @Autowired
    private GroupExitHandle groupExitHandle;

    @Autowired
    private GroupJoinHandle groupJoinHandle;

    @Autowired
    private GroupStoreDataHandle groupStoreDataHandle;

    @Autowired
    private SingleChatClerkDataHandle singleChatClerkDataHandle;

    @Autowired
    private SingleChatDetailsHandle singleChatDetailsHandle;

    @Autowired
    private SingleChatStoreDataHandle singleChatStoreDataHandle;

    /**
     * 单聊统计 会话数据概览
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("single-chat-overview")
    public RestResponse<SingleChatOverviewVO> singleChatOverview(@RequestBody SingleChatOverviewReq req) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(req);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO().setStoreGroupId(req.getStoreGroupId()));
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_chat_overview");
        List<JSONObject> list = DataApiUtils.getDataList(res);
        List<SingleChatOverviewVO> voList = JSONArray.parseArray(JSON.toJSONString(list), SingleChatOverviewVO.class);

        return RestResponse.successResult(CollectionUtils.isEmpty(voList) ? null : voList.get(0));

    }


    /**
     * 单聊统计 趋势图
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("single-chat-overview-trend")
    public RestResponse<List<SingleChatOverviewVO>> singleChatOverviewTrend(@RequestBody SingleChatOverviewReq req) throws ParseException {

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(req);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO().setStoreGroupId(req.getStoreGroupId()));

        List<MapThreadHandlerRequest> list = new ArrayList<>();
        jsonObject.put("groupType", 1);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "1_activeSessionsNum"));
        jsonObject.put("groupType", 2);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "2_custSessionsNum"));
        jsonObject.put("groupType", 3);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "3_replySessionsNum"));
        jsonObject.put("groupType", 4);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "4_replySessionsPrport"));
        jsonObject.put("groupType", 5);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "5_averageFirstReplyTime"));
        jsonObject.put("groupType", 6);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "6_sessionsCustNum"));
        jsonObject.put("groupType", 7);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "7_launchSessionsCustNum"));
        jsonObject.put("groupType", 8);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "8_launchSessionsSalesNum"));
        jsonObject.put("groupType", 9);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_chat_overview_date", "9_sendNewsNum"));

        Map<String, List<JSONObject>> map = ConcurrencyUtils.concurrencyDataForMap(list);
        List<JSONObject> resultList = new ArrayList<>();
        if (map != null) {
            map.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    for (JSONObject tempJson : v) {
                        tempJson.put(k.substring(0, 1), tempJson.get(k.substring(2)));
                    }
                    resultList.addAll(v);
                }
            });
        }
        Map<String, List<JSONObject>> voMap = resultList.stream().collect(Collectors.groupingBy(e -> e.getString("bizDate")));

        List<String> dateList = DateUtil.getBetweenDates(req.getStartDate(), req.getEndDate());
        List<SingleChatOverviewVO> voList = new ArrayList<>();
        for (String date : dateList) {
            SingleChatOverviewVO vo = new SingleChatOverviewVO();
            vo.setBizDate(date);
            List<JSONObject> mapValue = voMap.get(date);
            if (CollectionUtils.isNotEmpty(mapValue)) {
                for (JSONObject tempJson : mapValue) {
                    if (tempJson.containsKey("1")) {
                        vo.setActiveSessionsNum(tempJson.getInteger("1"));
                    }
                    if (tempJson.containsKey("2")) {
                        vo.setCustSessionsNum(tempJson.getInteger("2"));
                    }
                    if (tempJson.containsKey("3")) {
                        vo.setReplySessionsNum(tempJson.getInteger("3"));
                    }
                    if (tempJson.containsKey("4")) {
                        vo.setReplySessionsPrport(tempJson.getInteger("4"));
                    }
                    if (tempJson.containsKey("5")) {
                        vo.setAverageFirstReplyTime(tempJson.getInteger("5"));
                    }
                    if (tempJson.containsKey("6")) {
                        vo.setSessionsCustNum(tempJson.getInteger("6"));
                    }
                    if (tempJson.containsKey("7")) {
                        vo.setLaunchSessionsCustNum(tempJson.getInteger("7"));
                    }
                    if (tempJson.containsKey("8")) {
                        vo.setLaunchSessionsSalesNum(tempJson.getInteger("8"));
                    }
                    if (tempJson.containsKey("9")) {
                        vo.setSendNewsNum(tempJson.getInteger("9"));
                    }
                }
            }
            voList.add(vo);
        }

        return RestResponse.successResult(voList);


    }


    /**
     * 单聊统计 会话数据统计 门店维度
     *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("single-chat-store-data")
    public RestResponse<DataPageVO<SingleChatStoreGroupVO>> singleChatStoreData(@RequestBody SingleChatStoreGroupReq req) {
        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, req);
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_chat_count");
        jsonObject.put("groupType", 1);
        DataPageVO vo = storeAuthUtils.getDataCommon(jsonObject.toJSONString(), req.getPageNum(), "data_mbr_scale_haoban_qw_chat_count", req.getPageSize(), true);
        if (CollectionUtils.isNotEmpty(vo.getRows())) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(vo.getRows()), SingleChatStoreGroupVO.class));
        }
        return RestResponse.successResult(vo);

    }

    /**
     * 单聊统计 会话数据统计 导购维度
     *
     * 
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("single-chat-clerk-data")
    public RestResponse<DataPageVO<SingleChatClerkVO>> singleChatClerkData(@RequestBody SingleChatClerkReq req) {
        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("groupType", 2);
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_chat_count");

        Page page = DataApiUtils.getPageData(res);
        DataPageVO vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();

        vo.setTotalNum(page.getTotalCount());

        jsonObject.put("groupType", 1);
        jsonObject.put("storeGroup", 8);
        JSONObject total = storeAuthUtils.getTotalJson(jsonObject, "data_mbr_scale_haoban_qw_chat_count");
        if (list == null) {
            list = new ArrayList<>();
        }
        if (total != null) {
            total.put("clerkName", "合计（" + list.size() + "）");
            list.add(0, total);
        }
        vo.setRows(list);
        if (CollectionUtils.isNotEmpty(vo.getRows())) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(vo.getRows()), SingleChatClerkVO.class));
        }
        return RestResponse.successResult(vo);

    }


    /**
     * 单聊统计 会话数据统计 门店维度 数据导出
     *
     *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "export-single-chat-store-data")
    public RestResponse<Object> exportSingleChatStoreData(@RequestBody SingleChatStoreGroupReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.SINGLE_CHAT_STORE_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(singleChatStoreData(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, req);
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_chat_count");
        jsonObject.put("groupType", 1);
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();

        Integer storeGroup = jsonObject.getInteger("storeGroup");
        boolean isStore = storeGroup != null && storeGroup == 7;

        if (isStore) {
            indexList.add("门店名称");
            fieldList.add("storeName");
            indexList.add("门店code");
            fieldList.add("storeCode");
        } else {
            indexList.add("分组名称");
            fieldList.add("storeGroupName");
        }

        indexList.add("主动会话数");
        fieldList.add("activeSessionsNum");

        indexList.add("客户发起会话数");
        fieldList.add("custSessionsNum");

        indexList.add("会话总客户数");
        fieldList.add("sessionsCustNum");

        indexList.add("已回复会话数");
        fieldList.add("replySessionsNum");

        indexList.add("已回复会话占比");
        fieldList.add("replySessionsPrport");

        indexList.add("平均首次回复时长");
        fieldList.add("averageFirstReplyTime");

        indexList.add("企微好友数");
        fieldList.add("entWechatFdNum");

        indexList.add("会话总客户数");
        fieldList.add("sessionsCustNum");

        indexList.add("发起会话客户数");
        fieldList.add("launchSessionsCustNum");

        indexList.add("发起会话导购数");
        fieldList.add("launchSessionsSalesNum");

        indexList.add("发送消息数");
        fieldList.add("sendNewsNum");


        task.setFileName("好办单聊统计-门店维度-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-单聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(singleChatStoreDataHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }


    /**
     * 单聊统计 会话数据统计 导购维度 数据导出
     *
     *
     * 
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "export-single-chat-clerk-data")
    public RestResponse<Object> exportSingleChatClerkData(@RequestBody SingleChatClerkReq req) {
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.SINGLE_CHAT_CLERK_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(singleChatClerkData(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_chat_count");
        jsonObject.put("groupType", 2);
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("门店名称");
        fieldList.add("storeName");

        indexList.add("门店code");
        fieldList.add("storeCode");

        indexList.add("主动会话数");
        fieldList.add("activeSessionsNum");

        indexList.add("客户发起会话数");
        fieldList.add("custSessionsNum");

        indexList.add("会话总客户数");
        fieldList.add("sessionsCustNum");

        indexList.add("已回复会话数");
        fieldList.add("replySessionsNum");

        indexList.add("已回复会话占比");
        fieldList.add("replySessionsPrport");

        indexList.add("平均首次回复时长");
        fieldList.add("averageFirstReplyTime");

        indexList.add("企微好友数");
        fieldList.add("entWechatFdNum");

        indexList.add("会话总客户数");
        fieldList.add("sessionsCustNum");

        indexList.add("发起会话客户数");
        fieldList.add("launchSessionsCustNum");

        indexList.add("发送消息数");
        fieldList.add("sendNewsNum");

        task.setFileName("好办单聊统计-导购维度-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-单聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(singleChatClerkDataHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }


    /**
     * 单聊统计 会话数据详情
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("single-chat-details")
    public RestResponse<DataPageVO<SingleChatDetailVO>> singleChatDetails(@RequestBody SingleChatDetailReq req) {

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_chat_detail");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO<SingleChatDetailVO> vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            List<SingleChatDetailVO> voList = JSONArray.parseArray(JSON.toJSONString(list), SingleChatDetailVO.class);
            vo.setRows(voList);
        }
        vo.setTotalNum(page.getTotalCount());
        return RestResponse.successResult(vo);

    }


    /**
     * 单聊统计 会话数据详情 数据导出
     *
     * * *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("export-single-chat-details")
    public RestResponse<Object> exportSingleChatDetails(@RequestBody SingleChatDetailReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.SINGLE_CHAT_DETAIL_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(singleChatDetails(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_chat_detail");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("客户姓名");
        fieldList.add("memberName");

        indexList.add("客户昵称");
        fieldList.add("memberNick");

        indexList.add("客户手机号");
        fieldList.add("memberPhone");

        indexList.add("企微成员姓名");
        fieldList.add("staffName");

        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("导购所属门店名称");
        fieldList.add("storeName");

        indexList.add("导购所属门店code");
        fieldList.add("storeCode");

        indexList.add("会话发送人");
        fieldList.add("sendType");

        indexList.add("会话类型");
        fieldList.add("msgType");

        indexList.add("会话内容");
        fieldList.add("content");

        indexList.add("会话时间");
        fieldList.add("sendTime");

        task.setFileName( "好办单聊统计-会话明细-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-单聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(singleChatDetailsHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());


    }


    /**
     * 群聊统计 群数据概览
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-overview")
    public RestResponse<GroupChatOverviewVO> groupOverview(@RequestBody GroupChatOverviewReq req) {

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(req);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO().setStoreGroupId(req.getStoreGroupId()));
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_overview");
        List<JSONObject> list = DataApiUtils.getDataList(res);
        List<GroupChatOverviewVO> voList = JSONArray.parseArray(JSON.toJSONString(list), GroupChatOverviewVO.class);
        return RestResponse.successResult(CollectionUtils.isEmpty(voList) ? null : voList.get(0));
    }


    /**
     * 群聊统计 趋势图
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-overview-trend")
    public RestResponse<List<GroupChatOverviewVO>> groupOverviewTrend(@RequestBody GroupChatOverviewReq req) throws ParseException {

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(req);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO().setStoreGroupId(req.getStoreGroupId()));

        List<MapThreadHandlerRequest> list = new ArrayList<>();
        jsonObject.put("groupType", 1);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "1_newGroupNum"));
        jsonObject.put("groupType", 2);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "2_actGroupNum"));
        jsonObject.put("groupType", 3);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "3_groupCustNum"));
        jsonObject.put("groupType", 4);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "4_newGroupCustNum"));
        jsonObject.put("groupType", 5);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "5_actGroupCustNum"));
        jsonObject.put("groupType", 6);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "6_newExitGroupCustNum"));
        jsonObject.put("groupType", 7);
        list.add(new MapThreadHandlerRequest(jsonObject, "data_mbr_scale_haoban_qw_group_chat_date", "7_groupSessionsNum"));

        Map<String, List<JSONObject>> map = ConcurrencyUtils.concurrencyDataForMap(list);
        List<JSONObject> resultList = new ArrayList<>();
        if (map != null) {
            map.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    for (JSONObject tempJson : v) {
                        tempJson.put(k.substring(0, 1), tempJson.get(k.substring(2)));
                    }
                    resultList.addAll(v);
                }
            });
        }
        Map<String, List<JSONObject>> voMap = resultList.stream().collect(Collectors.groupingBy(e -> e.getString("bizDate")));

        List<String> dateList = DateUtil.getBetweenDates(req.getStartDate(), req.getEndDate());
        List<GroupChatOverviewVO> voList = new ArrayList<>();
        for (String date : dateList) {
            GroupChatOverviewVO vo = new GroupChatOverviewVO();
            vo.setBizDate(date);
            List<JSONObject> mapValue = voMap.get(date);
            if (CollectionUtils.isNotEmpty(mapValue)) {
                for (JSONObject tempJson : mapValue) {
                    if (tempJson.containsKey("1")) {
                        vo.setNewGroupNum(tempJson.getInteger("1"));
                    }
                    if (tempJson.containsKey("2")) {
                        vo.setActGroupNum(tempJson.getInteger("2"));
                    }
                    if (tempJson.containsKey("3")) {
                        vo.setGroupCustNum(tempJson.getInteger("3"));
                    }
                    if (tempJson.containsKey("4")) {
                        vo.setNewGroupCustNum(tempJson.getInteger("4"));
                    }
                    if (tempJson.containsKey("5")) {
                        vo.setActGroupCustNum(tempJson.getInteger("5"));
                    }
                    if (tempJson.containsKey("6")) {
                        vo.setNewExitGroupCustNum(tempJson.getInteger("6"));
                    }
                    if (tempJson.containsKey("7")) {
                        vo.setGroupSessionsNum(tempJson.getInteger("7"));
                    }
                }
            }
            voList.add(vo);
        }
        return RestResponse.successResult(voList);
    }


    /**
     * 群聊统计 群数据统计 门店维度
     *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-store-data")
    public RestResponse<DataPageVO<GroupChatStoreGroupVO>> groupStoreData(@RequestBody GroupChatStoreGroupReq req) {

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, req);
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_count");
        jsonObject.put("groupType", 1);
        DataPageVO vo = storeAuthUtils.getDataCommon(jsonObject.toJSONString(), req.getPageNum(), "data_mbr_scale_haoban_background_loss_statisti", req.getPageSize(), true);
        if (CollectionUtils.isNotEmpty(vo.getRows())) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(vo.getRows()), WechatWorkLostStoreGroupVO.class));
        }
        return RestResponse.successResult(vo);
        
    }

    /**
     * 群聊统计 群数据统计 导购维度
     *
     * 
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-clerk-data")
    public RestResponse<DataPageVO<GroupChatClerkVO>> groupClerkData(@RequestBody GroupChatClerkReq req) {

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("groupType", 2);
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_count");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();

        vo.setTotalNum(page.getTotalCount());

        jsonObject.put("groupType", 1);
        jsonObject.put("storeGroup", 8);
        JSONObject total = storeAuthUtils.getTotalJson(jsonObject, "data_mbr_scale_haoban_qw_group_chat_count");
        if (list == null) {
            list = new ArrayList<>();
        }
        if (total != null) {
            total.put("clerkName", "合计（" + list.size() + "）");
            list.add(0, total);
        }
        vo.setRows(list);
        if (CollectionUtils.isNotEmpty(vo.getRows())) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(vo.getRows()), GroupChatClerkVO.class));
        }
        return RestResponse.successResult(vo);

    }


    /**
     * 群聊统计 群数据统计 门店维度 数据导出
     *
     *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "export-group-store-data")
    public RestResponse<Object> exportGroupStoreData(@RequestBody GroupChatStoreGroupReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_STORE_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(groupStoreData(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, req);
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_count");
        jsonObject.put("groupType", 1);
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();

        Integer storeGroup = jsonObject.getInteger("storeGroup");
        boolean isStore = storeGroup != null && storeGroup == 7;

        if (isStore) {
            indexList.add("门店名称");
            fieldList.add("storeName");
            indexList.add("门店code");
            fieldList.add("storeCode");
        } else {
            indexList.add("分组名称");
            fieldList.add("storeGroupName");
        }

        indexList.add("上级分组");
        fieldList.add("parentStoreGroupName");

        indexList.add("群总数");
        fieldList.add("groupNum");

        indexList.add("新增群数");
        fieldList.add("newGroupNum");

        indexList.add("活跃群数");
        fieldList.add("actGroupNum");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");

        task.setFileName("好办群聊统计-门店维度-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupStoreDataHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }


    /**
     * 群聊统计 群数据统计 导购维度 数据导出
     *
     *
     * 
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "export-group-clerk-data")
    public RestResponse<Object> exportGroupClerkData(@RequestBody GroupChatClerkReq req) {
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_CLERK_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(groupClerkData(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_count");
        jsonObject.put("groupType", 2);
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("门店名称");
        fieldList.add("storeName");

        indexList.add("门店code");
        fieldList.add("storeCode");

        indexList.add("群总数");
        fieldList.add("groupNum");

        indexList.add("新增群数");
        fieldList.add("newGroupNum");

        indexList.add("活跃群数");
        fieldList.add("actGroupNum");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");

        task.setFileName("好办群聊统计-导购维度-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupClerkDataHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }


    /**
     * 群聊统计 群数据明细
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-data-details")
    public RestResponse<DataPageVO<GroupChatDetailVO>> groupDataDetails(@RequestBody GroupChatDetailReq req) {

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_detail");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO<GroupChatDetailVO> vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            List<GroupChatDetailVO> voList = JSONArray.parseArray(JSON.toJSONString(list), GroupChatDetailVO.class);
            vo.setRows(voList);
        }
        vo.setTotalNum(page.getTotalCount());
        return RestResponse.successResult(vo);

    }


    /**
     * 群聊统计 群数据明细 数据导出
     *
     * * *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("export-group-data-details")
    public RestResponse<Object> exportGroupDataDetails(@RequestBody GroupChatDetailReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_DETAIL_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(groupDataDetails(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_detail");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("群名称");
        fieldList.add("groupChatName");

        indexList.add("群ID");
        fieldList.add("groupChatId");

        indexList.add("群主姓名");
        fieldList.add("staffName");

        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("导购所属门店名称");
        fieldList.add("storeName");

        indexList.add("导购所属门店code");
        fieldList.add("storeCode");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");


        task.setFileName( "好办群聊统计-群数据明细-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupDetailsHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }


    /**
     * 群聊统计 入群明细
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("join-group-details")
    public RestResponse<DataPageVO<GroupChatJoinDetailVO>> joinGroupDetails(@RequestBody GroupChatJoinDetailReq req) {
        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_join");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO<GroupChatJoinDetailVO> vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            List<GroupChatJoinDetailVO> voList = JSONArray.parseArray(JSON.toJSONString(list), GroupChatJoinDetailVO.class);
            vo.setRows(voList);
        }
        vo.setTotalNum(page.getTotalCount());
        return RestResponse.successResult(vo);

    }


    /**
     * 群聊统计 入群明细 数据导出
     *
     * * *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("export-join-group-details")
    public RestResponse<Object> exportJoinGroupDetails(@RequestBody GroupChatDetailReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_JOIN_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(groupDataDetails(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_join");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("群名称");
        fieldList.add("groupChatName");

        indexList.add("群ID");
        fieldList.add("groupChatId");

        indexList.add("群主姓名");
        fieldList.add("staffName");

        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("导购所属门店名称");
        fieldList.add("storeName");

        indexList.add("导购所属门店code");
        fieldList.add("storeCode");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");


        task.setFileName( "好办群聊统计-群数据明细-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupJoinHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);

        return RestResponse.successResult(downloadTask.getResult());

    }


    /**
     * 群聊统计 退群明细
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("exit-group-details")
    public RestResponse<DataPageVO<GroupChatExitDetailVO>> exitGroupDetails(@RequestBody GroupChatExitDetailReq req) {

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_exit");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO<GroupChatExitDetailVO> vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            List<GroupChatExitDetailVO> voList = JSONArray.parseArray(JSON.toJSONString(list), GroupChatExitDetailVO.class);
            vo.setRows(voList);
        }
        vo.setTotalNum(page.getTotalCount());
        return RestResponse.successResult(vo);

    }


    /**
     * 群聊统计 退群明细 数据导出
     *
     * * *
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("export-exit-group-details")
    public RestResponse<Object> exportExitGroupDetails(@RequestBody GroupChatExitDetailReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_EXIT_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(exitGroupDetails(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_exit");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("群名称");
        fieldList.add("groupChatName");

        indexList.add("群ID");
        fieldList.add("groupChatId");

        indexList.add("群主姓名");
        fieldList.add("staffName");

        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("导购所属门店名称");
        fieldList.add("storeName");

        indexList.add("导购所属门店code");
        fieldList.add("storeCode");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");


        task.setFileName( "好办群聊统计-群数据明细-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupExitHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);

        return RestResponse.successResult(downloadTask.getResult());


    }


    /**
     * 群聊统计 会话明细
     * *
     *
     * @param req
     * @return
     */
    @RequestMapping("group-chat-details")
    public RestResponse<DataPageVO<GroupChatChatDetailVO>> groupChatDetails(@RequestBody GroupChatChatDetailReq  req) {
        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mbr_scale_haoban_qw_group_chat_con_detail");
        Page page = DataApiUtils.getPageData(res);
        DataPageVO<GroupChatChatDetailVO> vo = new DataPageVO();
        vo.setPageSize(page.getPageSize());
        vo.setPageNum(page.getCurrentPage());

        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            List<GroupChatChatDetailVO> voList = JSONArray.parseArray(JSON.toJSONString(list), GroupChatChatDetailVO.class);
            vo.setRows(voList);
        }
        vo.setTotalNum(page.getTotalCount());
        return RestResponse.successResult(vo);
    }


    /**
     * 群聊统计 会话明细 数据导出
     *
     *
     *
     *
     * @param req
     * @return
     */
    @RequestMapping("/export-group-chat-details")
    public RestResponse<Object> exportGroupChatDetails(@RequestBody GroupChatChatDetailReq req) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.GROUP_CHAT_CHAT_DATE);
        task.setDataType(req.getDataType());
        task.setUser(getUserInfo());

        task.setTotalCount(groupChatDetails(req).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        req.dealWithParam(jsonObject);
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO());
        jsonObject.put("apolloKey", "data_mbr_scale_haoban_qw_group_chat_con_detail");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        indexList.add("群名称");
        fieldList.add("groupChatName");

        indexList.add("群ID");
        fieldList.add("groupChatId");

        indexList.add("群主姓名");
        fieldList.add("staffName");

        indexList.add("导购姓名");
        fieldList.add("clerkName");

        indexList.add("导购code");
        fieldList.add("clerkCode");

        indexList.add("导购所属门店名称");
        fieldList.add("storeName");

        indexList.add("导购所属门店code");
        fieldList.add("storeCode");

        indexList.add("群总人数");
        fieldList.add("groupCustNum");

        indexList.add("新增群人数");
        fieldList.add("newGroupCustNum");

        indexList.add("活跃群人数");
        fieldList.add("actGroupCustNum");

        indexList.add("新退群人数");
        fieldList.add("newExitGroupCustNum");

        indexList.add("群会话总条数");
        fieldList.add("groupSessionsNum");


        task.setFileName( "好办群聊统计-群数据明细-" + req.getStartDate() + "_" + req.getEndDate());
        task.setChannelName("数据-会话数据-群聊统计");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(groupChatDetailsHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);

        return RestResponse.successResult(downloadTask.getResult());

    }


    private AuthorizedUser getUserInfo() {
        return AuthorizedUserUtils.getUserInfo();
    }

}
