package com.fkzy.warn.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fkzy.warn.common.constants.EntityConstants;
import com.fkzy.warn.common.util.ReportUtil;
import com.fkzy.warn.mapper.LawCaseMapper;
import com.fkzy.warn.model.*;
import com.fkzy.warn.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangjing
 * @date 2023/10/16 18:17
 * @description
 */
@Service
public class LawCaseServiceImpl extends ServiceImpl<LawCaseMapper, LawCase> implements LawCaseService {

    private static final Logger logger = LoggerFactory.getLogger(LawCaseServiceImpl.class);

    @Autowired
    private DishonestInfoService dishonestInfoService;

    @Autowired
    private LimitationService limitationService;

    @Autowired
    private LitigantInfoService litigantInfoService;

    @Autowired
    private EnterpriseInfoService enterpriseInfoService;

    @Autowired
    private EnterpriseAlarmInfoService enterpriseAlarmInfoService;


    @Autowired
    private AlarmCaseService alarmCaseService;
    @Autowired
    private EnterpriseProvinceService enterpriseProvinceService;

    @Override
    public void saveModel(LawCase entity, String ticket) {
        save(entity);
    }

    @Override
    public void updateModel(LawCase entity, String ticket) {
        this.updateById(entity);
    }

    @Override
    public void deleteModel(List<String> ids) {
        LawCase entity = new LawCase();
        entity.setIsDel(EntityConstants.DEL);
        QueryWrapper<LawCase> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        update(entity, wrapper);
    }

    /**
     * 近三月新发案件告警
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    private List<LawCase> threeMonthsCases(String creditCode,boolean needLitigant) {
        // 获取当前日期
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.MONTH, -16);
        Date threeMonthsAgo = calendar.getTime();
        // 获取近三个月的案件 d_larq 立案日期字段
        QueryWrapper<LawCase> query = new QueryWrapper<>();
        query.ge("d_larq", threeMonthsAgo);
        query.eq("credit_code", creditCode);
        List<LawCase> caseList = this.list(query);
        if (needLitigant){
            for (LawCase lawCase : caseList) {
                QueryWrapper<LitigantInfo> infoQueryWrapper = new QueryWrapper<>();
                infoQueryWrapper.eq("n_ajbs", lawCase.getNAjbs());
                lawCase.setLitigantInfoList(litigantInfoService.list(infoQueryWrapper));
            }
        }

        return caseList;
    }
    /**
     * 近三年案件
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    @Override
    public List<LawCase> threeYearsCases(String creditCode) {
        // 获取当前日期
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.MONTH, -36);
        Date threeMonthsAgo = calendar.getTime();
        // 获取近三个月的案件 d_larq 立案日期字段
        QueryWrapper<LawCase> query = new QueryWrapper<>();
        query.ge("d_larq", threeMonthsAgo);
        query.eq("credit_code", creditCode);
        List<LawCase> caseList = this.list(query);
        for (LawCase lawCase : caseList) {
            QueryWrapper<LitigantInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("n_ajbs", lawCase.getNAjbs());
            lawCase.setLitigantInfoList(litigantInfoService.list(infoQueryWrapper));
        }
        return caseList;
    }

    private ReportModel createReportData(String creditCode){
        ReportModel reportModel = new ReportModel();
        QueryWrapper<EnterpriseInfo> enterpriseInfoQueryWrapper = new QueryWrapper<>();
        enterpriseInfoQueryWrapper.eq("CREDITCODE", creditCode);
        EnterpriseInfo enterpriseInfo = enterpriseInfoService.getOne(enterpriseInfoQueryWrapper);
        reportModel.setBackgroundJudicial(ReportUtil.backgroundJudicial(enterpriseInfo));
        reportModel.setBasicEnterprise(enterpriseInfo);
        List<LawCase> threeMonthsCases = threeMonthsCases(creditCode,true);
        reportModel.setThreeMonthsText1(ReportUtil.threeMonthsText1(threeMonthsCases));
        reportModel.setThreeMonthsCases(threeMonthsCases);
        reportModel.setThreeMonthsText2(ReportUtil.threeMonthsText2(threeMonthsCases));
        reportModel.setThreeMonthsText3(ReportUtil.threeMonthsText3(threeMonthsCases));
        List<LawCase> threeYearsCases = threeYearsCases(creditCode);
        reportModel.setCaseStageText1(ReportUtil.caseStageText1(threeYearsCases));
        reportModel.setLocationText(ReportUtil.locationText(threeYearsCases));
        reportModel.setCaseActionText1(ReportUtil.caseActionText1(threeYearsCases));
        reportModel.setThreeYearsCases(threeYearsCases);
        reportModel.setCaseActionText2(ReportUtil.caseActionText2(threeYearsCases));
        reportModel.setLitigationStatusText(ReportUtil.litigationStatusText(threeYearsCases));
        reportModel.setMajorCaseText(ReportUtil.majorCase(threeYearsCases));
        reportModel.setHighFrequencyText(ReportUtil.highFrequencyText(threeYearsCases));
        return reportModel;
    }
    /**
     *
     * 案件信息汇总
     * @param creditCode
     * @return void
     * @author zhangjing
     * @create 2024/12/24
     **/
    private void setAlarmInfo(String creditCode){
        EnterpriseAlarmInfo data = new EnterpriseAlarmInfo();
        data.setCreditCode(creditCode);
        //近三月案件信息
        List<LawCase> threeMonths = threeMonthsCases(creditCode,false);
        data.setThreeMonthsCount(threeMonths.size());
        data.setThreeMonthsAmount(ReportUtil.getCaseAmount(threeMonths));
        //近三年案件信息
        List<LawCase> threeYears = threeYearsCases(creditCode);
        List<EnterpriseProvince> enterpriseProvinceList = new ArrayList<>();
        ReportUtil.setAlarmInfo(data, threeYears,enterpriseProvinceList);
        QueryWrapper<EnterpriseProvince> enterpriseProvinceQueue = new QueryWrapper<>();
        enterpriseProvinceQueue.eq("credit_code",creditCode);
        enterpriseProvinceService.remove(enterpriseProvinceQueue);
        enterpriseProvinceService.saveBatch(enterpriseProvinceList);
        enterpriseAlarmInfoService.saveOrUpdate(data);
    }

