package com.hai.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.entity.HighOrder;
import com.hai.entity.SecSinopecConfig;
import com.hai.service.HighCouponCodeService;
import com.hai.service.SecSinopecConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description: 同步中石化接口
 * @Date: 2021/3/31 23:49
 */
@Configuration
public class SynchronizeCNPC {

    private static Logger log = LoggerFactory.getLogger(SynchronizeCNPC.class);

    private static final String[] HEX_DIGITS = {"0" ,"1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private SecSinopecConfigService secSinopecConfigService;

    @Scheduled(cron="0 0/5 * * * ?")   //每5分钟执行一次
    public void certification() {

        List<SecSinopecConfig> sinopecConfig = secSinopecConfigService.getListSinopecConfig(new HashMap<>());
        for (SecSinopecConfig config : sinopecConfig) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("appId", config.getAppId());
            tokenMap.put("appSecret", config.getAppSecret());
            JSONObject jsonObject = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/api/open/merchant/token", JSON.toJSONString(tokenMap));
            log.error(jsonObject.toJSONString());

            if (jsonObject != null && jsonObject.getBoolean("success") == true) {
                JSONObject data = jsonObject.getJSONObject("data");
                String token = data.getString("token");

                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.MINUTE, -15);

                Map<String,Object> bodyMap = new HashMap<>();
                bodyMap.put("appId", config.getAppId());
                bodyMap.put("pageNo", 1);
                bodyMap.put("pageSize", 5000);
                bodyMap.put("startTime", instance.getTime());
                bodyMap.put("endTime", new Date());
                bodyMap.put("customerCode", config.getCode());

                Long date  = new Date().getTime();
                String sha256 = encodeBySHA256(config.getSignkey() + JSON.toJSONString(bodyMap) + date);
                JSONObject object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);

                //JSONObject object = JSONObject.parseObject("{\"code\":1000,\"data\":{\"pageNo\":1,\"pageSize\":100,\"rowCount\":\"2\",\"list\":[{\"nodeName\":\"中国石油化工股份有限公司重庆江南石油分公司大学城南二路加油加\",\"totalAmount\":150.00,\"codeId\":\"01DIhbtPzIghPP0mPWaWzO13\",\"nodeNo\":\"50000105\",\"name\":\"重庆惠昕石化有限责任公司11.02日150元券\",\"useTime\":\"2021-04-03 06:11:14\"},{\"nodeName\":\"中国石化销售有限公司重庆三峡分公司忠县经营部三台加油站\",\"totalAmount\":100.00,\"codeId\":\"201126141728001027\",\"nodeNo\":\"50000238\",\"name\":\"重庆惠昕石化有限责任公司11.26日100元券\",\"useTime\":\"2021-04-03 15:16:03\"}]},\"success\":true}");

                if(Objects.equals(object.get("success"), true)) {
                    log.error(JSONObject.toJSONString(object.get("data")));

                    Object dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                    JSONObject dataObject = JSON.parseObject(JSONObject.toJSONString(dataJson));
                    JSONArray list = dataObject.getJSONArray("list");
                    for (Object dataJsonObject : list) {
                        try {
                            JSONObject parseObject = JSON.parseObject(JSON.toJSONString(dataJsonObject));
                            String codeId = parseObject.getString("codeId");
                            String nodeName = parseObject.getString("nodeName");
                            Date useTime = DateUtil.format(parseObject.getString("useTime"), "yyyy-MM-dd HH:mm:ss");
                            highCouponCodeService.cnpcCallbackCouponCode(codeId, useTime, nodeName);
                        } catch (Exception e) {
                            log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                        }
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 0 4 * * ?")   // 每4小时0执行一次
    public void certification2() {

        List<SecSinopecConfig> sinopecConfig = secSinopecConfigService.getListSinopecConfig(new HashMap<>());
        for (SecSinopecConfig config : sinopecConfig) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("appId", config.getAppId());
            tokenMap.put("appSecret", config.getAppSecret());
            JSONObject jsonObject = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/api/open/merchant/token", JSON.toJSONString(tokenMap));
            log.error(jsonObject.toJSONString());

            if (jsonObject != null && jsonObject.getBoolean("success") == true) {
                JSONObject data = jsonObject.getJSONObject("data");
                String token = data.getString("token");

                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.HOUR_OF_DAY, -6);

                Map<String,Object> bodyMap = new HashMap<>();
                bodyMap.put("appId", config.getAppId());
                bodyMap.put("pageNo", 1);
                bodyMap.put("pageSize", 5000);
                bodyMap.put("startTime", instance.getTime());
                bodyMap.put("endTime", new Date());
                bodyMap.put("customerCode", config.getCode());

                Long date  = new Date().getTime();
                String sha256 = encodeBySHA256(config.getSignkey() + JSON.toJSONString(bodyMap) + date);
                JSONObject object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);

                //JSONObject object = JSONObject.parseObject("{\"code\":1000,\"data\":{\"pageNo\":1,\"pageSize\":100,\"rowCount\":\"2\",\"list\":[{\"nodeName\":\"中国石油化工股份有限公司重庆江南石油分公司大学城南二路加油加\",\"totalAmount\":150.00,\"codeId\":\"01DIhbtPzIghPP0mPWaWzO13\",\"nodeNo\":\"50000105\",\"name\":\"重庆惠昕石化有限责任公司11.02日150元券\",\"useTime\":\"2021-04-03 06:11:14\"},{\"nodeName\":\"中国石化销售有限公司重庆三峡分公司忠县经营部三台加油站\",\"totalAmount\":100.00,\"codeId\":\"201126141728001027\",\"nodeNo\":\"50000238\",\"name\":\"重庆惠昕石化有限责任公司11.26日100元券\",\"useTime\":\"2021-04-03 15:16:03\"}]},\"success\":true}");

                if(Objects.equals(object.get("success"), true)) {
                    log.error(JSONObject.toJSONString(object.get("data")));

                    Object dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                    JSONObject dataObject = JSON.parseObject(JSONObject.toJSONString(dataJson));
                    JSONArray list = dataObject.getJSONArray("list");
                    for (Object dataJsonObject : list) {
                        try {
                            JSONObject parseObject = JSON.parseObject(JSON.toJSONString(dataJsonObject));
                            String codeId = parseObject.getString("codeId");
                            String nodeName = parseObject.getString("nodeName");
                            Date useTime = DateUtil.format(parseObject.getString("useTime"), "yyyy-MM-dd HH:mm:ss");
                            highCouponCodeService.cnpcCallbackCouponCode(codeId, useTime, nodeName);
                        } catch (Exception e) {
                            log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                        }
                    }
                }
            }
        }
    }

