package com.chinaweal.aiccs.aiccs.abnormal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.CaseZfReport;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.CaseZfReportMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.CaseZfReportService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 行政处罚案件推送表 服务实现类
 * </p>
 *
 * @author lwd
 * @since 2025-10-29
 */
@Slf4j
@Service
public class CaseZfReportServiceImpl extends BaseServiceImpl<CaseZfReportMapper, CaseZfReport> implements CaseZfReportService {

    @Resource
    private CaseZfReportMapper caseZfReportMapper;

    @Override
    public IPage<CaseZfReport> queryCaseListWithPage(PageRequestDto pageRequestDto) {
        try {
            Page<CaseZfReport> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

            QueryWrapper<CaseZfReport> queryWrapper = new QueryWrapper<>();

            // 构建查询条件
            if (customParamMap != null) {
                // 单位名称
                if (customParamMap.containsKey("unitname") && StringUtils.hasText(customParamMap.get("unitname").toString())) {
                    queryWrapper.like("UNITNAME", customParamMap.get("unitname").toString());
                }

                // 统一社会信用代码
                if (customParamMap.containsKey("uniscid") && StringUtils.hasText(customParamMap.get("uniscid").toString())) {
                    queryWrapper.eq("UNISCID", customParamMap.get("uniscid").toString());
                }

                // 法定代表人
                if (customParamMap.containsKey("lerep") && StringUtils.hasText(customParamMap.get("lerep").toString())) {
                    queryWrapper.like("LEREP", customParamMap.get("lerep").toString());
                }

                // 案件编号
                if (customParamMap.containsKey("caseno") && StringUtils.hasText(customParamMap.get("caseno").toString())) {
                    queryWrapper.eq("CASENO", customParamMap.get("caseno").toString());
                }

                // 处罚决定日期范围
                if (customParamMap.containsKey("penDateStart") && StringUtils.hasText(customParamMap.get("penDateStart").toString())) {
                    queryWrapper.ge("PENDECISSDATE", customParamMap.get("penDateStart").toString());
                }
                if (customParamMap.containsKey("penDateEnd") && StringUtils.hasText(customParamMap.get("penDateEnd").toString())) {
                    queryWrapper.le("PENDECISSDATE", customParamMap.get("penDateEnd").toString());
                }

                // 处罚机关名称
                if (customParamMap.containsKey("penauthname") && StringUtils.hasText(customParamMap.get("penauthname").toString())) {
                    queryWrapper.like("PENAUTHNAME", customParamMap.get("penauthname").toString());
                }
            }

            queryWrapper.orderByDesc("PENDECISSDATE");

            return baseMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询行政处罚案件列表失败", e);
            throw new RuntimeException("查询行政处罚案件列表失败: " + e.getMessage());
        }
    }

    @Override
    public List<CaseZfReport> queryCaseListByCondition(Map<String, Object> customParamMap) {
        try {
            if (customParamMap == null) {
                customParamMap = new HashMap<>();
            }
            return caseZfReportMapper.queryCaseListByCondition(customParamMap);
        } catch (Exception e) {
            log.error("根据条件查询行政处罚案件失败", e);
            throw new RuntimeException("根据条件查询行政处罚案件失败: " + e.getMessage());
        }
    }

