package com.example.cattletends.service.impl;

import com.example.cattletends.dto.ProvinceDataDTO;
import com.example.cattletends.entity.CattleProvince;
import com.example.cattletends.repository.CattleProvinceRepository;
import com.example.cattletends.service.CattleProvinceService;
import com.example.cattletends.service.CattleNationalService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 省份数据服务实现类
 */
@Service
public class CattleProvinceServiceImpl implements CattleProvinceService {

    private final CattleProvinceRepository cattleProvinceRepository;
    private final CattleNationalService cattleNationalService;

    /**
     * 构造器注入
     */
    public CattleProvinceServiceImpl(CattleProvinceRepository cattleProvinceRepository,
                                     CattleNationalService cattleNationalService) {
        this.cattleProvinceRepository = cattleProvinceRepository;
        this.cattleNationalService = cattleNationalService;
    }

    @Override
    @Transactional
    public Map<String, Object> importProvinceData(List<ProvinceDataDTO> provinceDataList) {
        if (provinceDataList == null || provinceDataList.isEmpty()) {
            throw new RuntimeException("省份数据列表不能为空");
        }
        
        int updateCount = 0;
        int createCount = 0;
        
        // 更新或创建各省份数据
        for (ProvinceDataDTO dto : provinceDataList) {
            if (dto == null || dto.getProvince() == null || dto.getProvince().trim().isEmpty()) {
                continue; // 跳过无效数据
            }
            // 查找该省份是否已存在
            CattleProvince provinceData = cattleProvinceRepository.findFirstByProvince(dto.getProvince())
                    .orElse(null);
            
            if (provinceData != null) {
                // 更新现有数据
                // 注意：不更新 provincePrice 字段，该字段只通过牛只数据导入时的计算得出
                provinceData.setProvincePriceRange(dto.getProvincePriceRange());
                provinceData.setInventory23th(dto.getInventory23th());
                provinceData.setSlaughter23th(dto.getSlaughter23th());
                provinceData.setInventory24th(dto.getInventory24th());
                provinceData.setSlaughter24th(dto.getSlaughter24th());
                provinceData.setInventory25th(dto.getInventory25th());
                provinceData.setSlaughter25th(dto.getSlaughter25th());
                cattleProvinceRepository.save(provinceData);
                updateCount++;
            } else {
                // 创建新数据
                provinceData = new CattleProvince();
                provinceData.setProvince(dto.getProvince());
                // 注意：不设置 provincePrice 字段，该字段只通过牛只数据导入时的计算得出
                provinceData.setProvincePriceRange(dto.getProvincePriceRange());
                provinceData.setInventory23th(dto.getInventory23th());
                provinceData.setSlaughter23th(dto.getSlaughter23th());
                provinceData.setInventory24th(dto.getInventory24th());
                provinceData.setSlaughter24th(dto.getSlaughter24th());
                provinceData.setInventory25th(dto.getInventory25th());
                provinceData.setSlaughter25th(dto.getSlaughter25th());
                cattleProvinceRepository.save(provinceData);
                createCount++;
            }
        }
        
        // 自动从 cattleprovince 表计算并更新全国总量数据（从数据库表中读取所有省份数据并求和）
        // 只更新 cattlenational 表，不更新 cattleData 表
        com.example.cattletends.entity.CattleNational nationalData = 
                cattleNationalService.calculateAndUpdateNationalData();
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("createCount", createCount);
        result.put("updateCount", updateCount);
        result.put("totalCount", createCount + updateCount);
        
        // 从全国总量数据中获取计算结果
        if (nationalData != null) {
            result.put("nationalInventory23th", nationalData.getNationalInventory23th());
            result.put("nationalSlaughter23th", nationalData.getNationalSlaughter23th());
            result.put("nationalInventory24th", nationalData.getNationalInventory24th());
            result.put("nationalSlaughter24th", nationalData.getNationalSlaughter24th());
            result.put("nationalInventory25th", nationalData.getNationalInventory25th());
            result.put("nationalSlaughter25th", nationalData.getNationalSlaughter25th());
        } else {
            result.put("nationalInventory23th", 0);
            result.put("nationalSlaughter23th", 0);
            result.put("nationalInventory24th", 0);
            result.put("nationalSlaughter24th", 0);
            result.put("nationalInventory25th", 0);
            result.put("nationalSlaughter25th", 0);
        }
        
        return result;
    }

