package com.hai.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.WxUtils;
import com.hai.config.*;
import com.hai.dao.HighGasOrderPushMapper;
import com.hai.entity.*;
import com.hai.model.HighMerchantModel;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.ResponseData;
import com.hai.model.ResultProfitSharing;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/26 23:08
 */
@Controller
@RequestMapping(value = "/test")
@Api(value = "订单接口")
public class HighTestController {

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

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighGasOilPriceService highGasOilPriceService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighProfitSharingRecordService highProfitSharingRecordService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;

    @Resource
    private UnionPayConfig unionPayConfig;

    @Resource
    private SecSinopecConfigService secSinopecConfigService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @RequestMapping(value = "/synchronizeCNPC", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "同步重庆中石化")
    public ResponseData synchronizeCNPC(HttpServletRequest request) {


            List<SecSinopecConfig> sinopecConfigList = secSinopecConfigService.getListSinopecConfig(new HashMap<>());
            for (SecSinopecConfig config : sinopecConfigList) {
                try {
                    String token = getCnpcToken(config.getAppId(), config.getAppSecret());
                    if (token != null) {
                        Calendar instance = Calendar.getInstance();
                        instance.set(Calendar.YEAR, 2021);
                        instance.set(Calendar.MONTH, 9);
                        instance.set(Calendar.DATE, 1);
                        instance.set(Calendar.MINUTE, 00);
                        instance.set(Calendar.SECOND, 00);
                        instance.set(Calendar.MILLISECOND, 00);

                        Map<String,Object> bodyMap = new HashMap<>();
                        bodyMap.put("appId", config.getAppId());
                        bodyMap.put("pageNo", 1);
                        bodyMap.put("pageSize", 1000);
                        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);
                        if(Objects.equals(object.get("success"), true)) {
                            Object dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                            JSONObject dataObject = JSON.parseObject(JSONObject.toJSONString(dataJson));

                            // 总页数
                            int rowPageCount =  new BigDecimal(dataObject.getString("rowCount")).divide(new BigDecimal("100"), 0, BigDecimal.ROUND_UP).intValue();
                            for (int i = 1; i < rowPageCount;i++) {
                                token = getCnpcToken(config.getAppId(), config.getAppSecret());

                                bodyMap.clear();
                                bodyMap.put("appId", config.getAppId());
                                bodyMap.put("pageNo", i);
                                bodyMap.put("pageSize", 1000);
                                bodyMap.put("startTime", instance.getTime());
                                bodyMap.put("endTime", new Date());
                                bodyMap.put("customerCode", config.getCode());

                                Long date2 = new Date().getTime();
                                sha256 = encodeBySHA256(config.getSignkey() + JSON.toJSONString(bodyMap) + date);
                                object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);
                                if (Objects.equals(object.get("success"), true)) {
                                    dataJson = JSONObject.parse(JSONObject.toJSONString(object.get("data")));
                                    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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("HighUserCardController --> oilCardRefund() error!", e);
                    return ResponseMsgUtil.exception(e);
                }
            }
            return ResponseMsgUtil.success(null);
    }

    private String getCnpcToken(String appId,String appSecret) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("appId", appId);
        tokenMap.put("appSecret", appSecret);
        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");
            return token;
        }
        return null;
    }

    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 static final String[] HEX_DIGITS = {"0" ,"1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
    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();
    }

}
