package com.trs.project.activemq;
//
import cn.hutool.core.io.FileUtil;
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.jcraft.jsch.ChannelSftp;
import com.trs.project.entity.BusinessInfo;
import com.trs.project.entity.DataCleaning;
import com.trs.project.entity.NewsArticleInfo;
import com.trs.project.entity.RiskArticleInfo;
import com.trs.project.file.FileReaderResource;
import com.trs.project.service.BusinessInfoService;
import com.trs.project.service.DataCleaningService;
import com.trs.project.service.NewsArticleInfoService;
import com.trs.project.service.RiskArticleInfoService;
import com.trs.project.timer.BusinessTask;
import com.trs.project.utils.SFTPUtils;
import com.trs.project.utils.TRSParser;
import com.trs.project.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.util.*;

//
///**
// * @Author 一一哥Sun
// * @Date Created in 2020/4/15
// * @Description 消息的消费者
// */
@Slf4j
@Component
public class Consumer {


   @Autowired
    private RiskArticleInfoService riskArticleInfoService;

    @Autowired
    private BusinessInfoService businessInfoService;

    @Autowired
    private FileReaderResource fileReaderResource;

    @Autowired
    private DataCleaningService dataCleaningService;

    @Autowired
    private NewsArticleInfoService newsArticleInfoService;

    @Value("${ftp.fileURL}")
    private String fileUrl_config;

    @Value("${ftp.host}")
    private String host_config;

    @Value("${ftp.port}")
    private int port_config;

    @Value("${ftp.username}")
    private String username_config;

    @Value("${ftp.password}")
    private String password_config;

    private String targetUrl;