    @Override
    public void judicialModelSave(JSONObject jsonObject) {
        setAlarmInfo("91320301MA20TF8T84");
        if (true){
            return;
        }

//          ReportModel reportModel = createReportData();
//          ReportUtil.createReport(reportModel);
        String filePath = "徐州-司法.txt";
//        String filePath = "工商.txt";
        String jsonOutput = convertTextToJson(filePath);
       if (jsonOutput == null) {
            logger.error("转换失败，JSON 字符串为空");
            return;
        }
        jsonObject = new JSONObject().parseObject(jsonOutput);
//        enterpriseInfoService.industryModelSave(jsonObject);
        JSONArray arr = jsonObject.getJSONArray("data");
        if (arr == null || arr.isEmpty()) {
            logger.error("数据数组为空");
            return;
        }

        JSONObject data = arr.getJSONObject(0);
        String info = data.getString("id");
        String companyName = null;
        String creditCode = null;
        if (info != null) {
            String[] items = info.split(":");
            if (items.length == 2) {
                companyName = items[0];
                creditCode = items[1];
            }
        }

        // 失信
//        JSONObject sx = data.getJSONObject("sx");
//        JSONArray sxbzxrCurrent = sx.getJSONArray("sxbzxr_current");
//        String finalCompanyName = companyName;
//        String finalCreditCode = creditCode;
//        List<DishonestInfo> dishonestInfoList = JSON.parseArray(sxbzxrCurrent.toString(), DishonestInfo.class)
//            .stream()
//            .peek(p -> {
//                p.setCompanyName(finalCompanyName);
//                p.setCreditCode(finalCreditCode);
//            })
//            .collect(Collectors.toList());
//        dishonestInfoService.saveOrUpdateBatch(dishonestInfoList);

//        // 八类案件
//        JSONObject detail = data.getJSONObject("detail");
//        setCases(detail, companyName, creditCode);
//
//        // 限高
//        JSONObject xg = data.getJSONObject("xg");
//        JSONArray xgbzxrCurrent = xg.getJSONArray("xgbzxr_current");
//
//        List<Limitation> limitationList = JSON.parseArray(xgbzxrCurrent.toString(), Limitation.class)
//            .stream()
//            .peek(p -> {
//                p.setCompanyName(finalCompanyName);
//                p.setCreditCode(finalCreditCode);
//            })
//            .collect(Collectors.toList());
//        limitationService.saveOrUpdateBatch(limitationList);
    }




