package com.ruoyi.excel.wecom.service;

import com.ruoyi.excel.wecom.domain.*;
import com.ruoyi.excel.wecom.enums.AddWayEnum;
import com.ruoyi.excel.wecom.mapper.*;
import com.ruoyi.excel.wecom.model.WecomCustomer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户导出服务类
 */
@Service
public class CustomerExportService {

    @Autowired
    private CorpUserMapper corpUserMapper;

    @Autowired
    private CorpDepartmentMapper corpDepartmentMapper;

    @Autowired
    private WecomTagMapper wecomTagMapper;

    @Autowired
    private WecomTagGroupMapper wecomTagGroupMapper;

    @Autowired
    private CustomerExportDataMapper customerExportDataMapper;

    @Autowired
    private CustomerDataChangeTrackingService changeTrackingService;

    // 缓存映射
    private Map<String, CorpUser> userIdToUserMap = new HashMap<>();
    private Map<Long, String> departmentIdToNameMap = new HashMap<>();
    private Map<String, WecomTagDomain> tagIdToTagMap = new HashMap<>();
    private Map<String, WecomTagGroupDomain> tagGroupIdToGroupMap = new HashMap<>();
    private Map<String, List<WecomTagDomain>> tagGroupIdToTagsMap = new HashMap<>();

    /**
     * 初始化缓存数据
     * 在服务启动时自动执行
     */
    @PostConstruct
    public void initCache() {
        System.out.println("开始初始化缓存数据...");

        // 1. 加载用户数据
        List<CorpUser> userList = corpUserMapper.selectList(null);
        userIdToUserMap = userList.stream()
                .collect(Collectors.toMap(CorpUser::getUserid, user -> user, (v1, v2) -> v1));
        System.out.println("已加载 " + userIdToUserMap.size() + " 个用户");

        // 2. 加载部门数据
        List<CorpDepartment> departmentList = corpDepartmentMapper.selectList(null);
        departmentIdToNameMap = departmentList.stream()
                .collect(Collectors.toMap(CorpDepartment::getId, CorpDepartment::getName, (v1, v2) -> v1));
        System.out.println("已加载 " + departmentIdToNameMap.size() + " 个部门");

        // 3. 加载标签数据
        List<WecomTagDomain> tagList = wecomTagMapper.selectList(null);
        tagIdToTagMap = tagList.stream()
                .collect(Collectors.toMap(WecomTagDomain::getTagId, tag -> tag, (v1, v2) -> v1));
        System.out.println("已加载 " + tagIdToTagMap.size() + " 个标签");

        // 4. 加载标签组数据
        List<WecomTagGroupDomain> tagGroupList = wecomTagGroupMapper.selectList(null);
        tagGroupIdToGroupMap = tagGroupList.stream()
                .collect(Collectors.toMap(WecomTagGroupDomain::getTagGroupId, group -> group, (v1, v2) -> v1));
        System.out.println("已加载 " + tagGroupIdToGroupMap.size() + " 个标签组");

        // 5. 构建标签组到标签列表的映射
        for (WecomTagDomain tag : tagList) {
            String groupId = tag.getTagGroupId();
            tagGroupIdToTagsMap.computeIfAbsent(groupId, k -> new ArrayList<>()).add(tag);
        }

        System.out.println("缓存初始化完成！");
    }

