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.commons.util.DataApiUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.web.handle.WechatEventTrackingClerkDetailHandle;
import com.gic.haoban.manage.web.handle.WechatEventTrackingStoreGroupHandle;
import com.gic.haoban.manage.web.qo.eventtracking.WechatEventTrackingClerkDetailQO;
import com.gic.haoban.manage.web.qo.eventtracking.WechatEventTrackingStoreGroupQO;
import com.gic.haoban.manage.web.qo.eventtracking.WechatOverviewQO;
import com.gic.haoban.manage.web.qo.wechatwork.StoreGroupCommonQO;
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.utils.eventtracking.DateExpandUtils;
import com.gic.haoban.manage.web.vo.eventtracking.TrendVO;
import com.gic.haoban.manage.web.vo.eventtracking.ViewModuleVO;
import com.gic.haoban.manage.web.vo.eventtracking.WechatEventTrackingClerkVO;
import com.gic.haoban.manage.web.vo.eventtracking.WechatEventTrackingStoreGroupVO;
import com.gic.haoban.manage.web.vo.wechatwork.DataPageVO;
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.apache.commons.lang3.StringUtils;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 好办小程序埋点分析
 * @Author guojx
 * @Date 2024/5/30 9:06
 */
@RestController
@Slf4j
@RequestMapping("wechat-event-tracking")
public class EventTrackingController extends NewBaseController {
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private WechatEventTrackingStoreGroupHandle wechatEventTrackingStoreGroupHandle;
    @Autowired
    private WechatEventTrackingClerkDetailHandle wechatEventTrackingClerkDetailHandle;

    /**
     * 概览
     * @param qo
     * @return
     */
    @RequestMapping(value = "overview")
    public RestResponse overview(@RequestBody WechatOverviewQO qo) {
        Map<String, Object> res = DataApiUtils.http(getOverviewParam(qo).toJSONString(), "data_point_anal_hb_app_overview");
        List<JSONObject> list = DataApiUtils.getDataList(res);
        return RestResponse.successResult(CollectionUtils.isEmpty(list) ? null : list.get(0));
    }

    /**
     * 趋势图
     * @param qo
     * @return
     */
    @RequestMapping(value = "trend")
    public RestResponse<List<TrendVO>> trend(@RequestBody WechatOverviewQO qo) {
        Map<String, Object> res = DataApiUtils.http(getOverviewParam(qo).toJSONString(), "data_point_anal_hb_app_trend");
        List<JSONObject> list = DataApiUtils.getDataList(res);
        Map<String, JSONObject> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            map = list.stream().collect(Collectors.toMap(e ->e.getString("bizDate"), e -> e));
        }
        //日期补零
        List<String> dateList = DateExpandUtils.getDateList(qo.getStartDate(), qo.getEndDate(), qo.getDateType());