    private void setCases(JSONObject detail, String companyName, String creditCode) {
        List<Map.Entry<String, JSONArray>> entries = Arrays.asList(
            new AbstractMap.SimpleEntry<>("civil", detail.getJSONObject("civil").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("criminal", detail.getJSONObject("criminal").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("administrative", detail.getJSONObject("administrative").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("preservation", detail.getJSONObject("preservation").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("implement", detail.getJSONObject("implement").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("bankrupt", detail.getJSONObject("bankrupt").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("jurisdict", detail.getJSONObject("jurisdict").getJSONArray("cases")),
            new AbstractMap.SimpleEntry<>("compensate", detail.getJSONObject("compensate").getJSONArray("cases")));
        entries.forEach(entry -> saveCases(entry.getValue(), entry.getKey(), companyName, creditCode));
    }


    private void saveCases(JSONArray jsonArray, String type, String companyName, String creditCode) {
        List<LawCase> caseList = new ArrayList<>();
        List<LitigantInfo> litigantInfoList = new ArrayList<>();
        List<String> nAjbsList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            LawCase lawCase = JSON.parseObject(jsonObject.toString(), LawCase.class);
            lawCase.setCompanyName(companyName);
            lawCase.setCreditCode(creditCode);
            lawCase.setCaseType(type);
            if (lawCase.getNAjbs() != null) {
                caseList.add(lawCase);
            }

            JSONArray cDsrxx = jsonObject.getJSONArray("c_dsrxx");
            nAjbsList.add(lawCase.getNAjbs());
            if (cDsrxx != null && lawCase.getNAjbs() != null) {
                for (int j = 0; j < cDsrxx.size(); j++) {
                    JSONObject obj = cDsrxx.getJSONObject(j);
                    LitigantInfo litigantInfo = JSON.parseObject(obj.toString(), LitigantInfo.class);
                    litigantInfo.setNAjbs(lawCase.getNAjbs());
                    litigantInfoList.add(litigantInfo);
                }
            }
        }


        if (!caseList.isEmpty()) {
            saveOrUpdateCases(caseList);
        }
        if (!litigantInfoList.isEmpty()) {
            QueryWrapper<LitigantInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("n_ajbs", nAjbsList);
            litigantInfoService.remove(queryWrapper);
            saveOrUpdateLitigantInfo(litigantInfoList);
        }
    }

    public void saveOrUpdateCases(List<LawCase> entityList) {
        int batchSize=20;
        int size = entityList.size();
        for (int i = 0; i < size; i += batchSize) {
            int toIndex = Math.min(i + batchSize, size);
            List<LawCase> batch = entityList.subList(i, toIndex);
            this.saveOrUpdateBatch(batch);
        }
    }

public void saveOrUpdateLitigantInfo(List<LitigantInfo> entityList) {
    int batchSize=20;
    int size = entityList.size();
    for (int i = 0; i < size; i += batchSize) {
        int toIndex = Math.min(i + batchSize, size);
        List<LitigantInfo> batch = entityList.subList(i, toIndex);
        // 执行批量插入或更新操作
        litigantInfoService.saveOrUpdateBatch(batch);
    }
}


    public String convertTextToJson(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String currentLine;
            while ((currentLine = br.readLine()) != null) {
                contentBuilder.append(currentLine).append("\n");
            }
        } catch (Exception e) {
            logger.error("读取文件 {} 失败", filePath, e);
            return null;
        }
        return contentBuilder.toString();
    }
}
