package com.ruoyi.excel.wecom.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.excel.wecom.domain.CustomerContactData;
import com.ruoyi.excel.wecom.domain.CustomerStatisticsData;
import com.ruoyi.excel.wecom.mapper.CustomerContactDataMapper;
import com.ruoyi.excel.wecom.mapper.CustomerStatisticsDataMapper;
import com.ruoyi.excel.wecom.vo.CustomerStatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 企业微信统计数据服务类
 */
@Service
public class WecomStatisticsService {

    @Autowired
    private CustomerStatisticsDataMapper customerStatisticsDataMapper;

    @Autowired
    private CustomerContactDataMapper customerContactDataMapper;

    /**
     * 处理并存储联系客户统计数据
     *
     * @param date 日期
     * @param statisticsData 统计数据
     * @return 处理成功的数量
     */
    public int handleAndSaveCustomerStatistics(String corpId,String date, JSONObject statisticsData) {
        if (statisticsData == null || !statisticsData.containsKey("behavior_data")) {
            return 0;
        }

        JSONArray behaviorDataArray = statisticsData.getJSONArray("behavior_data");
        if (behaviorDataArray == null || behaviorDataArray.isEmpty()) {
            return 0;
        }

        int successCount = 0;

        try {
            Date curDate = new java.text.SimpleDateFormat("yyyy-MM-dd").parse(date);

            for (int i = 0; i < behaviorDataArray.size(); i++) {
                JSONObject behaviorData = behaviorDataArray.getJSONObject(i);
                String userid = behaviorData.getString("userid");
                JSONObject data = behaviorData.getJSONObject("data");

                // 处理每个统计指标
                successCount += handleStatisticsIndicators(corpId,curDate, userid, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("处理联系客户统计数据失败: " + e.getMessage());
        }

        return successCount;
    }

    /**
     * 处理统计指标并保存到数据库
     *
     * @param curDate 当前日期
     * @param userid 成员ID
     * @param data 统计数据
     * @return 处理成功的数量
     */
    private int handleStatisticsIndicators(String corpId,Date curDate, String userid, JSONObject data) {
        int successCount = 0;

        // 处理各项统计指标
        // 这里需要根据实际的指标名称进行映射
        // 示例：处理新增客户数
        if (data.containsKey("new_contact_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "新增客户数", userid, data.getInteger("new_contact_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        // 处理聊天次数
        if (data.containsKey("chat_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "聊天次数", userid, data.getInteger("chat_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        // 处理发送消息数
        if (data.containsKey("msg_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "发送消息数", userid, data.getInteger("msg_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        // 处理语音通话时长（秒）
        if (data.containsKey("voice_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "语音通话时长（秒）", userid, data.getInteger("voice_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        // 处理视频通话时长（秒）
        if (data.containsKey("video_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "视频通话时长（秒）", userid, data.getInteger("video_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        // 处理拜访次数
        if (data.containsKey("visit_cnt")) {
            CustomerStatisticsData statisticsData = createCustomerStatisticsData(corpId,curDate, "拜访次数", userid, data.getInteger("visit_cnt"));
            customerStatisticsDataMapper.insert(statisticsData);
            successCount++;
        }

        return successCount;
    }

    /**
     * 创建客户统计数据实体
     *
     * @param curDate 当前日期
     * @param indicatorName 指标名称
     * @param userid 成员ID
     * @param value 指标值
     * @return 客户统计数据实体
     */
    private CustomerStatisticsData createCustomerStatisticsData(String corpId,Date curDate, String indicatorName, String userid, Integer value) {
        CustomerStatisticsData statisticsData = new CustomerStatisticsData();
        statisticsData.setCurDate(curDate);
        statisticsData.setCorpId(corpId);
        statisticsData.setIndicatorName(indicatorName);
        
        // 这里需要根据userid映射到对应的部门组
        // 示例：暂时将所有数据存储到N组
        statisticsData.setNtfGroup(value != null ? value.toString() : "0");
        
        // 其他组暂时设置为空
        statisticsData.setOfhGroup("");
        statisticsData.setPswGroup("");
        statisticsData.setWa1Group("");
        statisticsData.setXb1Group("");
        statisticsData.setYc1Group("");
        statisticsData.setZd1Group("");
        statisticsData.setAaGroup("");
        statisticsData.setAcGroup("");
        statisticsData.setAdGroup("");
        statisticsData.setAeGroup("");

        return statisticsData;
    }

    /**
     * 根据日期获取客户统计数据
     *
     * @param date 日期
     * @return 客户统计数据列表
     */
    public List<CustomerStatisticsVO> getCustomerStatisticsByDate(String corpId,Date date) {
        return customerStatisticsDataMapper.selectByDate(corpId,date);
    }

    /**
     * 处理并存储详细的客户联系统计数据
     *
     * @param statisticsData 统计数据
     * @return 处理成功的数量
     */
    public int handleAndSaveCustomerContactData(String corpId,JSONObject statisticsData) {
        if (statisticsData == null || !statisticsData.containsKey("behavior_data")) {
            return 0;
        }

        JSONArray behaviorDataArray = statisticsData.getJSONArray("behavior_data");
        if (behaviorDataArray == null || behaviorDataArray.isEmpty()) {
            return 0;
        }

        int successCount = 0;

        try {
            for (int i = 0; i < behaviorDataArray.size(); i++) {
                JSONObject behaviorData = behaviorDataArray.getJSONObject(i);
                String userid = behaviorData.getString("userid");
                JSONObject data = behaviorData.getJSONObject("data");

                // 处理每个成员的详细统计数据
                successCount += handleCustomerContactData(corpId,userid, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("处理客户联系统计数据失败: " + e.getMessage());
        }

        return successCount;
    }

    /**
     * 处理单个成员的客户联系统计数据
     *
     * @param userid 成员ID
     * @param data 统计数据
     * @return 处理成功的数量
     */
    private int handleCustomerContactData(String corpId,String userid, JSONObject data) {
        int successCount = 0;

        // 处理每个统计时间点的数据
        JSONArray statDataArray = data.getJSONArray("stat_data");
        if (statDataArray == null || statDataArray.isEmpty()) {
            return 0;
        }

        for (int i = 0; i < statDataArray.size(); i++) {
            JSONObject statData = statDataArray.getJSONObject(i);
            CustomerContactData contactData = createCustomerContactData(corpId,userid, statData);
            if (contactData != null) {
                customerContactDataMapper.insert(contactData);
                successCount++;
            }
        }

        return successCount;
    }

    /**
     * 创建客户联系统计数据实体
     *
     * @param userid 成员ID
     * @param statData 统计数据
     * @return 客户联系统计数据实体
     */
    private CustomerContactData createCustomerContactData(String corpId,String userid, JSONObject statData) {
        CustomerContactData contactData = new CustomerContactData();
        contactData.setCorpId(corpId);
        // 设置统计时间戳
        if (statData.containsKey("stat_time")) {
            contactData.setStatTime(statData.getLong("stat_time"));
            // 根据时间戳设置统计日期
            Date statDate = new Date(statData.getLong("stat_time") * 1000);
            contactData.setStatDate(statDate);
        }
        
        // 设置聊天次数
        if (statData.containsKey("chat_cnt")) {
            contactData.setChatCnt(statData.getInteger("chat_cnt"));
        }
        
        // 设置消息次数
        if (statData.containsKey("message_cnt")) {
            contactData.setMessageCnt(statData.getInteger("message_cnt"));
        }
        
        // 设置回复率
        if (statData.containsKey("reply_percentage")) {
            contactData.setReplyPercentage(statData.getDouble("reply_percentage"));
        }
        
        // 设置平均回复时间
        if (statData.containsKey("avg_reply_time")) {
            contactData.setAvgReplyTime(statData.getInteger("avg_reply_time"));
        }
        
        // 设置负面反馈次数
        if (statData.containsKey("negative_feedback_cnt")) {
            contactData.setNegativeFeedbackCnt(statData.getInteger("negative_feedback_cnt"));
        }
        
        // 设置新申请次数
        if (statData.containsKey("new_apply_cnt")) {
            contactData.setNewApplyCnt(statData.getInteger("new_apply_cnt"));
        }
        
        // 设置新联系次数
        if (statData.containsKey("new_contact_cnt")) {
            contactData.setNewContactCnt(statData.getInteger("new_contact_cnt"));
        }
        
        // 设置成员ID
        contactData.setUserid(userid);
        
        return contactData;
    }

    /**
     * 根据日期获取客户联系统计数据
     *
     * @param statDate 统计日期
     * @return 客户联系统计数据列表
     */
    public List<CustomerContactData> getCustomerContactDataByDate(String corpId,Date statDate) {
        return customerContactDataMapper.selectByStatDate(corpId,statDate);
    }

    /**
     * 根据成员ID和日期获取客户联系统计数据
     *
     * @param userid 成员ID
     * @param statDate 统计日期
     * @return 客户联系统计数据列表
     */
    public List<CustomerContactData> getCustomerContactDataByUseridAndDate(String corpId,String userid, Date statDate) {
        return customerContactDataMapper.selectByUseridAndStatDate(corpId,userid, statDate);
    }
}
