package cn.com.taiji.mqcrj.task;

import cn.com.taiji.mqcrj.entity.*;
import cn.com.taiji.mqcrj.mapper.BaseCreateNewTableMapper;
import cn.com.taiji.mqcrj.service.*;
import cn.com.taiji.mqcrj.utils.Constant;
import cn.com.taiji.mqcrj.utils.SSLClient;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务
 * @author chen mh
 * @date 2023/7/11 10:20
 */
@Component
@Slf4j
public class ScheduleTask {
    @Resource
    private MQDQZDRSService mqdqzdrsService;

    @Resource
    private MQDQCRJZDRSService mqdqcrjzdrsService;

    @Resource
    private MQWGRQZBLQKService mqwgrqzblqkService;

    @Resource
    private MQWGRYJService mqwgryjService;

    @Resource
    private MQWGRZDJZQKService mqwgrzdjzqkService;

    @Resource
    private MQWGRYJSJService mqwgryjsjService;

    @Resource
    private BaseCreateNewTableMapper baseCreateNewTableMapper;

    @Value("${taiji.jgUrl}")
    private String jgUrl;

    @Value("${taiji.xt-code}")
    private String xtCode;

    @Value("${taiji.jym}")
    private String jym;

    /**
     * 每天六点执行一次  获取免签地区在岛人数
     */
    @Scheduled(cron = "0 0 6 * * ?")
    //@Scheduled(initialDelay = 5000,fixedDelay = 60*60*60)
    public void scheduleOne() throws Exception {
        log.info("{}-执行START时间-{}", Constant.MQDQZDRS,DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQDQZDRS, null, 1);
        HttpResponse res = client.execute(get);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);
            for (int i=1;i<=total/200+1;i++){
                Thread.sleep(1000);
                HttpGet httpGet = handleJgUrl(Constant.MQDQZDRS, null, i);
                HttpResponse response = client.execute(httpGet);
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject jsonObject1 = JSONObject.parseObject(resultPage);
                    if (jsonObject1.getBoolean("success")) {
                        String rows1 = jsonObject1.getString("rows");
                        List<VisaFreeAreaIslandPerson> visaFreeAreaIslandPeople = JSONObject.parseArray(rows1, VisaFreeAreaIslandPerson.class);
                        mqdqzdrsService.saveOrUpdateBatch(visaFreeAreaIslandPeople);
                    }
                }
                httpGet.releaseConnection();
            }
        }

        log.info("执行END时间-{}", DateUtil.date());
    }

    @Scheduled(cron = "1 10 6 * * ?")
    public void scheduleTwo() throws Exception {
        log.info("{}==执行START时间-{}",Constant.MQDQCRJZDRS, DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQDQCRJZDRS, null, 1);
        HttpResponse res = client.execute(get);
        int count = 0;
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);

            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);
            if(total>0){
                baseCreateNewTableMapper.delTable("jg_mqdqcrj_zdrs");
            }

            for (int i=1;i<=total/200+1;i++){
                count=i;
                Thread.sleep(2000);
                HttpGet httpGet = handleJgUrl(Constant.MQDQCRJZDRS, null, i);
                HttpResponse response = client.execute(httpGet);
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject jsonObject1 = JSONObject.parseObject(resultPage);
                    if (jsonObject1.getBoolean("success")) {
                        String rows = jsonObject1.getString("rows");
                        List<VisaFreeAreaEntryAndExitIslandPerson> visaFree = JSONObject.parseArray(rows, VisaFreeAreaEntryAndExitIslandPerson.class);
                        mqdqcrjzdrsService.saveBatch(visaFree);
                    }
                }
                httpGet.releaseConnection();
            }
        }
        log.info("执行END时间-{},执行次数-{}", DateUtil.date(),count);
    }

    @Scheduled(cron = "2 20 6 * * ?")
    public void scheduleThree() throws Exception {
        log.info("{}==执行START时间-{}",Constant.MQWGRQZQK, DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQWGRQZQK, null, 1);
        HttpResponse res = client.execute(get);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);
            for (int i=1;i<=total/200+1;i++){
                Thread.sleep(1000);
                HttpGet httpGet = handleJgUrl(Constant.MQWGRQZQK, null, i);
                HttpResponse response = client.execute(httpGet);
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject jsonObject1 = JSONObject.parseObject(resultPage);
                    if (jsonObject1.getBoolean("success")) {
                        String rows1 = jsonObject1.getString("rows");
                        List<VisaFreeForeignerApply> visaFreeForeignerApplies = JSONObject.parseArray(rows1, VisaFreeForeignerApply.class);
                        mqwgrqzblqkService.saveOrUpdateBatch(visaFreeForeignerApplies);
                    }
                }
                httpGet.releaseConnection();
            }
        }
        log.info("执行END时间-{}", DateUtil.date());
    }

    @Scheduled(cron = "3 30 6 * * ?")
    public void scheduleFour() throws Exception {
        log.info("{}==执行START时间-{}",Constant.MQWGRYJ, DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQWGRYJ, null, 1);
        HttpResponse res = client.execute(get);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);

            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);
            if(total>0){
                baseCreateNewTableMapper.delTable("jg_mqwgr_warning");
            }
            for (int i=1;i<=total/200+1;i++){
                Thread.sleep(1000);
                HttpGet httpGet = handleJgUrl(Constant.MQWGRYJ, null, i);
                HttpResponse response = client.execute(httpGet);
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject jsonObject1 = JSONObject.parseObject(resultPage);
                    if (jsonObject1.getBoolean("success")) {
                        String rows = jsonObject1.getString("rows");
                        List<VisaFreePersonWarning> visaFreePersonWarnings = JSONObject.parseArray(rows, VisaFreePersonWarning.class);
                        mqwgryjService.saveOrUpdateBatch(visaFreePersonWarnings);
                    }
                }
                httpGet.releaseConnection();
            }
        }
        log.info("执行END时间-{}", DateUtil.date());
    }

    @Scheduled(cron = "4 40 6 * * ?")
    public void scheduleFive() throws Exception {
        log.info("{}==执行START时间-{}",Constant.MQWGRZDJZQK, DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQWGRZDJZQK, null, 1);
        HttpResponse res = client.execute(get);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);

            for (int i=1;i<=total/200+1;i++){
                Thread.sleep(1000);
                HttpGet httpGet = handleJgUrl(Constant.MQWGRZDJZQK, null, i);
                HttpResponse response = client.execute(httpGet);
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject jsonObject1 = JSONObject.parseObject(resultPage);
                    if (jsonObject1.getBoolean("success")) {
                        String rows = jsonObject1.getString("rows");
                        List<VisaFreePersonPutUpCondition> visaFreePersonPutUpConditions = JSONObject.parseArray(rows, VisaFreePersonPutUpCondition.class);
                        mqwgrzdjzqkService.saveOrUpdateBatch(visaFreePersonPutUpConditions);
                    }
                }
                httpGet.releaseConnection();
            }
        }
        log.info("执行END时间-{}", DateUtil.date());
    }


    @Scheduled(cron = "6 50 6 * * ?")
    public void scheduleSix() throws Exception {
        log.info("{}==执行START时间-{}",Constant.MQWGRYJSJ, DateUtil.date());
        HttpClient client = new SSLClient();
        HttpGet get = handleJgUrl(Constant.MQWGRYJSJ, null, 1);
        HttpResponse res = client.execute(get);
        int count = 0;
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer total = jsonObject.getInteger("total");
            log.info("总数---{}",total);
            if(total>0){
                baseCreateNewTableMapper.delTable("jg_mqwgr_warning_data");
            }
            for (int i=1;i<=total/200+1;i++){
                count=i;
                Thread.sleep(3000);
                HttpGet httpGet = handleJgUrl(Constant.MQWGRYJSJ, null, i);
                HttpResponse response = client.execute(httpGet);

                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entityPage = response.getEntity();
                    String resultPage = EntityUtils.toString(entityPage);
                    JSONObject objPage = JSONObject.parseObject(resultPage);
                    if (objPage.getBoolean("success")) {
                        String rows = objPage.getString("rows");
                        List<VisaFreeWarningData> visaFreeWarningData = JSONObject.parseArray(rows, VisaFreeWarningData.class);
                        mqwgryjsjService.saveBatch(visaFreeWarningData);
                    }
                }
                httpGet.releaseConnection();
            }
        }
        log.info("执行END时间-{},执行次数-{}", DateUtil.date(),count);
    }


    public HttpGet handleJgUrl(String qspBizId,String terms,int page){
        StringBuffer param = new StringBuffer();
        JSONArray parse = JSONArray.parseArray(terms);
        // 特殊字符转译
        String replace = JSONArray.toJSONString(parse).replace(" ","")
                .replace("\"", "%22")
                .replace("{", "%7b").replace("}", "%7d")
                .replace("[","%5B").replace("]","%5D");

        param.append(jgUrl).append("?")
                .append("qspBizId=").append(qspBizId).append("&")
                .append("terms=").append(replace).append("&")
                .append("page=").append(page);
        HttpGet get = new HttpGet(param.toString());

        get.addHeader("Content-type", "application/json; charset=utf-8");
        get.setHeader("Accept", "application/json");
        get.addHeader("XT_CODE", xtCode);
        get.addHeader("JYM", jym);
        return get;
    }
}
