package com.ruoyi.quartz.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.SubPreNewMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.SubInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.util.*;
import java.util.regex.Pattern;

import static java.lang.System.in;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {

    @Autowired
    private ITenderService tenderService;
    @Autowired
    private ITenderLogService tenderLogService;
    @Autowired
    private ISubPreNewService subPreNewService;
    @Autowired
    private ISubFlowService subFlowService;
    @Autowired
    private ISubInfoService subInfoService;
    @Autowired
    private ISubService subService;
    @Autowired
    private ISubDocumentService subDocumentService;

    @Autowired
    private ISubDocService subDocService;
    @Autowired
    private ISubPreLogService subPreLogService;

    @Autowired
    private ISyncLogService syncLogService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private ISubSourceService subSourceService;

    @Autowired
    private ISyncVisitService visitService;
    @Autowired
    private IDocLogService docLogService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    boolean isRun = false;

    public void ryNoParams() {
        //同步自治区项目信息
        if (!isRun) {
            isRun = true;
            //从自治区同步项目信息
            this.syncSubInfo();
//            //同步自治区前期手续信息
            this.syncPreNew();
//           //同步住建局手续
            this.syncDoc();
//            this.syncDocLog();
//            //从公共资源交易中心同步招投标信息
            this.syncTender();
//           //从公共资源交易中心同步招投标信息
//            this.syncTenderLog();
            isRun = false;
        }
/*        //同步自治区前期手续信息
        this.syncPreNew();
        //从公共资源交易中心同步招投标信息
        this.syncTender();
        //从公共资源交易中心同步招投标信息
        this.syncTenderLog();*/
    }

    private void syncPreNew() {
        String company = "自治区";
        List<SubDocument> list = new ArrayList<>();
        try {
            subDocumentService.deleteByCon();
            list = subDocumentService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }

        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "4"));
        }

        for (SubDocument document : list) {
            try {
                if (subInfoService.syncDocument(document, company)) {
                    document.setIsHandle("2");
                    subDocumentService.saveOrUpdate(document);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SyncLog log = new SyncLog();
                log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("3").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续异常:项目名称【%s】和项目代码【%s】,手续【%s】", document.getProjectname(), document.getProjectid(), document.getSxzxname()));
                syncLogService.saveOrUpdate(log);
                System.out.println("执行同步前期手续办理情况异常" + e.getMessage());
            }
        }
        //任务处理成功,没有返回异常将记录置为已处理
        System.out.println("执行无参方法");
    }
    private void syncDocLog() {
        String company = "住建局";
        List<DocLog> list = new ArrayList<>();
        try {
            list = docLogService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }

        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "4").eq(SyncLog::getCompany, company).ne(SyncLog::getState,"2"));
        }
        for (DocLog doc : list) {
            if(doc.getCode().split("-").length!=5){
                doc.setIsHandle("2");
                docLogService.saveOrUpdate(doc);
                continue;
            }
//            if (doc.getDocName().contains("-")){
//                doc.setDocName(doc.getDocName().split("-")[0]);
//            }
            try {
                if (subInfoService.SyncDocLog(doc, company)) {
                    doc.setIsHandle("2");
                    docLogService.saveOrUpdate(doc);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SyncLog log = new SyncLog();
                log.setCat("5").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(doc)).setState("3").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setCompany(company).setIsHandle("1").setRemark(String.format("同步前期办理手续异常:项目名称【%s】和项目代码【%s】,手续【%s】", doc.getCode(), doc.getCode(), doc.getDocName()));
                syncLogService.saveOrUpdate(log);
                System.out.println("执行同步前期手续办理情况异常" + e.getMessage());
            }
        }
        //任务处理成功,没有返回异常将记录置为已处理
        System.out.println("执行无参方法");
    }

    private void syncDoc() {
        String company = "住建局";
        List<SubDoc> list = new ArrayList<>();
        try {
            list = subDocService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }

        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "4").eq(SyncLog::getCompany, company).ne(SyncLog::getState,"2"));
        }

        for (SubDoc doc : list) {
            String code = doc.getCode();
            String[] parts = code.split("-");
            if (parts.length >= 5) {
                doc.setCode(String.join("-", Arrays.copyOfRange(parts, 0, 5)));
            }
            try {
                if (subInfoService.syncDoc(doc, company)) {
                    doc.setIsHandle("2");
                    subDocService.saveOrUpdate(doc);
                }
                /*                this.handlerDocument(document);*/
            } catch (Exception e) {
                e.printStackTrace();
                SyncLog log = new SyncLog();
                log.setCat("5").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(doc)).setState("3").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setCompany(company).setIsHandle("1").setRemark(String.format("同步前期办理手续异常:项目名称【%s】和项目代码【%s】,手续【%s】", doc.getProjectName(), doc.getCode(), doc.getSxzxName()));
                syncLogService.saveOrUpdate(log);
                System.out.println("执行同步前期手续办理情况异常" + e.getMessage());
            }
        }
        //任务处理成功,没有返回异常将记录置为已处理
        System.out.println("执行无参方法");
    }


    private void setSubInfoStatus(SubInfo subInfo) {
        //如果政府项目办理了项目投资建议书 进入新建库   企业核准或备案 进入新建库
        boolean isHave = false;
        subInfo.setStatus("6");
        if ("1".equals(subInfo.getKindNature())) { //政府投资
            //如果政府项目办理了项目投资建议书  则进入新建库
            int cnt = subPreNewService.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, 1));
            if (cnt > 0) {
                isHave = true;
                subInfo.setStatus("6");
            }
        } else {
            //企业核准或备案 进入新建库
            int cnt = subPreNewService.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "3"));
            if (cnt > 0) {
                subInfo.setStatus("6");
                isHave = true;
            }
            cnt = subPreNewService.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "5"));
            if (cnt > 0) {
                isHave = true;
                subInfo.setStatus("6");
            }
        }
        //如果办理了招投标  自动进入在建库
        int cnt = subPreNewService.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "16"));
        if (cnt > 0) {
            subInfo.setStatus("7");
        } else {
            if (isHave) {
                subInfo.setStatus("6");
            } else {
                subInfo.setStatus("1");
            }
        }
        subInfoService.saveOrUpdate(subInfo);
    }

    //同步项目信息
    private void syncSubInfo() {
        String company = "自治区";
        List<Sub> list = new ArrayList<>();
        try {
            list = subService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }

        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "1"));
        }
        for (Sub sub : list) {
            if (sub.getProjectid().contains("X")||sub.getProjectid().contains("x")){
                continue;
            }
            String prefix = sub.getProjectid().substring(0, 4);
            String regex = "^\\d{2}(0[1-9]|1[0-2])"; // 两位数字年份，后接两位数字月份
            if (!Pattern.matches(regex,prefix)){
                continue;
            }
            try {
                if (subInfoService.syncSubInfo(sub, company)) {
                    sub.setIsHandle("2");
                    subService.saveOrUpdate(sub);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SyncLog log = new SyncLog();
                log.setCat("1").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(sub)).setState("3").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setCompany(company).setIsHandle("1").setRemark(String.format("同步项目信息异常:项目名称【%s】和项目代码【%s】", sub.getProjectname(), sub.getProjectid()));
                syncLogService.saveOrUpdate(log);
                System.out.println("执行同步项目情况异常" + e.getMessage());
            }
        }
    }


    public void syncTenderLog() {
        //查询没有处理的招投标信息
        String company = "公共资源交易中心";
        List<TenderLog> list = new ArrayList<>();
        try {
            list = tenderLogService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }
        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "4"));
        }
        //处理招标任务
        for (TenderLog tenderLog : list) {
            try {
                if (subInfoService.SyncTenderLog(tenderLog, company)) {
                    tenderLog.setIsHandle("2");
                    tenderLogService.saveOrUpdate(tenderLog);
                }
            } catch (Exception e) {
                SyncLog log = new SyncLog();
                log.setCat("3").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("1").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步招投标审批信息异常:项目名称【%s】和项目代码【%s】", tenderLog.getTitle(), tenderLog.getCode()));
                syncLogService.saveOrUpdate(log);
            }
        }
        //任务处理成功,没有返回异常将记录置为已处理
        System.out.println("执行无参方法");
    }

    //同步招投标信息
    public void syncTender() {
        //查询没有处理的招投标信息
        String company = "公共资源交易中心";
        List<Tender> list = new ArrayList<>();
        try {
            list = tenderService.listTask();
        } catch (Exception ex) {
            System.out.println("数据查询异常" + ex.getMessage());
        }
        if (list.size() > 0) {
            //删除之前的同步日志
            syncLogService.remove(new LambdaQueryWrapper<SyncLog>().eq(SyncLog::getCat, "1"));
        }
        //处理招标任务
        for (Tender tender : list) {
            try {
                if (subInfoService.syncTender(tender, company)) {
                    tender.setIsHandle("2");
                    tenderService.saveOrUpdate(tender);
                }
            } catch (Exception e) {
                SyncLog log = new SyncLog();
                log.setCat("4").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(tender)).setState("1").setInfo(e.getMessage());
                log.setCreateTime(DateUtil.date()).setIsHandle("1").setCompany(company).setRemark(String.format("同步招投标信息:项目名称【%s】和项目代码【%s】", tender.getTitle(), tender.getCode()));
                syncLogService.saveOrUpdate(log);
                System.out.println("执行同步招标投标异常" + e.getMessage());
            }
        }
        //任务处理成功,没有返回异常将记录置为已处理
        System.out.println("执行无参方法");
    }

}
