package com.ruoyi.web.controller.wocom;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CorpContextHolder;
import com.ruoyi.excel.wecom.service.WecomContactService;
import com.ruoyi.excel.wecom.service.WecomStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 企业微信统计数据控制器
 */
@RestController
@RequestMapping("/api/wecom/statistics")
public class WecomStatisticsController {

    @Autowired
    private WecomContactService wecomContactService;

    @Autowired
    private WecomStatisticsService wecomStatisticsService;

    /**
     * 获取某一天的联系客户统计数据
     *
     * @param date 日期（格式：yyyy-MM-dd）
     * @param useridList 成员ID列表
     * @return 统计数据
     */
    @PostMapping("/customer/{date}")
    public AjaxResult getCustomerStatistics(@PathVariable("date") String date, @RequestParam(value = "useridList", required = false) List<String> useridList) {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();
            JSONObject statisticsData = wecomContactService.getDayUserBehaviorData(corpId,date, useridList);
            return AjaxResult.success("获取联系客户统计数据成功", statisticsData);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("获取联系客户统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取某一天的联系客户统计数据并存储到数据库
     *
     * @param date 日期（格式：yyyy-MM-dd）
     * @param useridList 成员ID列表
     * @return 处理结果
     */
    @PostMapping("/customer/{date}/save")
    public AjaxResult saveCustomerStatistics(@PathVariable("date") String date, @RequestParam(value = "useridList", required = false) List<String> useridList) {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();

            JSONObject statisticsData = wecomContactService.getDayUserBehaviorData(corpId,date, useridList);
            
            // 存储汇总统计数据
            int summaryCount = wecomStatisticsService.handleAndSaveCustomerStatistics(corpId,date, statisticsData);
            
            // 存储详细联系统计数据
            int contactCount = wecomStatisticsService.handleAndSaveCustomerContactData(corpId,statisticsData);
            
            return AjaxResult.success("获取并存储联系客户统计数据成功，共处理 " + summaryCount + " 条汇总数据，" + contactCount + " 条详细数据", statisticsData);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("获取联系客户统计数据失败: " + e.getMessage());
        }
    }
}
