package com.lightinit.hsdatashow.tasks;

import com.lightinit.hsdatashow.entity.AirQualityIndex;
import com.lightinit.hsdatashow.entity.AreaAirPollutionIndex;
import com.lightinit.hsdatashow.entity.HbCityAirQualityIndex;
import com.lightinit.hsdatashow.entity.PollutionIndex;
import com.lightinit.hsdatashow.service.task.IGrabDataFromWebTaskService;
import net.sf.ehcache.transaction.xa.EhcacheXAException;
import org.apache.http.util.TextUtils;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: sunxiang
 * @Date: 2018/9/15 15:29
 * @Description:
 **/
@Component("grabDataFromWebTask")
public class GrabDataFromWebTask {

    @Value("${hb.air.url}")
    String hbUrl;

    @Value("${hs.area.air.url}")
    String hsUrl;

    @Autowired
    private IGrabDataFromWebTaskService grabDataFromWebTaskService;

    //定时任务（解析html）
    public void getDataFromHtml(){
        try {
            Document document = getDocument(hbUrl);
            if(document!=null){
                insetDataToDatabase(document);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从网页扒取数据失败！！！！");
        }
    }

    //解析远程文档
    private Document getDocument(String url) throws Exception{
        URL urlPath = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlPath.openConnection();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            StringBuffer stringBuffer = new StringBuffer();//接受html
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            Document document = Jsoup.parse(stringBuffer.toString());
            return document;
        }
        return null;
    }

    //插入数据库
    private void insetDataToDatabase(Document document) throws IOException, ParseException {
            Elements htmlTime = document.getElementsByClass("time");//获取网页中时间标签
            Elements htmlAreIndexAndDegree = document.getElementsByClass("time").next();//获取需要的文本
            //将字符串时间转成时间格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss");
            Date updateDate = dateFormat.parse(htmlTime.text().substring(5));
            String airIndex= htmlAreIndexAndDegree.text().split(" ")[2];//空气质量指数(暂时没有存到数据库)
            //获取各种污染物名称，指数，等级
            Element iscrollTop1 = document.getElementById("iscrollTop1");
            String pollutionAndIndexAndLevle = iscrollTop1.text();
            String[] splits1 = pollutionAndIndexAndLevle.split(" ");
            ArrayList<AirQualityIndex> list1 = new ArrayList<>();
            AirQualityIndex airQualityIndex;
            for(int i=1;i<=splits1.length-1;i++){
                if(i%3==0){
                    airQualityIndex= new AirQualityIndex(splits1[i-3],splits1[i-2].matches("^[1-9]\\d*$")?Integer.parseInt(splits1[i-2]):0,splits1[i-1]);
                    airQualityIndex.setUpdateTime(updateDate);
                    list1.add(airQualityIndex);
                }
            }
            grabDataFromWebTaskService.insert(list1);
            //区县的污染物和空气污染指数
            String[] splits2 = document.getElementsByAttributeValueContaining("background", "http://121.28.49.85:8080/static/images/mainpage_2013_64.jpg").
                    next().text().substring(20).split(" ");
            ArrayList<AreaAirPollutionIndex> list2 = new ArrayList<>();
            AreaAirPollutionIndex areaAirPollutionIndex;
            for(int i=1;i<=splits2.length-1;i++){
                if(i%5==0){
                    areaAirPollutionIndex=new AreaAirPollutionIndex(splits2[i-5],splits2[i-4].matches("^[1-9]\\d*$")?Integer.parseInt(splits2[i-4]):0,splits2[i-3],splits2[i-2],splits2[i-1]);
                    areaAirPollutionIndex.setUpdateTime(updateDate);
                    list2.add(areaAirPollutionIndex);
                }
            }
            grabDataFromWebTaskService.insert(list2);
    }


    private static int xmlCount=0;//当一次连接失败，用于重新发送请求的计数器
    //定时任务（解析xml）
    public void getDataFromXml(){
        System.out.println("解析数据第 ---------------------"+xmlCount+"次");
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//时间转化格式
            ArrayList<HbCityAirQualityIndex> list3 = new ArrayList<>();
            URL url = new URL(hsUrl);
            SAXReader saxReader = new SAXReader();
            org.dom4j.Document document = saxReader.read(url);
            org.dom4j.Element rootElement = document.getRootElement();
            Iterator elementIterator = rootElement.elementIterator();
            org.dom4j.Element e=null;//强转类型此用
            HbCityAirQualityIndex hbCityAirQualityIndex = null;
            while(elementIterator.hasNext()){
                Object node = elementIterator.next();
                Iterator requiredNodes = ((org.dom4j.Element) node).elementIterator();
                hbCityAirQualityIndex = new HbCityAirQualityIndex();
                while (requiredNodes.hasNext()){
                    e=((org.dom4j.Element)requiredNodes.next());
                    if("CityName".equals(e.getName())){
                        hbCityAirQualityIndex.setCityName(e.getText());
                    }
                    if("DayShouYaoWRW".equals(e.getName())){
                        hbCityAirQualityIndex.setPollutionName(e.getText());
                    }
                    if("DayAqi".equals(e.getName())){
                        hbCityAirQualityIndex.setAirIndex(e.getText().matches("[1-9]\\d*$")?Integer.parseInt(e.getText()):0);
                    }
                    if("DayVel".equals(e.getName())){
                        hbCityAirQualityIndex.setDegree(e.getText());
                    }
                    if("DayQuailtyZhuangKuang".equals(e.getName())){
                        hbCityAirQualityIndex.setState(e.getText());
                    }
                    if("DayDate_Time".equals(e.getName())){
                        hbCityAirQualityIndex.setUpdateDate(dateFormat.parse(e.getText().substring(0,11)));
                    }
                }
                list3.add(hbCityAirQualityIndex);
            }
            grabDataFromWebTaskService.insert(list3);
        } catch (Exception e1) {
            e1.printStackTrace();
            if(xmlCount++<3){
                getDataFromXml();
            }else{
                xmlCount=0;
            }
        }
    }
}