    @Override
    @Transactional
    public List<CattleProvince> getAllProvinceData(String province) {
        // 按省份均价降序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "provincePrice");
        
        List<CattleProvince> dataList;
        
        // 如果提供了省份参数，则只查询该省份数据
        if (province != null && !province.trim().isEmpty()) {
            dataList = cattleProvinceRepository.findByProvince(province.trim(), sort);
        } else {
            // 否则返回所有省份数据，按省份均价降序排序
            dataList = cattleProvinceRepository.findAll(sort);
        }
        
        // 去重处理：如果同一个省份有多条记录，保留最新的一条（up_time最大），更新其他记录
        if (dataList != null && !dataList.isEmpty()) {
            System.out.println("========== 开始去重处理 ==========");
            System.out.println("去重前记录数: " + dataList.size());
            
            // 按省份分组，找出每个省份的最新记录
            java.util.Map<String, CattleProvince> provinceMap = new java.util.HashMap<>();
            java.util.List<CattleProvince> duplicatesToUpdate = new java.util.ArrayList<>();
            
            for (CattleProvince item : dataList) {
                String provinceName = item.getProvince();
                if (provinceName == null || provinceName.trim().isEmpty()) {
                    continue;
                }
                
                if (!provinceMap.containsKey(provinceName)) {
                    // 第一次遇到该省份，直接添加
                    provinceMap.put(provinceName, item);
                } else {
                    // 已存在该省份，比较更新时间，保留最新的
                    CattleProvince existing = provinceMap.get(provinceName);
                    if (item.getUpTime() != null && existing.getUpTime() != null) {
                        if (item.getUpTime().isAfter(existing.getUpTime())) {
                            // 当前记录更新，标记旧记录需要更新
                            duplicatesToUpdate.add(existing);
                            provinceMap.put(provinceName, item);
                        } else {
                            // 现有记录更新，标记当前记录需要更新
                            duplicatesToUpdate.add(item);
                        }
                    } else if (item.getUpTime() != null) {
                        // 当前记录有更新时间，保留它
                        duplicatesToUpdate.add(existing);
                        provinceMap.put(provinceName, item);
                    } else if (existing.getUpTime() != null) {
                        // 现有记录有更新时间，保留现有记录
                        duplicatesToUpdate.add(item);
                    } else {
                        // 都没有更新时间，保留ID较小的（通常是最早创建的）
                        if (item.getId() < existing.getId()) {
                            duplicatesToUpdate.add(existing);
                            provinceMap.put(provinceName, item);
                        } else {
                            duplicatesToUpdate.add(item);
                        }
                    }
                }
            }
            
            // 更新重复记录：将旧记录的数据更新为最新记录的数据
            int updatedCount = 0;
            for (CattleProvince duplicate : duplicatesToUpdate) {
                CattleProvince latest = provinceMap.get(duplicate.getProvince());
                if (latest != null && !latest.getId().equals(duplicate.getId())) {
                    // 更新旧记录的数据为最新记录的数据
                    duplicate.setProvincePrice(latest.getProvincePrice());
                    duplicate.setProvincePriceRange(latest.getProvincePriceRange());
                    duplicate.setInventory23th(latest.getInventory23th());
                    duplicate.setSlaughter23th(latest.getSlaughter23th());
                    duplicate.setInventory24th(latest.getInventory24th());
                    duplicate.setSlaughter24th(latest.getSlaughter24th());
                    duplicate.setInventory25th(latest.getInventory25th());
                    duplicate.setSlaughter25th(latest.getSlaughter25th());
                    cattleProvinceRepository.save(duplicate);
                    updatedCount++;
                }
            }
            
            // 如果更新了重复记录，重新查询
            if (updatedCount > 0) {
                System.out.println("更新了 " + updatedCount + " 条重复记录");
                if (province != null && !province.trim().isEmpty()) {
                    dataList = cattleProvinceRepository.findByProvince(province.trim(), sort);
                } else {
                    dataList = cattleProvinceRepository.findAll(sort);
                }
            }
            
            // 最终去重：按省份去重，每个省份只保留一条（保留最新的）
            java.util.Map<String, CattleProvince> finalMap = new java.util.LinkedHashMap<>();
            for (CattleProvince item : dataList) {
                String provinceName = item.getProvince();
                if (provinceName == null || provinceName.trim().isEmpty()) {
                    continue;
                }
                
                if (!finalMap.containsKey(provinceName)) {
                    finalMap.put(provinceName, item);
                } else {
                    CattleProvince existing = finalMap.get(provinceName);
                    if (item.getUpTime() != null && existing.getUpTime() != null) {
                        if (item.getUpTime().isAfter(existing.getUpTime())) {
                            finalMap.put(provinceName, item);
                        }
                    } else if (item.getUpTime() != null) {
                        finalMap.put(provinceName, item);
                    } else if (existing.getUpTime() != null) {
                        // 保持现有记录
                    } else {
                        // 都没有更新时间，保留ID较小的
                        if (item.getId() < existing.getId()) {
                            finalMap.put(provinceName, item);
                        }
                    }
                }
            }
            
            dataList = new java.util.ArrayList<>(finalMap.values());
            System.out.println("去重后记录数: " + dataList.size());
            System.out.println("========== 去重处理完成 ==========");
        }
        
        return dataList;
    }