    /*@Scheduled(cron="0 0/1 * * * ?")   //每5分钟执行一次
    public void certification3(){
        List<SecSinopecConfig> sinopecConfig = secSinopecConfigService.getListSinopecConfig(new HashMap<>());
        for (SecSinopecConfig config : sinopecConfig) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("appId", config.getAppId());
            tokenMap.put("appSecret", config.getAppSecret());
            JSONObject jsonObject = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/api/open/merchant/token", JSON.toJSONString(tokenMap));

            if (jsonObject != null && jsonObject.getBoolean("success") == true) {
                JSONObject data = jsonObject.getJSONObject("data");
                String token = data.getString("token");

                Calendar instance = Calendar.getInstance();
                instance.set(Calendar.MONTH, 9);
                instance.set(Calendar.DAY_OF_MONTH, 9);
                instance.set(Calendar.HOUR_OF_DAY, 00);
                instance.set(Calendar.MINUTE, 00);
                instance.set(Calendar.SECOND, 00);
                //instance.add(Calendar.MINUTE, -15);

                Calendar endTime = Calendar.getInstance();
                endTime.set(Calendar.MONTH, 9);
                endTime.set(Calendar.DAY_OF_MONTH, 9);
                endTime.set(Calendar.HOUR_OF_DAY, 23);
                endTime.set(Calendar.MINUTE, 59);
                endTime.set(Calendar.SECOND, 59);

                Map<String,Object> bodyMap = new HashMap<>();
                bodyMap.put("appId", config.getAppId());
                bodyMap.put("pageNo", 1);
                bodyMap.put("pageSize", 10000);
                bodyMap.put("startTime", instance.getTime());
                bodyMap.put("endTime", new Date().getTime());
                bodyMap.put("customerCode", config.getCode());

                Long date  = new Date().getTime();
                String sha256 = encodeBySHA256(config.getSignkey() + JSON.toJSONString(bodyMap) + date);
                JSONObject object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);
                System.out.println(object.toJSONString());
                //JSONObject object = JSONObject.parseObject("{\"code\":1000,\"data\":{\"pageNo\":1,\"pageSize\":100,\"rowCount\":\"2\",\"list\":[{\"nodeName\":\"中国石油化工股份有限公司重庆江南石油分公司大学城南二路加油加\",\"totalAmount\":150.00,\"codeId\":\"01DIhbtPzIghPP0mPWaWzO13\",\"nodeNo\":\"50000105\",\"name\":\"重庆惠昕石化有限责任公司11.02日150元券\",\"useTime\":\"2021-04-03 06:11:14\"},{\"nodeName\":\"中国石化销售有限公司重庆三峡分公司忠县经营部三台加油站\",\"totalAmount\":100.00,\"codeId\":\"201126141728001027\",\"nodeNo\":\"50000238\",\"name\":\"重庆惠昕石化有限责任公司11.26日100元券\",\"useTime\":\"2021-04-03 15:16:03\"}]},\"success\":true}");

                if(Objects.equals(object.get("success"), true)) {
                    Object dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                    JSONObject dataObject = JSON.parseObject(JSONObject.toJSONString(dataJson));
                    JSONArray list = dataObject.getJSONArray("list");
                    for (Object dataJsonObject : list) {
                        try {
                            JSONObject parseObject = JSON.parseObject(JSON.toJSONString(dataJsonObject));
                            String codeId = parseObject.getString("codeId");
                            String nodeName = parseObject.getString("nodeName");
                            Date useTime = DateUtil.format(parseObject.getString("useTime"), "yyyy-MM-dd HH:mm:ss");
                            highCouponCodeService.cnpcCallbackCouponCode(codeId, useTime, nodeName);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    }*/

