package common;

import com.CWebApplication;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hai.common.QRCodeGenerator;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.IDGenerator;
import com.hai.entity.HighCouponCode;
import com.hai.entity.HighMerchantStore;
import com.hai.entity.HighOrder;
import com.hai.entity.SecRegion;
import com.hai.service.CommonService;

import com.hai.service.HighCouponCodeService;
import com.hai.service.HighMerchantStoreService;
import com.hai.service.HighOrderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

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

/**
 * @ClassName RegionTest
 * @Description: TODO ()
 * @Author 胡锐
 * @Date 2020/12/29
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CWebApplication.class)
@WebAppConfiguration
public class RegionTest {

    @Resource
    private CommonService commonService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;


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

    @Test
    public void addLogs() {
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("exampleWrite.json"),"UTF-8");
            List<Map<String,Object>> jobTypeList = new ArrayList<>();
            List<Map<String,Object>> children1;

            List<SecRegion> parentRegion = commonService.getCities();
            for (SecRegion parent : parentRegion) {
                Map<String,Object> map = new HashMap<>();
                map.put("value", parent.getRegionId());
                map.put("label", parent.getRegionName());

                // 查询二级
                List<SecRegion> chinRegion = commonService.getRegionsByParentId(parent.getRegionId());
                children1 = new ArrayList<>();
                for (SecRegion chin : chinRegion) {
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("value", chin.getRegionId());
                    map1.put("label", chin.getRegionName());
                    children1.add(map1);
                }

                map.put("children", children1);
                jobTypeList.add(map);
            }

            osw.write(JSON.toJSONString(jobTypeList));
            osw.flush();//清空缓冲区，强制输出数据
            osw.close();//关闭输出流
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void addLogs1(){
        try {
            highCouponCodeService.cnpcCallbackCouponCode("2021041201",new Date(), "南充");
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Test
    public void gQrCode(){
        try {

            List<String> list = new ArrayList<>();
            list.add("01ZCplFfrpgRKydlzGKNNW");
            list.add("0191TLwAwBB956jzWM3YIC");
            list.add("01n04fzTdsTpeKmayBZyAk");
            list.add("01c6xoP1tJyBRC2zaTUhuI");
            list.add("01lmjIWIENUfiD43bf4qN1");
            list.add("01D5rNSEoNnSBGjgXqKzLb");
            list.add("01FeU4TAvGE6GuIYj8CWSG");
            list.add("01WX7Wepav3IY9c1dM1480");
            list.add("01b2wl9RRbFr74KurfNs9D");
            list.add("01b0KC0vpZxUxyWybIldpA");
            list.add("013x24Ou0EZTGDUFUUoVJH");
            list.add("01NYmIdcTxXk8uTP2wlzxN");
            list.add("01DsyPN9QUvwL8YEEjhHK2");
            list.add("01Tf9T9zK3tiW157oxTluZ");
            list.add("01C5XMRbxA13KmQZdigYrQ");
            list.add("01IkkXn3fbBGmeBQGlie6N");
            list.add("01fiH3t7P1DahSTgnltE5C");
            list.add("015I6hBEIUB6UtJB1AJpTY");
            list.add("017Rsu81CAy2lgya5qCVYK");
            list.add("01bOsNk2KViUjrKr1sifdM");
            list.add("01UUd4bpXAPvhGSNPiVdgv");
            list.add("01YDIj4DWaRCvWcd0UPTl4");
            list.add("01CBiCaEPp1PXms8wAoXtL");
            list.add("01aSV8p1RtV11aQRv5HyEg");
            list.add("01XYud7OMwKAzzZJssHAxX");
            list.add("01AgLE01SiraWzvZmaAMQz");
            list.add("01M1vYhLl6gfrknCTmQjVo");
            list.add("01GWKsIOTQKIJk9xk9zlq3");
            list.add("01S3GkZAtcvgHGZzkK9je1");
            list.add("01l0yZxhNDjUTgBfNFpZ0N");
            list.add("01Tm7PE3wvu6S4PRQD0sez");
            list.add("01b0NrXyZ8FDSyPQtxOwKM");
            list.add("01V6FFylLgJX95uNNHxt5K");

            for(String code : list) {
                HighCouponCode salesCode = highCouponCodeService.getCouponCodeBySalesCode(code);
                if (salesCode != null){
                    // 生成二维码
                    String qrCodeImg = DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(10) +".png";
                    String qrCodeUrl = "G:/couponCode/" + qrCodeImg;
                    QRCodeGenerator.generateQRCodeImage(code, 350, 350, qrCodeUrl);
                    salesCode.setExt1(qrCodeImg);
                    highCouponCodeService.updateCouponCode(salesCode);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void test(){
        try {

            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("appId", "jsVpwDoHZfR2rrpjhA");
            tokenMap.put("appSecret", "R7yJjinikdPhOlTrVgmdS7cblWMMOf99zEJkfPgaTIoDtKGlX51JKueLV725a6S4");
            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");

                Map<String,Object> bodyMap = new HashMap<>();
                bodyMap.put("appId", "jsVpwDoHZfR2rrpjhA");
                bodyMap.put("pageNo", 1);
                bodyMap.put("pageSize", 10);
                bodyMap.put("startTime", "2021-3-31 00:00:00");
                bodyMap.put("endTime", "2021-3-31 23:00:00");
                //bodyMap.put("customerCode", "48464274");
                bodyMap.put("customerCode", "hAFO76ZqXmIqosNw3PTAP4wxGJTN7MPawSU0QFDzzNioLjKMEaVFDlNKRIQX6n0DgyoVMy170T0b13P8uUTAQsbk9UNRPFO5i0fWp1hHOhNdaaQ2BdC0WXQz5QQ5epyK");

                String signature = "hAFO76ZqXmIqosNw3PTAP4wxGJTN7MPawSU0QFDzzNioLjKMEaVFDlNKRIQX6n0DgyoVMy170T0b13P8uUTAQsbk9UNRPFO5i0fWp1hHOhNdaaQ2BdC0WXQz5QQ5epyK";

                Long date  = new Date().getTime();
                String sha256 = encodeBySHA256(signature + JSON.toJSONString(bodyMap) + date);

/*            Map<String,Object> headerMap = new HashMap<>();
            headerMap.put("token", token);
            headerMap.put("sign", sha256);
            headerMap.put("ts", date);*/
                //map2.put("sign", sha256);
                JSONObject object = HttpsUtils.doPost("https://app.zshcqsy.com/api-provider/sapapi/open/coupon/customerRedeemcodeList", JSON.toJSONString(bodyMap), token, sha256, date);
                System.out.println(JSON.toJSONString(object));
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

}
