package com.bweb.controller;

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.HighCouponCode;
import com.hai.entity.SecSinopecConfig;
import com.hai.service.HighCouponCodeService;
import com.hai.service.SecSinopecConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/25 22:40
 */
@RestController
@RequestMapping(value="/cnpc")
@Api(value="中石化数据接口")
public class CnpcController {

    private static Logger log = LoggerFactory.getLogger(CnpcController.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;

    @RequestMapping(value="/certification",method= RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "数据")
    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.set(Calendar.HOUR_OF_DAY, 1);
                instance.add(Calendar.MINUTE, -10);

                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());
                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");
                            HighCouponCode code = highCouponCodeService.getCouponCodeByKey(codeId);
                            if (code != null) {
                                code.setStoreName(nodeName);
                                highCouponCodeService.updateCouponCode(code);
                            }
                        } catch (Exception e) {
                            log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                        }
                    }
                }
                log.error(object.toJSONString());
            }
        }
    }

    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();
    }
}
