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

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.JSONResponse;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.web.handle.WechatWorkOverviewStoreGroupHandle;
import com.gic.haoban.manage.web.qo.wechatwork.StoreGroupCommonQO;
import com.gic.haoban.manage.web.qo.wechatwork.WechatWorkOverviewQO;
import com.gic.haoban.manage.web.qo.wechatwork.WechatWorkOverviewStoreGroupQO;
import com.gic.haoban.manage.web.qo.wechatwork.WechatWorkOverviewTrendQO;
import com.gic.haoban.manage.web.utils.AuthorizedUserUtils;
import com.gic.haoban.manage.web.utils.data.DataApiQO;
import com.gic.haoban.manage.web.utils.data.StoreAuthUtils;
import com.gic.haoban.manage.web.vo.wechatwork.DataPageVO;
import com.gic.haoban.manage.web.vo.wechatwork.WechatWorkOverviewStoreGroupVO;
import com.gic.haoban.manage.web.vo.wechatwork.WechatWorkOverviewTrendVO;
import com.gic.haoban.manage.web.vo.wechatwork.WechatWorkOverviewVO;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 企微概览
 * @Author guojx
 * @Date 2024/7/23 10:45
 */
@RestController
@Slf4j
@RequestMapping("wechat-work-overview")
public class WechatWorkOverviewController extends NewBaseController {
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private WechatWorkOverviewStoreGroupHandle wechatWorkOverviewStoreGroupHandle;

    /**
     * 概览
     * @param qo
     * @return
     */
    @RequestMapping(value = "overview")
    public RestResponse<WechatWorkOverviewVO> overview(@RequestBody WechatWorkOverviewQO qo) {
        List<WechatWorkOverviewVO> voList = storeAuthUtils.getOverview(
                "data_mbr_scale_haoban_background_overview",
                new JSONObject(),
                new StoreGroupCommonQO().setStoreGroupId(qo.getStoreGroupId()),
                WechatWorkOverviewVO.class);
        return RestResponse.successResult(CollectionUtils.isEmpty(voList) ? null : voList.get(0));
    }

    /**
     * 趋势图
     * @param qo
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "trend")
    public RestResponse<List<WechatWorkOverviewTrendVO>> trend(@RequestBody WechatWorkOverviewTrendQO qo) throws ParseException {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        //1：总数 2：日期趋势
        jsonObject.put("groupType", 2);
        List<WechatWorkOverviewTrendVO> list = storeAuthUtils.getOverview(
                "data_mbr_scale_haoban_background_overview_date",
                jsonObject,
                new StoreGroupCommonQO().setStoreGroupId(qo.getStoreGroupId()),
                WechatWorkOverviewTrendVO.class);
        Map<String, WechatWorkOverviewTrendVO> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            map = list.stream().collect(Collectors.toMap(e -> e.getBizDate(), e -> e));
        }

        List<WechatWorkOverviewTrendVO> voList = new ArrayList<>();
        List<String> dateList = DateUtil.getBetweenDates(qo.getStartDate(), qo.getEndDate());
        for (String date : dateList) {
            WechatWorkOverviewTrendVO vo = map.get(date);
            if (vo == null) {
                vo = new WechatWorkOverviewTrendVO();
                vo.setBizDate(date);
            }
            voList.add(vo);
        }

        return RestResponse.successResult(voList);
    }

    /**
     * 新增概览数据
     * @param qo
     * @return
     */
    @RequestMapping(value = "new-overview")
    public RestResponse<WechatWorkOverviewTrendVO> newOverview(@RequestBody WechatWorkOverviewTrendQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        //1：总数 2：日期趋势
        jsonObject.put("groupType", 1);
        List<WechatWorkOverviewTrendVO> voList = storeAuthUtils.getOverview(
                "data_mbr_scale_haoban_background_overview_date",
                jsonObject,
                new StoreGroupCommonQO().setStoreGroupId(qo.getStoreGroupId()),
                WechatWorkOverviewTrendVO.class);
        return RestResponse.successResult(CollectionUtils.isEmpty(voList) ? null : voList.get(0));
    }

    /**
     * 门店分组
     * @param qo
     * @return
     */
    @RequestMapping(value = "store-group")
    public RestResponse<DataPageVO<WechatWorkOverviewStoreGroupVO>> storeGroup(@RequestBody WechatWorkOverviewStoreGroupQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        return RestResponse.successResult(storeAuthUtils.getData(new DataApiQO()
                .setPageSize(qo.getPageSize())
                .setCurrentPage(qo.getPageNum())
                .setNoTotal(false)
                .setHasCountPerPage(true)
                .setClazz(WechatWorkOverviewStoreGroupVO.class)
                .setJsonObject(jsonObject)
                .setStoreGroupCommonQO(qo)
                .setApolloKey(qo.getQueryDataType() == 1 ? "data_mbr_scale_haoban_background_count" : "data_mbr_scale_haoban_background_count_new")
        ));
    }

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

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

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

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        storeAuthUtils.setStoreGroupJsonParam(jsonObject, qo);

        boolean isTotalQuery = qo.getQueryDataType() == 1;
        jsonObject.put("apolloKey", isTotalQuery ? "data_mbr_scale_haoban_background_count" : "data_mbr_scale_haoban_background_count_new");
        //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");


        if (isTotalQuery) {
            indexList.add("企微好友总数（去重）");
            fieldList.add("newEntwchFdNum");
            indexList.add("企微好友总数");
            fieldList.add("entwchFdNumTotal");
            indexList.add("已注册会员好友数");
            fieldList.add("entwchFdNumMbr");
            indexList.add("未注册会员好友数");
            fieldList.add("entwchFdNumNonmbr");
        } else {
            indexList.add("新增企微好友数");
            fieldList.add("newEntwchFdNumTotal");
            indexList.add("新增已注册会员好友数");
            fieldList.add("newEntwchFdNumMbr");
            indexList.add("新增未注册会员好友数");
            fieldList.add("newEntwchFdNumNonmbr");
        }


        if (isTotalQuery) {
            task.setFileName("企微概览-门店维度总数数据");
        } else {
            task.setFileName("企微概览-门店维度新增数据-" + qo.getStartDate() + "_" + qo.getEndDate());
        }
        task.setChannelName("数据-企微数据-企微概览");
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        jsonObject.put("indexList", indexList);
        jsonObject.put("fieldList", fieldList);
        task.setSearchDataParams(jsonObject.toJSONString());
        task.setHandler(wechatWorkOverviewStoreGroupHandle);
        JSONResponse downloadTask = DownloadTaskUtil.createDownloadTask(task);
        return RestResponse.successResult(downloadTask.getResult());
    }

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

}
