package com.storlead.sales.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.storlead.message.service.impl.MessageService;
import com.storlead.sales.pojo.vo.report.BroadcastCompanyVO;
import com.storlead.sales.pojo.vo.report.BroadcastDataVO;
import com.storlead.sales.pojo.vo.report.BroadcastPersonVO;
import com.storlead.sales.pojo.vo.report.BroadcastTotalMessageVO;
import com.storlead.sales.service.BroadcastMessageService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class BroadcastMessageServiceImpl implements BroadcastMessageService {

    @Resource
    private MessageService messageService;

    @Override
    public void sendCompanyDataReportMessages(Integer type, String messageEventCode, Set<Long> toUserIds, BroadcastCompanyVO companyVO) {
        BroadcastTotalMessageVO vo = new BroadcastTotalMessageVO();
        vo.setBroadcastCustomerDates(companyVO.getBroadcastCustomerDates());
        vo.setBroadcastBusinessDates(companyVO.getBroadcastBusinessDates());
        vo.setBroadcastOrderDates(companyVO.getBroadcastOrderDates());
        vo.setBroadcastOrderAmountDates(companyVO.getBroadcastOrderAmountDates());
        vo.setTotalCustomerNum(companyVO.getTotalCustomerNum());
        vo.setTotalOrderAmount(companyVO.getTotalOrderAmount());
        vo.setTotalBusinessNum(companyVO.getTotalBusinessNum());
        vo.setTotalOrderNum(companyVO.getTotalOrderNum());
        vo.setRecordTime(companyVO.getRecordTime());
        vo.setRecordRangeTime(companyVO.getRecordRangeTime());
        vo.setType(resolveCycleName(type));
        vo.setCompanyName(companyVO.getCompanyName());
        Map<String,Object> messageMap = BeanUtil.beanToMap(vo);

        // 格式化列表数据为字符串列表
        formatBroadcastDataList(messageMap, "broadcastCustomerDates", false, vo.getTotalCustomerNum());
        formatBroadcastDataList(messageMap, "broadcastBusinessDates", false, vo.getTotalBusinessNum());
        formatBroadcastDataList(messageMap, "broadcastOrderDates", false, vo.getTotalOrderNum());
        formatBroadcastDataList(messageMap, "broadcastOrderAmountDates", true, vo.getTotalOrderAmount());

        messageService.autoMatchEventSendMessage(messageMap,"200",messageEventCode,toUserIds,"wecom");
    }

    @Override
    public void sendBranchDataReportMessages(Integer type,String messageEventCode, Set<Long> toUserIds,BroadcastCompanyVO companyVO) {
        BroadcastTotalMessageVO vo = new BroadcastTotalMessageVO();
        vo.setBroadcastCustomerDates(companyVO.getBroadcastCustomerDates());
        vo.setBroadcastBusinessDates(companyVO.getBroadcastBusinessDates());
        vo.setBroadcastOrderDates(companyVO.getBroadcastOrderDates());
        vo.setBroadcastOrderAmountDates(companyVO.getBroadcastOrderAmountDates());
        vo.setTotalCustomerNum(companyVO.getTotalCustomerNum());
        vo.setTotalOrderAmount(companyVO.getTotalOrderAmount());
        vo.setTotalBusinessNum(companyVO.getTotalBusinessNum());
        vo.setTotalOrderNum(companyVO.getTotalOrderNum());
        vo.setRecordTime(companyVO.getRecordTime());
        vo.setRecordRangeTime(companyVO.getRecordRangeTime());
        vo.setType(resolveCycleName(type));
        vo.setCompanyName(companyVO.getCompanyName());
        Map<String,Object> messageMap = BeanUtil.beanToMap(vo);

        // 格式化列表数据为字符串列表
        formatBroadcastDataList(messageMap, "broadcastCustomerDates", false, vo.getTotalCustomerNum());
        formatBroadcastDataList(messageMap, "broadcastBusinessDates", false, vo.getTotalBusinessNum());
        formatBroadcastDataList(messageMap, "broadcastOrderDates", false, vo.getTotalOrderNum());
        formatBroadcastDataList(messageMap, "broadcastOrderAmountDates", true, vo.getTotalOrderAmount());

        messageService.autoMatchEventSendMessage(messageMap,"200",messageEventCode,toUserIds,"wecom");
    }

    @Override
    public void sendDeptDataReportMessages(Integer type, String messageEventCode, Set<Long> toUserIds, BroadcastPersonVO personVO) {
        BroadcastTotalMessageVO vo = new BroadcastTotalMessageVO();
        vo.setTotalCustomerNum(personVO.getTotalCustomerNum());
        vo.setTotalOrderAmount(personVO.getTotalOrderAmount());
        vo.setTotalBusinessNum(personVO.getTotalBusinessNum());
        vo.setTotalOrderNum(personVO.getTotalOrderNum());
        vo.setTotalClueNum(personVO.getTotalClueNum());
        vo.setTotalFollowNum(personVO.getTotalFollowNum());
        vo.setTotalEmailNum(personVO.getTotalEmailNum());
        vo.setRecordTime(personVO.getRecordTime());
        vo.setRecordRangeTime(personVO.getRecordRangeTime());
        vo.setType(resolveCycleName(type));
        vo.setCompanyName(personVO.getCompanyName());
        vo.setDeptName(personVO.getDeptName());
        Map<String,Object> messageMap = BeanUtil.beanToMap(vo);
        messageService.autoMatchEventSendMessage(messageMap,"200",messageEventCode,toUserIds,"wecom");
    }

    @Override
    public void sendPersonalDataReportMessages(Integer type,String messageEventCode, Set<Long> toUserIds, BroadcastPersonVO personVO) {
        BroadcastTotalMessageVO vo = new BroadcastTotalMessageVO();
        vo.setTotalCustomerNum(personVO.getTotalCustomerNum());
        vo.setTotalOrderAmount(personVO.getTotalOrderAmount());
        vo.setTotalBusinessNum(personVO.getTotalBusinessNum());
        vo.setTotalOrderNum(personVO.getTotalOrderNum());
        vo.setTotalClueNum(personVO.getTotalClueNum());
        vo.setTotalFollowNum(personVO.getTotalFollowNum());
        vo.setTotalEmailNum(personVO.getTotalEmailNum());
        vo.setRecordTime(personVO.getRecordTime());
        vo.setRecordRangeTime(personVO.getRecordRangeTime());
        vo.setType(resolveCycleName(type));
        vo.setCompanyName(personVO.getCompanyName());
        vo.setDeptName(personVO.getDeptName());
        Map<String,Object> messageMap = BeanUtil.beanToMap(vo);
        messageService.autoMatchEventSendMessage(messageMap,"200",messageEventCode,toUserIds,"wecom");
    }

    /**
     * 将周期类型数字转换为名称
     */
    private String resolveCycleName(Integer type) {
        if (type == null) {
            return "";
        }
        switch (type) {
            case 10: return "周";
            case 20: return "月";
            case 30: return "季度";
            case 40: return "半年度";
            case 50: return "年度";
            default: return "";
        }
    }

    /**
     * 格式化BroadcastDataVO列表为字符串列表
     * @param messageMap 消息Map
     * @param fieldName 字段名称
     * @param isAmount 是否为金额类型（金额需要转换为万元单位）
     * @param total 总额，用于控制是否展示列表
     */
    private void formatBroadcastDataList(Map<String, Object> messageMap, String fieldName, boolean isAmount, BigDecimal total) {
        // 总额为空或为0，展示空列表以避免模板占位符原样输出
        if (total == null || BigDecimal.ZERO.compareTo(total) == 0) {
            messageMap.put(fieldName, new ArrayList<String>());
            return;
        }

        Object fieldValue = messageMap.get(fieldName);
        if (fieldValue == null) {
            messageMap.put(fieldName, new ArrayList<String>());
            return;
        }

        if (fieldValue instanceof List) {
            @SuppressWarnings("unchecked")
            List<Object> list = (List<Object>) fieldValue;
            if (CollectionUtils.isEmpty(list)) {
                messageMap.put(fieldName, new ArrayList<String>());
                return;
            }

            List<String> formattedList = new ArrayList<>();
            for (Object item : list) {
                if (item instanceof BroadcastDataVO) {
                    BroadcastDataVO dataVO = (BroadcastDataVO) item;
                    String formatted = formatBroadcastDataVO(dataVO, isAmount);
                    if (formatted != null && !formatted.isEmpty()) {
                        formattedList.add(formatted);
                    }
                } else if (item instanceof Map) {
                    // 处理BeanUtil转换后的Map格式
                    @SuppressWarnings("unchecked")
                    Map<String, Object> itemMap = (Map<String, Object>) item;
                    String organization = itemMap.get("organization") != null ? itemMap.get("organization").toString() : "";
                    Object totalNumObj = itemMap.get("totalNum");
                    BigDecimal totalNum = null;
                    if (totalNumObj instanceof BigDecimal) {
                        totalNum = (BigDecimal) totalNumObj;
                    } else if (totalNumObj != null) {
                        try {
                            totalNum = new BigDecimal(totalNumObj.toString());
                        } catch (Exception e) {
                            // 忽略转换错误
                        }
                    }

                    if (totalNum != null) {
                        BroadcastDataVO dataVO = new BroadcastDataVO();
                        dataVO.setOrganization(organization);
                        dataVO.setTotalNum(totalNum);
                        String formatted = formatBroadcastDataVO(dataVO, isAmount);
                        if (formatted != null && !formatted.isEmpty()) {
                            formattedList.add(formatted);
                        }
                    }
                }
            }
            messageMap.put(fieldName, formattedList);
        }
    }

    /**
     * 格式化单个BroadcastDataVO为字符串
     * @param dataVO 数据VO
     * @param isAmount 是否为金额类型
     * @return 格式化后的字符串，格式：组织名称:数值
     */
    private String formatBroadcastDataVO(BroadcastDataVO dataVO, boolean isAmount) {
        if (dataVO == null || dataVO.getOrganization() == null || dataVO.getOrganization().isEmpty()) {
            return null;
        }

        BigDecimal totalNum = dataVO.getTotalNum();
        if (totalNum == null) {
            totalNum = BigDecimal.ZERO;
        }

        String formattedValue;
        if (isAmount) {
            // 金额转换为万元，保留2位小数
            BigDecimal amountInWan = totalNum.divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP);
            formattedValue = amountInWan.toString() + "万元";
        } else {
            // 其他数据直接显示整数
            formattedValue = totalNum.setScale(0, RoundingMode.HALF_UP).toString();
        }

        return dataVO.getOrganization() + ":" + formattedValue;
    }
}