        List<TrendVO> voList = new ArrayList<>();
        for (String date : dateList) {
            TrendVO vo = null;
            JSONObject temp = map.get(date);
            if (temp == null) {
                vo = new TrendVO();
            } else {
                vo = JSONObject.parseObject(temp.toJSONString(), TrendVO.class);
            }
            vo.setBizDate(date);
            voList.add(vo);
        }
        return RestResponse.successResult(voList);
    }

    /**
     * 模块访问统计
     * @param qo
     * @return
     */
    @RequestMapping(value = "view-module")
    public RestResponse<List<ViewModuleVO>> viewModule(@RequestBody WechatOverviewQO qo) {
        JSONObject jsonParam = getOverviewParam(qo);
        List<MapThreadHandlerRequest> list = new ArrayList<>();
        // 1 访问次数 2 访问人数 3 访问时长
        jsonParam.put("orderByField", 1);
        list.add(new MapThreadHandlerRequest(jsonParam, "data_point_anal_hb_app_module", "1_visitCnt"));
        jsonParam.put("orderByField", 2);
        list.add(new MapThreadHandlerRequest(jsonParam, "data_point_anal_hb_app_module", "2_visitNum"));
        jsonParam.put("orderByField", 3);
        list.add(new MapThreadHandlerRequest(jsonParam, "data_point_anal_hb_app_module", "3_visitTime"));

        Map<String, List<JSONObject>> map = ConcurrencyUtils.concurrencyDataForMap(list);

        List<ViewModuleVO> voList = new ArrayList<>();
        if (map != null && map.size() > 0) {
            map.forEach((k,v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    String dataType = k.substring(0, 1);
                    String key = k.substring(2);
                    List<ViewModuleVO> tempList = new ArrayList<>();
                    for (JSONObject temp : v) {
                        ViewModuleVO vo = JSON.parseObject(temp.toJSONString(), ViewModuleVO.class);
                        vo.setDataType(Integer.parseInt(dataType));
                        vo.setData(temp.getLong(key));
                        tempList.add(vo);
                    }
                    voList.addAll(tempList);
                }
            });
        }
        return RestResponse.successResult(voList);
    }

    /**
     * 门店分组下钻
     * @param qo
     * @return
     */
    @RequestMapping(value = "store-group")
    public RestResponse<DataPageVO<WechatEventTrackingStoreGroupVO>> storeGroup(@RequestBody WechatEventTrackingStoreGroupQO qo) {
        JSONObject jsonObject = new JSONObject();
        qo.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, qo);
        jsonObject.put("apolloKey", "data_point_anal_hb_app_store");
        DataPageVO vo = storeAuthUtils.getDataCommon(jsonObject.toJSONString(), qo.getPageNum(), "data_point_anal_hb_app_store", qo.getPageSize(), true);
        storeAuthUtils.deleteTotalData(vo);
        if (CollectionUtils.isNotEmpty(vo.getRows())) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(vo.getRows()), WechatEventTrackingStoreGroupVO.class));
        }
        return RestResponse.successResult(vo);
    }

    /**
     * 门店明细导出
     * @param qo
     * @return
     */
    @RequestMapping(value = "export-store-group")
    public RestResponse exportStoreGroup(@RequestBody WechatEventTrackingStoreGroupQO qo) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.HAOBAN_WECHAT_EVENT_STORE);
        task.setDataType(qo.getDataType());
        task.setUser(AuthorizedUserUtils.getUserInfo());

        task.setTotalCount(storeGroup(qo).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        qo.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, qo);
        jsonObject.put("apolloKey", "data_point_anal_hb_app_store");
        //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("clerkNum");
        indexList.add("绑定人数");
        fieldList.add("bindingNum");
        indexList.add("绑定率");
        fieldList.add("bindingRate");
        indexList.add("活跃人数");
        fieldList.add("visitNum");
        indexList.add("活跃率");
        fieldList.add("visitRate");


        task.setFileName( "门店明细数据-" + qo.getStartDate() + (StringUtils.isNotBlank(qo.getEndDate()) ?  "_" + qo.getEndDate() : ""));
        task.setChannelName("数据-登录数据-好办使用详情");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(wechatEventTrackingStoreGroupHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }

    /**
     * 导购明细
     * @param qo
     * @return
     */
    @RequestMapping(value = "clerk")
    public RestResponse<DataPageVO<WechatEventTrackingClerkVO>> clerk(@RequestBody WechatEventTrackingClerkDetailQO qo) {
        JSONObject jsonObject = new JSONObject();
        qo.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, new StoreGroupCommonQO()
                .setStoreGroupId(qo.getStoreGroupId()).setStoreId(qo.getStoreId()));

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_point_anal_hb_app_clerk");
        DataPageVO<WechatEventTrackingClerkVO> vo = new DataPageVO<>();
        Page page = DataApiUtils.getPageData(res);
        vo.setTotalNum(page.getTotalCount());
        vo.setPageNum(page.getCurrentPage());
        vo.setPageSize(page.getPageSize());
        List<JSONObject> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            vo.setRows(JSONArray.parseArray(JSON.toJSONString(list), WechatEventTrackingClerkVO.class));
        }
        return RestResponse.successResult(vo);
    }

    /**
     * 查询分组下的门店，即无归属门店
     * @param storeGroupId
     * @return
     */
    @RequestMapping(value = "get-unaffiliated-store")
    public RestResponse<List<String>> getUnaffiliatedStoreByStoreGroupId(String storeGroupId) {
        return RestResponse.successResult(storeAuthUtils.getUnaffiliatedStoreByStoreGroupId(storeGroupId));
    }

    /**
     * 导购明细导出
     * @param qo
     * @return
     */
    @RequestMapping(value = "export-clerk")
    public RestResponse exportClerk(@RequestBody WechatEventTrackingClerkDetailQO qo) {

        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.HAOBAN_WECHAT_EVENT_CLERK);
        task.setDataType(qo.getDataType());
        task.setUser(AuthorizedUserUtils.getUserInfo());

        task.setTotalCount(clerk(qo).getResult().getTotalNum());

        JSONObject jsonObject = new JSONObject();
        qo.dealWithParam(jsonObject);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, new StoreGroupCommonQO()
                .setStoreGroupId(qo.getStoreGroupId()).setStoreId(qo.getStoreId()));
        jsonObject.put("apolloKey", "data_point_anal_hb_app_clerk");
        //Excel的标题是字段进行计算
        List<String> indexList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();

        indexList.add("导购code");
        fieldList.add("clerkCode");
        indexList.add("导购名称");
        fieldList.add("clerkName");
        indexList.add("归属门店名称");
        fieldList.add("storeName");
        indexList.add("归属门店code");
        fieldList.add("storeCode");

        indexList.add("是否绑定");
        fieldList.add("isBinding");
        indexList.add("是否登陆");
        fieldList.add("isLogin");
        indexList.add("登陆次数");
        fieldList.add("visitCnt");
        indexList.add("日均访问时长");
        fieldList.add("visitTimeStr");
        indexList.add("最近一次登陆时间");
        fieldList.add("lastVisitTime");


        task.setFileName("导购明细数据-" + qo.getStartDate() + (StringUtils.isNotBlank(qo.getEndDate()) ? "_" + qo.getEndDate() : ""));
        task.setChannelName("数据-登录数据-好办使用详情");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(wechatEventTrackingClerkDetailHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }

    private JSONObject getOverviewParam(WechatOverviewQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        jsonObject.remove("storeGroupId");
        jsonObject.remove("storeId");
        storeAuthUtils.setCommonParam(jsonObject, new StoreGroupCommonQO().setStoreGroupId(qo.getStoreGroupId()).setStoreId(qo.getStoreId()));
        return jsonObject;
    }
}