   /* @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void certification3() {

        List<SecSinopecConfig> sinopecConfig = secSinopecConfigService.getListSinopecConfig(new HashMap<>());
        for (SecSinopecConfig config : sinopecConfig) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("appId", config.getAppId());
            tokenMap.put("appSecret", config.getAppSecret());
            JSONObject jsonObject = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/api/open/merchant/token", JSON.toJSONString(tokenMap));
            log.error(jsonObject.toJSONString());

            if (jsonObject != null && jsonObject.getBoolean("success") == true) {
                JSONObject data = jsonObject.getJSONObject("data");
                String token = data.getString("token");

                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.DAY_OF_MONTH, -1);
                instance.set(Calendar.HOUR_OF_DAY, 00);
                instance.set(Calendar.MINUTE, 00);
                instance.set(Calendar.SECOND, 00);

                Map<String,Object> bodyMap = new HashMap<>();
                bodyMap.put("appId", config.getAppId());
                bodyMap.put("pageNo", 1);
                bodyMap.put("pageSize", 5000);
                bodyMap.put("startTime", instance.getTime());
                bodyMap.put("endTime", new Date());
                bodyMap.put("customerCode", config.getCode());

                Long date  = new Date().getTime();
                String sha256 = encodeBySHA256(config.getSignkey() + JSON.toJSONString(bodyMap) + date);
                JSONObject object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);

                //JSONObject object = JSONObject.parseObject("{\"code\":1000,\"data\":{\"pageNo\":1,\"pageSize\":100,\"rowCount\":\"2\",\"list\":[{\"nodeName\":\"中国石油化工股份有限公司重庆江南石油分公司大学城南二路加油加\",\"totalAmount\":150.00,\"codeId\":\"01DIhbtPzIghPP0mPWaWzO13\",\"nodeNo\":\"50000105\",\"name\":\"重庆惠昕石化有限责任公司11.02日150元券\",\"useTime\":\"2021-04-03 06:11:14\"},{\"nodeName\":\"中国石化销售有限公司重庆三峡分公司忠县经营部三台加油站\",\"totalAmount\":100.00,\"codeId\":\"201126141728001027\",\"nodeNo\":\"50000238\",\"name\":\"重庆惠昕石化有限责任公司11.26日100元券\",\"useTime\":\"2021-04-03 15:16:03\"}]},\"success\":true}");

                if(Objects.equals(object.get("success"), true)) {
                    log.error(JSONObject.toJSONString(object.get("data")));

                    Object dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                    JSONObject dataObject = JSON.parseObject(JSONObject.toJSONString(dataJson));
                    JSONArray list = dataObject.getJSONArray("list");
                    for (Object dataJsonObject : list) {
                        try {
                            JSONObject parseObject = JSON.parseObject(JSON.toJSONString(dataJsonObject));
                            String codeId = parseObject.getString("codeId");
                            String nodeName = parseObject.getString("nodeName");
                            Date useTime = DateUtil.format(parseObject.getString("useTime"), "yyyy-MM-dd HH:mm:ss");
                            highCouponCodeService.cnpcCallbackCouponCode(codeId, useTime, nodeName);
                        } catch (Exception e) {
                            log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                        }
                    }
                }
            }
        }
    }*/


    public String encodeBySHA256(String str) {
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            return getFormattedText(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    private String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j=0;j<len;j++){
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

}
