package cn.com.taiji.dataService.task;


import cn.com.digitalhainan.apione.sdk.ContentBody;
import cn.com.taiji.dataService.utils.ResultHandle;
import cn.com.taiji.dataService.utils.StringProducer;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import cn.com.digitalhainan.apione.sdk.HttpCaller;
import cn.com.digitalhainan.apione.sdk.HttpParameters;
import cn.com.digitalhainan.apione.sdk.HttpReturn;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ScheduleTask {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @Resource
    private StringProducer producer;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 10 2 * * ?")
    //@Scheduled(initialDelay = 5000,fixedDelay = 60*60*1000)
    public void Schedule(){
        log.info("执行收寄件任务---{}",DateUtil.date());
        //原REDIS中的编号查询
        Set<String> keys = stringRedisTemplate.keys("ZWWW_" + "*");
        for (String key : keys) {
            String value = stringRedisTemplate.opsForValue().get(key);
            HttpReturn bReturn = connect(value, ak3, sk3, api3);
            JSONObject subObject = JSON.parseObject(bReturn.getResponse());
            JSONObject subObject1= JSON.parseObject(subObject.getString("data"));
            if(500==subObject1.getInteger("status")){
                stringRedisTemplate.opsForValue().set(key,value,25, TimeUnit.HOURS);
            }else {
                JSONArray data = JSON.parseArray(subObject1.getString("data"));
                data.stream().forEach(d->{
                    //结果推送kafka
                    producer.sendMessage(topic,d.toString());
                });
            }
        }
        String date = DateUtil.format(DateUtil.yesterday(), "YYYYMMdd");
        //打私办入参数据
        String contentJson = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://server.unimas.com/\"> <soapenv:Header/> <soapenv:Body> <ser:query> <in>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; &lt;search&gt; &lt;appname&gt;query193&lt;/appname&gt; &lt;limited&gt;100&lt;/limited&gt; &lt;conditions&gt; &lt;s1f1c1&gt;"+
                date+"&lt;/s1f1c1&gt; &lt;/conditions&gt; &lt;/search&gt;</in> </ser:query> </soapenv:Body>";
        //调用打私办接口，获取返回数据
        HttpReturn connect = connect(contentJson, ak1, sk1,api1);
        String response = connect.getResponse();
        JSONArray handle = ResultHandle.handle(response);

        if(handle == null){
            log.info(date+"日没有查询数据");
            return;
        }

        //获取打私办返回数据，组装邮政接口入参参数
        handle.stream().forEach(array->{

            com.alibaba.fastjson.JSONObject object = JSON.parseObject(array.toString());
            com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
            param.put("data",object.getString("JDJK_SEND.DATA"));
            param.put("dataType",object.getString("JDJK_SEND.DATETYPE"));
            param.put("type",object.getString("JDJK_SEND.TYPE"));
            param.put("operateOrg",object.getString("JDJK_SEND.OPERATEORG"));
            param.put("operator",object.getString("JDJK_SEND.OPERATOR"));
            param.put("photoName",object.getString("JDJK_SEND.PHOTONAME"));
            param.put("photo",object.getString("JDJK_SEND.PHOTO"));

            //快递寄件接口
            HttpReturn httpReturn = connect(param.toJSONString(), ak2, sk2, api2);
            System.out.println(httpReturn.getResponse());
            QueryData queryData = JSON.parseObject(httpReturn.getResponse(), QueryData.class);
            if("500".equals(queryData.getCode())){
                log.info("邮政接口调用失败--原因：{}",queryData.getMsg());
                return;
            }
            int queryNo = queryData.getData().getData().getQueryNo();
            com.alibaba.fastjson.JSONObject param3 = new com.alibaba.fastjson.JSONObject();
            param3.put("queryNo",queryNo);
            //寄件结果查询接口
            HttpReturn aReturn = connect(param3.toJSONString(), ak3, sk3, api3);
            String response1 = aReturn.getResponse();

            JSONObject jsonObject = JSON.parseObject(response1);
            JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
            //查询未审核状态则将信息存储到redis
            if(500==jsonObject1.getInteger("status")){
                stringRedisTemplate.opsForValue().set("ZWWW_JJ"+queryNo,param3.toJSONString(),25, TimeUnit.HOURS);
            }else {
                JSONArray data = JSON.parseArray(jsonObject1.getString("data"));
                data.stream().forEach(d->{
                    //结果推送kafka
                    producer.sendMessage(topic,d.toString());
                });
            }

            //快递收件接口协查函
            HttpReturn httpReturn4 = connect(param.toJSONString(), ak4, sk4, api4);
            System.out.println(httpReturn4.getResponse());
            QueryData queryData4 = JSON.parseObject(httpReturn4.getResponse(), QueryData.class);
            if("500".equals(queryData4.getCode())){
                log.info("邮政接口调用失败--原因：{}",queryData4.getMsg());
                return;
            }
            int queryNo4 = queryData4.getData().getData().getQueryNo();
            com.alibaba.fastjson.JSONObject param4 = new com.alibaba.fastjson.JSONObject();
            param4.put("queryNo",queryNo4);
            //收件接口结果查询
            HttpReturn aReturn4 = connect(param4.toJSONString(), ak5, sk5, api5);
            String response_sj = aReturn4.getResponse();

            JSONObject jsonObjectSj = JSON.parseObject(response_sj);
            JSONObject jsonObjectSjj = JSON.parseObject(jsonObjectSj.getString("data"));
            //查询未审核状态则将信息存储到redis
            if(500==jsonObjectSjj.getInteger("status")){
                stringRedisTemplate.opsForValue().set("ZWWW_SJ"+queryNo4,param4.toJSONString(),25, TimeUnit.HOURS);
            }else {
                JSONArray data = JSON.parseArray(jsonObjectSjj.getString("data"));
                data.stream().forEach(d->{
                    //结果推送kafka
                    producer.sendMessage("gjyzj_kdsjcxjgjk",d.toString());
                });
            }
        });

    }

    private HttpReturn connect(String contentJson,String ak,String sk,String api){
        //String region = "接口请求区域 INTRA(政务外网),INTER(政务互联网),PUBLIC(公网)";
        String region = "INTRA";
        String requestUrl = "https://api-one.digitalhainan.com.cn/apione";
        ContentBody contentBody = new ContentBody(contentJson);

        //拼装业务信息
        HttpParameters parameters = HttpParameters.builder()
                .api(api)
                .region(region)
                // 如果有query参数需要设置
                //.queryParamsMap(query)
                // 如果有path参数需要设置
                //.path(path)
                .accessKey(ak)
                .secretKey(sk)
                .contentBody(contentBody)
                .requestUrl(requestUrl)
                .build();

        // 请求服务接口，获取response
        HttpReturn call = HttpCaller.getInstance().call(parameters);

        return call;
    }

//    @Scheduled(cron = "0 0/1 * * * ?")
//    public void test(){
//        com.alibaba.fastjson.JSONObject param3 = new com.alibaba.fastjson.JSONObject();
//        param3.put("queryNo","110");
//        HttpReturn aReturn = connect(param3.toJSONString(), ak3, sk3, api3);
//
//        String response1 = aReturn.getResponse();
//
//        JSONObject jsonObject = JSON.parseObject(response1);
//        JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
//        JSONArray data = JSON.parseArray(jsonObject1.getString("data"));
//        data.forEach(d->{
//            //结果推送kafka
//            producer.sendMessage(topic,d.toString());
//        });
//    }

}