    public List<Date> getAllDate() {
        return customerExportDataMapper.getDistinctDate();
    }
    /**
     * 处理客户数据并保存到数据库
     * 集成数据变更追踪功能：
     * 1. 检查数据是否发生变更（通过数据指纹）
     * 2. 如果数据变更，保存历史快照和变更日志
     * 3. 更新或插入当前数据
     *
     * @param customerList 客户列表
     * @return 处理成功的数量
     */
    public int handleData(List<WecomCustomer> customerList) {
        if (customerList == null || customerList.isEmpty()) {
            System.out.println("客户列表为空，无需处理");
            return 0;
        }

        int successCount = 0;
        int insertCount = 0;
        int updateCount = 0;
        int unchangedCount = 0;
        System.out.println("开始处理 " + customerList.size() + " 个客户数据...");

        for (WecomCustomer customer : customerList) {
            try {
                CustomerExportData exportData = convertToExportData(customer);
                if (exportData != null) {
                    // 根据唯一标识（客户名称+添加人账号+添加时间）查询是否已存在
                    CustomerExportData existingData = customerExportDataMapper.selectByUniqueKey(
                            exportData.getCustomerName(),
                            exportData.getAddUserAccount(),
                            exportData.getAddTime()
                    );

                    if (existingData == null) {
                        // 新增客户
                        customerExportDataMapper.insert(exportData);

                        // 保存新增记录到历史表
                        changeTrackingService.saveDataChange(exportData.getId(), exportData, "INSERT");

                        insertCount++;
                        successCount++;
                        System.out.println("新增客户: " + exportData.getCustomerName());
                    } else {
                        // 检查数据是否发生变更
                        boolean hasChanged = changeTrackingService.hasDataChanged(existingData.getId(), exportData);

                        if (hasChanged) {
                            // 数据已变更，更新数据库
                            exportData.setId(existingData.getId());
                            customerExportDataMapper.updateById(exportData);

                            // 保存变更记录到历史表和变更日志表
                            changeTrackingService.saveDataChange(existingData.getId(), exportData, "UPDATE");

                            updateCount++;
                            successCount++;
                            System.out.println("更新客户: " + exportData.getCustomerName() + " (数据已变更)");
                        } else {
                            // 数据未变更，跳过更新
                            unchangedCount++;
                            System.out.println("跳过客户: " + exportData.getCustomerName() + " (数据未变更)");
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("处理客户数据失败: " + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println("数据处理完成！");
        System.out.println("总计: " + customerList.size() + " 条");
        System.out.println("新增: " + insertCount + " 条");
        System.out.println("更新: " + updateCount + " 条");
        System.out.println("未变更: " + unchangedCount + " 条");
        System.out.println("成功: " + successCount + " 条");
        return successCount;
    }

    /**
     * 将企业微信客户数据转换为导出数据实体
     *
     * @param customer 企业微信客户数据
     * @return 导出数据实体
     */
    private CustomerExportData convertToExportData(WecomCustomer customer) {
        if (customer == null) {
            return null;
        }

        CustomerExportData exportData = new CustomerExportData();
        WecomCustomer.ExternalContact externalContact = customer.getExternalContact();
        //设置性别
        if(externalContact != null) {
            exportData.setGender(externalContact.getGender());
        }

        // 获取跟进信息
        WecomCustomer.FollowInfo followInfo = customer.getFollowInfo();
        if (followInfo != null) {
            exportData.setCustomerName(followInfo.getRemark());
            exportData.setDescription(followInfo.getDescription());
            // 添加人信息
            String userId = followInfo.getUserid();
            CorpUser user = userIdToUserMap.get(userId);
            if (user != null) {
                exportData.setAddUserName(user.getName());
                exportData.setAddUserAccount(user.getUserid());

                // 获取部门信息
                Long departId = user.getDepartId();
                if (departId != null) {
                    exportData.setAddUserDepartment(user.getDepartmentName());
                }
            }

            // 添加时间
            Long createTime = followInfo.getCreatetime();
            if (createTime != null) {
                exportData.setAddTime(new Date(createTime * 1000));
                exportData.setAddDate(new Date(createTime * 1000));
            }

            // 来源
            Integer addWay = followInfo.getAddWay();
            exportData.setSource(AddWayEnum.getDescriptionByCode(addWay));

            // 备注信息
            exportData.setMobile(followInfo.getRemarkMobiles() != null && !followInfo.getRemarkMobiles().isEmpty()
                    ? String.join(",", followInfo.getRemarkMobiles()) : null);
            exportData.setCompany(followInfo.getRemarkCorpName());

            // 处理标签 - 按标签组分类
            List<String> tagIds = followInfo.getTagId();
            if (tagIds != null && !tagIds.isEmpty()) {
                processCustomerTags(exportData, tagIds);
            }
        }


        return exportData;
    }

    /**
     * 处理客户标签，按标签组分类填充到对应字段
     *
     * @param exportData 导出数据实体
     * @param tagIds 标签ID列表
     */
    private void processCustomerTags(CustomerExportData exportData, List<String> tagIds) {
        // 按标签组分组
        Map<String, List<String>> groupedTags = new HashMap<>();

        for (String tagId : tagIds) {
            WecomTagDomain tag = tagIdToTagMap.get(tagId);
            if (tag != null) {
                String groupId = tag.getTagGroupId();
                groupedTags.computeIfAbsent(groupId, k -> new ArrayList<>()).add(tag.getName());
            }
        }

        // 将标签填充到对应的标签组字段
        for (Map.Entry<String, List<String>> entry : groupedTags.entrySet()) {
            String groupId = entry.getKey();
            String tagNames = String.join(",", entry.getValue());

            WecomTagGroupDomain tagGroup = tagGroupIdToGroupMap.get(groupId);
            if (tagGroup != null) {
                String groupName = tagGroup.getName();

                // 根据标签组名称填充到对应字段
                // 这里需要根据实际的标签组名称进行映射
                fillTagGroupField(exportData, groupName, tagNames);
            }
        }
    }

    /**
     * 根据标签组名称填充到对应的字段
     *
     * @param exportData 导出数据实体
     * @param groupName 标签组名称
     * @param tagNames 标签名称（逗号分隔）
     */
    private void fillTagGroupField(CustomerExportData exportData, String groupName, String tagNames) {
        // 根据标签组名称映射到对应字段
        // 这里的映射关系需要根据实际业务调整
        if (groupName.contains("投放")) {
            exportData.setTagGroup1(tagNames);
        } else if (groupName.contains("公司孵化")) {
            exportData.setTagGroup2(tagNames);
        } else if (groupName.contains("商务")) {
            exportData.setTagGroup3(tagNames);
        } else if (groupName.contains("成交日期")) {
            exportData.setTagGroup4(tagNames);
        } else if (groupName.contains("年级组")) {
            exportData.setTagGroup5(tagNames);
        } else if (groupName.contains("客户属性")) {
            exportData.setTagGroup6(tagNames);
        } else if (groupName.contains("成交") && !groupName.contains("日期") && !groupName.contains("品牌")) {
            exportData.setTagGroup7(tagNames);
        } else if (groupName.contains("成交品牌")) {
            exportData.setTagGroup8(tagNames);
        } else if (groupName.contains("线索通")) {
            exportData.setTagGroup9(tagNames);
        } else if (groupName.contains("A1")) {
            exportData.setTagGroup10(tagNames);
        } else if (groupName.contains("B1")) {
            exportData.setTagGroup11(tagNames);
        } else if (groupName.contains("C1")) {
            exportData.setTagGroup12(tagNames);
        } else if (groupName.contains("D1")) {
            exportData.setTagGroup13(tagNames);
        } else if (groupName.contains("E1")) {
            exportData.setTagGroup14(tagNames);
        } else if (groupName.contains("意向度")) {
            exportData.setTagGroup15(tagNames);
        } else if (groupName.contains("自然流")) {
            exportData.setTagGroup16(tagNames);
        } else if (groupName.contains("F1")) {
            exportData.setTagGroup17(tagNames);
        } else if (groupName.contains("G1")) {
            exportData.setTagGroup18(tagNames);
        }
    }

    /**
     * 手动刷新缓存
     */
    public void refreshCache() {
        initCache();
    }

    /**
     * 获取缓存统计信息
     *
     * @return 缓存统计信息
     */
    public Map<String, Integer> getCacheStats() {
        Map<String, Integer> stats = new HashMap<>();
        stats.put("users", userIdToUserMap.size());
        stats.put("departments", departmentIdToNameMap.size());
        stats.put("tags", tagIdToTagMap.size());
        stats.put("tagGroups", tagGroupIdToGroupMap.size());
        return stats;
    }


}