    @Override
    @Transactional
    public CattleProvince getProvinceDataByName(String province) {
        // 查询该省份的所有记录
        List<CattleProvince> provinceList = cattleProvinceRepository.findAllByProvince(province);
        
        if (provinceList == null || provinceList.isEmpty()) {
            throw new RuntimeException("省份数据不存在：" + province);
        }
        
        // 如果有多条记录，进行去重处理
        if (provinceList.size() > 1) {
            System.out.println("========== 发现重复省份记录: " + province + " ==========");
            System.out.println("重复记录数: " + provinceList.size());
            
            // 找出最新的记录（up_time最大）
            CattleProvince latest = provinceList.get(0);
            for (CattleProvince item : provinceList) {
                if (item.getUpTime() != null && latest.getUpTime() != null) {
                    if (item.getUpTime().isAfter(latest.getUpTime())) {
                        latest = item;
                    }
                } else if (item.getUpTime() != null) {
                    latest = item;
                }
            }
            
            // 更新其他重复记录
            int updatedCount = 0;
            for (CattleProvince item : provinceList) {
                if (!item.getId().equals(latest.getId())) {
                    // 更新旧记录的数据为最新记录的数据
                    item.setProvincePrice(latest.getProvincePrice());
                    item.setProvincePriceRange(latest.getProvincePriceRange());
                    item.setInventory23th(latest.getInventory23th());
                    item.setSlaughter23th(latest.getSlaughter23th());
                    item.setInventory24th(latest.getInventory24th());
                    item.setSlaughter24th(latest.getSlaughter24th());
                    item.setInventory25th(latest.getInventory25th());
                    item.setSlaughter25th(latest.getSlaughter25th());
                    cattleProvinceRepository.save(item);
                    updatedCount++;
                }
            }
            
            if (updatedCount > 0) {
                System.out.println("更新了 " + updatedCount + " 条重复记录");
            }
            
            return latest;
        }
        
        // 只有一条记录，直接返回
        return provinceList.get(0);
    }
}
