package com.jsc.dsp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsc.dsp.model.SearchAggregation;
import com.jsc.dsp.model.TargetSocial;
import com.jsc.dsp.model.TargetWebsite;

import java.util.Date;
import java.util.Map;
import java.util.logging.Logger;

import static com.jsc.dsp.utils.EsUtils.performAggregationSearch;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.support.LogIfLevelEnabled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class AutoPatroller {

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    long updateInterval = 1500L;

    @Value("${custom.websiteQueryAPI}")
    String websiteQueryAPI;

    @Value("${custom.websiteUpdateAPI}")
    String websiteUpdateAPI;

    @Value("${custom.socialQueryAPI}")
    String socialQueryAPI;

    @Value("${custom.socialUpdateAPI}")
    String socialUpdateAPI;

    @Value("${es.ip}")
    String esIp;

    @Value("${es.port}")
    Integer esPort;

    @Value("${es.username}")
    String esUsername;

    @Value("${es.password}")
    String esPassword;

    @Scheduled(cron = "0 45 0/3 * * *")
    public void checkNewsSite() {
        checkWebsite("es_sitename", "es_carriertype", "news");
    }

    @Scheduled(cron = "0 15 1/3 * * *")
    public void checkWechat() {
        checkSocial("es_authors", "es_carriertype", "wechat", "5");
    }

    @Scheduled(cron = "0 0 2/4 * * *")
    public void checkArticleSite() {
        checkWebsite("es_sitename", "es_carriertype", "article");
    }

    public void checkWebsite(String aggFieldName, String queryFieldName, String queryFieldValue) {
        try {
            Map<String, SearchAggregation> searchAggregationMap = performAggregationSearch(
                    esIp, esPort, esUsername, esPassword, aggFieldName, queryFieldName, queryFieldValue);
            JSONObject dataObject = new JSONObject();
            dataObject.put("carrierType", queryFieldValue);
            String rsp = HttpUtils.post(websiteQueryAPI, dataObject);
            JSONObject rspObj = JSON.parseObject(rsp);
            if (rspObj.getIntValue("code") == 200) {
                JSONArray rspArr = rspObj.getJSONArray("content");
                for (Object obj : rspArr) {
                    TargetWebsite targetWebsite = JSONObject.parseObject(obj.toString(), TargetWebsite.class);
                    String siteName = targetWebsite.getSiteName();
                    if (searchAggregationMap.containsKey(siteName)) {
                        SearchAggregation checkInfo = searchAggregationMap.get(siteName);
                        targetWebsite.setCheckTotalNum(checkInfo.getCount());
                        targetWebsite.setCheckLastTime(checkInfo.getLastTime());
                        targetWebsite.setCheckUpdateTime(new Date());
                        String updateRsp = HttpUtils.post(websiteUpdateAPI, targetWebsite);
                        JSONObject updateRspObj = JSONObject.parseObject(updateRsp);
                        if (updateRspObj.getIntValue("code") != 200) {
                            logger.warning("更新站点【" + siteName + "】巡检信息失败");
                        }
                        Thread.sleep(updateInterval);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("站点巡检完毕");
    }

    public void checkSocial(String aggFieldName, String queryFieldName, String queryFieldValue, String socialTypeCode) {
        try {
            Map<String, SearchAggregation> searchAggregationMap = performAggregationSearch(
                    esIp, esPort, esUsername, esPassword, aggFieldName, queryFieldName, queryFieldValue);
            TargetSocial postData = new TargetSocial();
            postData.setUserFlag("0");
            postData.setUserType(socialTypeCode);
            String rsp = HttpUtils.post(socialQueryAPI, postData);
            JSONObject rspObj = JSON.parseObject(rsp);
            if (rspObj.getIntValue("code") == 200) {
                JSONArray rspArr = rspObj.getJSONArray("content");
                for (Object obj : rspArr) {
                    TargetSocial targetSocial = JSONObject.parseObject(obj.toString(), TargetSocial.class);
                    String userName = targetSocial.getUserName();
                    if (searchAggregationMap.containsKey(userName)) {
                        SearchAggregation checkInfo = searchAggregationMap.get(userName);
                        targetSocial.setCheckTotalNum(checkInfo.getCount());
                        targetSocial.setCheckLastTime(checkInfo.getLastTime());
                        targetSocial.setCheckUpdateTime(new Date());
                        String updateRsp = HttpUtils.post(socialUpdateAPI, targetSocial);
                        JSONObject updateRspObj = JSONObject.parseObject(updateRsp);
                        if (updateRspObj.getIntValue("code") != 200) {
                            logger.warning("更新账号【" + userName + "】巡检信息失败");
                        }
                        Thread.sleep(updateInterval);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("社交帐号巡检完毕");

    }

}