   //queue模式的消费者
    @JmsListener(destination="${spring.activemq.queue-name}", containerFactory="queueListener")
    public void readActiveQueue(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        Object filelist = jsonObject.get("filelist");
        Object type = jsonObject.get("type");
        String types = type.toString();
        //log.info(jsonObject.toJSONString());
        if(types.equals("4")  || types.equals("10")){
            JSONArray arrayStr = JSONArray.parseArray(filelist.toString());
            for (Object oStr : arrayStr) {
                try {
                    targetUrl = oStr.toString();
                    String fileUrl = fileUrl_config +"/mq4/";
                    SFTPUtils sftpUtils  =  new SFTPUtils(host_config, port_config, username_config, password_config);
                    String[] split = targetUrl.split("/");
                    String file = "";
                    for(int i = 0; i < split.length-1;i++){
                        file += split[i]+"/";
                    }
                    String name = split[split.length - 1];
                    sftpUtils.download(file,name,fileUrl_config +"/mq4/"+name, sftpUtils.sftp);
                    //解压
                    //Java 解压zip
                    String newFilename = ZipUtil.unzipFile(fileUrl+name, fileUrl);
                    //解析文件对应的JSON数据
                    File fileJSON = new File(fileUrl_config+"/mq4/"+newFilename);
                    String content = FileUtils.readFileToString(fileJSON,"GBK");
                    JSONArray array = JSONArray.parseArray(JSON.parseObject(content).get("RECLIST").toString());
                    for (Object o : array) {
                        RiskArticleInfo riskArticleInfo = JSON.parseObject(o.toString(), RiskArticleInfo.class);
                        String pubtime = riskArticleInfo.getPubtime();
                        pubtime = pubtime.replace("/", "-");
                        riskArticleInfo.setPubtime(pubtime);
                        riskArticleInfo.setSavetime(LocalDateTime.now());
                        log.info("保存信号信息："+riskArticleInfo.getTitle());
                        riskArticleInfoService.saveOrUpdate(riskArticleInfo);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(types.equals("1") || types.equals("2") || types.equals("3")){
            JSONArray arrayStr = JSONArray.parseArray(filelist.toString());
            for (Object oStr : arrayStr) {
                try {
                    targetUrl = oStr.toString();
                    String fileUrl = fileUrl_config+"/mq2/";
                    SFTPUtils sftpUtils  =  new SFTPUtils(host_config, port_config, username_config, password_config);
                    String[] split = targetUrl.split("/");
                    String file = "";
                    for(int i = 0; i < split.length-1;i++){
                        file += split[i]+"/";
                    }
                    String name = split[split.length - 1];
                    sftpUtils.download(file,name,fileUrl_config+"/mq2/"+name, sftpUtils.sftp);
                    //解压
                    //Java 解压zip
                    String newFilename = ZipUtil.unzipFile(fileUrl+name, fileUrl);
                    //解析文件对应的JSON数据
                    File fileJSON = new File(fileUrl_config+"/mq2/"+newFilename);
                    String content = FileUtils.readFileToString(fileJSON,"GBK");
                    JSONArray array = JSONArray.parseArray(JSON.parseObject(content).get("RECLIST").toString());
                    for (Object o : array) {
                        DataCleaning dataCleaning = JSON.parseObject(o.toString(), DataCleaning.class);
                        Object trsCust = JSON.parseObject(o.toString()).get("trsCust");
                        Object result = JSON.parseObject(trsCust.toString()).get("result");
                        JSONArray array1 = JSONArray.parseArray(result.toString());
                        dataCleaning.setResultstr("");
                        for (Object o1 : array1) {
                            dataCleaning.setResultstr(o1.toString());
                            if(types.equals("1")){
                                dataCleaning.setSource("新闻");
                            }
                            if(types.equals("2")){
                                dataCleaning.setSource("微信");
                            }
                            if(types.equals("3")){
                                dataCleaning.setSource("微博");
                            }
                            try {
                                log.info("保存清洗数据信息："+dataCleaning.getTitle());
                                dataCleaning.setSavetime(LocalDateTime.now());
                                dataCleaningService.saveOrUpdate(dataCleaning);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        //清洗程序
        QueryWrapper<BusinessInfo> queryWrapperBusinessInfo1 = new QueryWrapper<BusinessInfo>();
        queryWrapperBusinessInfo1.eq("BUSINESS_TYPE",1);
        List<BusinessInfo> listBusinessInfo1 = businessInfoService.list(queryWrapperBusinessInfo1);
        QueryWrapper<BusinessInfo> queryWrapperBusinessInfo2 = new QueryWrapper<BusinessInfo>();
        queryWrapperBusinessInfo2.eq("BUSINESS_TYPE",2);
        List<BusinessInfo> listBusinessInfo2 = businessInfoService.list(queryWrapperBusinessInfo2);
        listBusinessInfo1.addAll(listBusinessInfo2);
        for (BusinessInfo businessInfo : listBusinessInfo1) {
            QueryWrapper<DataCleaning> queryWrapperDataCleaning = new QueryWrapper<DataCleaning>();
            queryWrapperDataCleaning.like("TITLE",businessInfo.getName());
            queryWrapperDataCleaning.or()
                    .like("CONTENT",businessInfo.getName());
            List<DataCleaning> list = dataCleaningService.list(queryWrapperDataCleaning);
            for (DataCleaning cleaning : list) {
                NewsArticleInfo newsArticleInfo = new NewsArticleInfo(cleaning);
                try {
                    log.info("保存舆情信息："+newsArticleInfo.getTitle());
                    newsArticleInfo.setResultstr(businessInfo.getName());
                    newsArticleInfoService.saveOrUpdate(newsArticleInfo);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        //企业简称+地域清洗程序
        //地区名称
        ArrayList<String> arrayList = fileReaderResource.ReaderFile();
        //企业简称
        Map<String, String> enterpriseArrayALL = getEnterpriseArrayALL();
        Iterator<Map.Entry<String, String>> iterator = enterpriseArrayALL.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            for (String city : arrayList) {
                List<DataCleaning> list = dataCleaningService.list();
                for (DataCleaning cleaning : list) {
                    String title = cleaning.getTitle();
                    String content = cleaning.getContent();
                    if(content.contains("请不要刷新太快")){
                        continue;
                    }
                    boolean containsCityTitle = title.contains(city);
                    boolean containsValueTitle = title.contains(entry.getValue());
                    boolean containsCitycontent =  content.contains(city);
                    boolean containsValueContent = content.contains(entry.getValue());
                    if( (containsCityTitle && containsValueTitle) || (containsCitycontent && containsValueContent)){
                        NewsArticleInfo newsArticleInfo = new NewsArticleInfo(cleaning);
                        newsArticleInfo.setResultstr(entry.getKey());
                        try {
                            log.info("保存舆情信息："+newsArticleInfo.getTitle());
                            newsArticleInfoService.saveOrUpdate(newsArticleInfo);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        QueryWrapper<DataCleaning> deleteAll  = new QueryWrapper<DataCleaning>();
        dataCleaningService.remove(deleteAll);
        try {
         Path path = Paths.get(fileUrl_config+"/mq4/");
         Files.walkFileTree(path,
                 new SimpleFileVisitor<Path>() {
                  // 先去遍历删除文件
                  @Override
                  public FileVisitResult visitFile(Path file,
                                                   BasicFileAttributes attrs) throws IOException {
                   Files.delete(file);
                   System.out.printf("文件被删除 : %s%n", file);
                   return FileVisitResult.CONTINUE;
                  }
                 }
         );
        }catch (Exception e){
         e.printStackTrace();
        }
        try {
            Path path = Paths.get(fileUrl_config+"/mq2/");
            Files.walkFileTree(path,
                    new SimpleFileVisitor<Path>() {
                        // 先去遍历删除文件
                        @Override
                        public FileVisitResult visitFile(Path file,
                                                         BasicFileAttributes attrs) throws IOException {
                            Files.delete(file);
                            System.out.printf("文件被删除 : %s%n", file);
                            return FileVisitResult.CONTINUE;
                        }
                    }
            );
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String[] getEnterpriseArray(){
        String enterpriseArrayYl[] = {
                "伊利集团","伊利公司","伊利乳液",  "伊利",
                "鄂尔多斯资源","鄂尔多斯资源股份",
                "天首科技","天首集团","天首",
                "华资实业", "华资",
                "平庄能源","平庄",
                "吉隆黄金","吉隆",
                "兴业矿业","兴业",
                "亿利洁能","亿利",
                "蒙电华能","蒙电","蒙电华能热电",
                "金宇生物","金宇","金宇生物技术",
                "银泰","银泰黄金",
                "君正能源化工","君正能源","君正","化工",
                "君正能源化工集团","君正",
                "第一机械","第一机械集团",
                "北方重型汽车","北方汽车",
                "明天科技","明天","西水创业","西水",
                "远兴","远兴能源",
                "兰太","兰太实业",
                "包钢钢联","包钢","包钢集团",
                "北方稀土(集团)","北方稀土集团","北方稀土",
                "金河生物","金河",
                "霍林河露天煤业","霍林河露天","露天煤业",
                "蒙草生态环境(集团)","蒙草生态环境集团","蒙草生态环境","蒙草生态","蒙草",
                "东宝生物","东宝生物技术","东宝","福瑞医疗","福瑞医疗科技","福瑞"
        };
        return enterpriseArrayYl;
    }
    public Map<String,String> getEnterpriseArrayALL(){
        Map<String,String> hashMap = new HashMap<String,String>();
        hashMap.put("内蒙古包钢钢联股份有限公司","包钢");
        hashMap.put("内蒙古君正能源化工集团股份有限公司","君正");
        hashMap.put("内蒙古君正能源化工集团股份有限公司","君正能源");
        hashMap.put("内蒙古伊利实业集团股份有限公司","伊利");
        hashMap.put("中国北方稀土（集团）高科技股份有限公司","北方稀土");
        hashMap.put("亿利洁能股份有限公司","亿利");
        hashMap.put("亿利洁能股份有限公司","亿利洁能");
        hashMap.put("银泰黄金股份有限公司","银泰");
        hashMap.put("银泰黄金股份有限公司","银泰黄金");
        hashMap.put("内蒙古电投能源股份有限公司","电投能源");
        hashMap.put("内蒙古电投能源股份有限公司","电投");
        hashMap.put("内蒙古兴业矿业股份有限公司","兴业");
        hashMap.put("内蒙古兴业矿业股份有限公司","兴业矿业");
        hashMap.put("内蒙古第一机械集团股份有限公司","内蒙古第一机械集团");
        hashMap.put("内蒙古第一机械集团股份有限公司","第一机械");
        hashMap.put("蒙草生态环境（集团）股份有限公司","蒙草");
        hashMap.put("内蒙古大中矿业股份有限公司","大中矿业");
        hashMap.put("内蒙古大中矿业股份有限公司","矿业");
        hashMap.put("内蒙古大中矿业股份有限公司","内蒙古大中矿业");
        hashMap.put("内蒙古鄂尔多斯资源股份有限公司","内蒙古鄂尔多斯资源");
        hashMap.put("内蒙古鄂尔多斯资源股份有限公司","鄂尔多斯资源");
        hashMap.put("金宇生物技术股份有限公司","金宇生物");
        hashMap.put("金宇生物技术股份有限公司","金宇生物技术");
        hashMap.put("金河生物科技股份有限公司","金河生物");
        hashMap.put("金河生物科技股份有限公司","金河生物科技");
        hashMap.put("包头东宝生物技术股份有限公司","东宝生物");
        hashMap.put("包头东宝生物技术股份有限公司","包头东宝生物");
        hashMap.put("内蒙古新华发行集团股份有限公司","新华发行");
        hashMap.put("内蒙古福瑞医疗科技股份有限公司","福瑞");
        hashMap.put("内蒙古福瑞医疗科技股份有限公司","福瑞医疗");
        hashMap.put("内蒙古大唐药业股份有限公司","大唐药业");
        hashMap.put("内蒙古北方重型汽车股份有限公司","北方重型");
        return hashMap;
    }

}