    @Override
    public List<CaseZfReport> queryCaseHistoryByPripid(String pripid) {
        try {
            if (!StringUtils.hasText(pripid)) {
                return new ArrayList<>();
            }
            return caseZfReportMapper.queryCaseHistoryByPripid(pripid);
        } catch (Exception e) {
            log.error("根据主体标识查询案件历史记录失败", e);
            throw new RuntimeException("根据主体标识查询案件历史记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<CaseZfReport> queryCaseByUniscid(String uniscid) {
        try {
            if (!StringUtils.hasText(uniscid)) {
                return new ArrayList<>();
            }
            return caseZfReportMapper.queryCaseByUniscid(uniscid);
        } catch (Exception e) {
            log.error("根据统一社会信用代码查询案件记录失败", e);
            throw new RuntimeException("根据统一社会信用代码查询案件记录失败: " + e.getMessage());
        }
    }

    @Override
    public CaseZfReport queryCaseDetailByCaseno(String caseno) {
        try {
            if (!StringUtils.hasText(caseno)) {
                return null;
            }
            return caseZfReportMapper.queryCaseDetailByCaseno(caseno);
        } catch (Exception e) {
            log.error("根据案件编号查询案件详情失败", e);
            throw new RuntimeException("根据案件编号查询案件详情失败: " + e.getMessage());
        }
    }

    @Override
    public int countCaseByDateRange(String startDate, String endDate) {
        try {
            if (!StringUtils.hasText(startDate) || !StringUtils.hasText(endDate)) {
                return 0;
            }
            return caseZfReportMapper.countCaseByDateRange(startDate, endDate);
        } catch (Exception e) {
            log.error("统计指定时间范围内的行政处罚案件数量失败", e);
            throw new RuntimeException("统计指定时间范围内的行政处罚案件数量失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePenResultById(String id, String penresult) {
        try {
            if (!StringUtils.hasText(id)) {
                return false;
            }
            int result = caseZfReportMapper.updatePenResultById(id, penresult);
            return result > 0;
        } catch (Exception e) {
            log.error("更新处罚结果失败", e);
            throw new RuntimeException("更新处罚结果失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCaseZfReport(CaseZfReport caseZfReport, AICUser aicUser) {
        try {
            if (caseZfReport == null) {
                return false;
            }

            // 设置创建人信息
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 验证必填字段
            if (!StringUtils.hasText(caseZfReport.getCaseno())) {
                throw new RuntimeException("案件编号不能为空");
            }
            if (!StringUtils.hasText(caseZfReport.getBizseq())) {
                throw new RuntimeException("业务序列编号不能为空");
            }

            // 检查案件编号是否已存在
            QueryWrapper<CaseZfReport> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("CASENO", caseZfReport.getCaseno());
            CaseZfReport existing = baseMapper.selectOne(checkWrapper);
            if (existing != null) {
                log.warn("案件编号 {} 已存在，跳过保存", caseZfReport.getCaseno());
                return false;
            }

            int result = baseMapper.insert(caseZfReport);

            return result > 0;
        } catch (Exception e) {
            log.error("保存行政处罚案件失败", e);
            throw new RuntimeException("保存行政处罚案件失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> batchImportCaseList(List<CaseZfReport> caseList, AICUser aicUser) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        List<String> failMessages = new ArrayList<>();

        try {
            if (caseList == null || caseList.isEmpty()) {
                result.put("success", false);
                result.put("message", "导入列表为空");
                return result;
            }

            for (int i = 0; i < caseList.size(); i++) {
                CaseZfReport caseZfReport = caseList.get(i);
                try {
                    if (saveCaseZfReport(caseZfReport, aicUser)) {
                        successCount++;
                    } else {
                        failCount++;
                        failMessages.add("第 " + (i + 1) + " 行: 案件编号 " + caseZfReport.getCaseno() + " 已存在或保存失败");
                    }
                } catch (Exception e) {
                    failCount++;
                    failMessages.add("第 " + (i + 1) + " 行: " + e.getMessage());
                    log.error("导入第{}行数据失败", i + 1, e);
                }
            }

            result.put("success", true);
            result.put("totalCount", caseList.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("failMessages", failMessages);
            result.put("message", "导入完成，成功" + successCount + "条，失败" + failCount + "条");


        } catch (Exception e) {
            log.error("批量导入行政处罚案件失败", e);
            result.put("success", false);
            result.put("message", "批量导入失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> statisticsCaseByAuth(Map<String, Object> customParamMap) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 根据处罚机关统计案件数量
            List<Map<String, Object>> statisticsList = new ArrayList<>();

            QueryWrapper<CaseZfReport> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("PENAUTHNAME as penAuthName", "COUNT(*) as caseCount");
            queryWrapper.groupBy("PENAUTHNAME");
            queryWrapper.orderByDesc("caseCount");

            // 添加时间范围条件
            if (customParamMap != null) {
                if (customParamMap.containsKey("startDate") && StringUtils.hasText(customParamMap.get("startDate").toString())) {
                    queryWrapper.ge("PENDECISSDATE", customParamMap.get("startDate").toString());
                }
                if (customParamMap.containsKey("endDate") && StringUtils.hasText(customParamMap.get("endDate").toString())) {
                    queryWrapper.le("PENDECISSDATE", customParamMap.get("endDate").toString());
                }
            }

            List<Map<String, Object>> statistics = baseMapper.selectMaps(queryWrapper);

            // 计算总数
            int totalCases = statistics.stream().mapToInt(map -> Integer.parseInt(map.get("caseCount").toString())).sum();

            result.put("statistics", statistics);
            result.put("totalCases", totalCases);
            result.put("authCount", statistics.size());

        } catch (Exception e) {
            log.error("根据办案机关统计案件数量失败", e);
            throw new RuntimeException("根据办案机关统计案件数量失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public List<CaseZfReport> querycasereportview() {
        return baseMapper.querycasereportview();
    }

    @Override
    public List<CaseZfReport> queryCaseListWithOffset(int offset, int pageSize) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offset);
            params.put("pageSize", pageSize);
            return baseMapper.queryCaseListWithOffset(offset, pageSize);
        } catch (Exception e) {
            log.error("批量分页查询行政处罚案件失败", e);
            throw new RuntimeException("批量分页查询行政处罚案件失败: " + e.getMessage());
        }
    }
}
