package com.malk.siku;

import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.siku.service.SikuService;
import com.malk.siku.service.SikuTaskService;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class SkTest {
    @Autowired
    private SikuTaskService sikuTaskService;

    @Autowired
    private SikuService sikuService;

    @Autowired
    private YDClient ydClient;

    @Test
    public void getSecret(){
        //每刻报销-测试环境
        /*String appCode="AP52Y01LHHTAP9";
        String appSecret="N4WuERLteAUPaWebnsHy";*/

        //每刻报销-生产环境
        String appCode="AP52RG1SCG8S6L";
        String appSecret="YFTbD2MviqUwztBTbMWd";

        //每刻云票-测试环境
        /*String appCode="AP53EP1SVDS1N9";
        String appSecret="qF4nm3nPnyXYcrWcr5jl";*/

        long timeMillis = System.currentTimeMillis();
        log.info("time：{}",timeMillis);

        String s = DigestUtils.sha256Hex(appSecret + ":" + appCode + ":" + timeMillis);
        log.info("s:{}",s);
    }

    @Test
    public void ssoGetToken(){
        //生成token所使用的java代码
        String ssoSecret = "EC52NRFQYEFIB5:h34BITN5HAtVMt82P9VvTRhFYpCXLgfo";//该秘钥获取路径“设置-安全设置-系统安全策略-SSO”（若无此入口，需项目经理在boss系统开通相关许可）
        long timestamp = System.currentTimeMillis();
        String userId = "HZ769";
        String token = DigestUtils.sha256Hex((ssoSecret + ":" + userId + ":" + timestamp).getBytes());

        System.out.println("timestamp:"+timestamp);
        System.out.println("token:"+token);
    }

    @Test
    public void test(){
        sikuTaskService.syncLoanManage();
    }

    //批量触发供应商推送每刻
    @Test
    public void test2() throws ParseException {
        String createTime = "2026-06-8 00:00:00";
        //createTime转换为时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(createTime);
        long timestamp = date.getTime(); // 毫秒时间戳

        List<Map> dataList = getYdFormDataList("FORM-A4B7986899BF42BE8E6B5B9BC85839484PTG", JSONObject.toJSONString(Arrays.asList(new YDSearch("createTime", timestamp, "创建时间", YDSearch.Type.DATE_FIELD, YDSearch.Operator.GE))), YDConf.FORM_QUERY.retrieve_list_all);

        /*List<Map> dataList = (List<Map>)(ydClient.queryData(YDParam.builder()
                .formUuid("FORM-A4B7986899BF42BE8E6B5B9BC85839484PTG")
                .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch("createTime",timestamp,"创建时间", YDSearch.Type.DATE_FIELD,YDSearch.Operator.GE))))
                .pageSize(100)
                .pageNumber(1)
                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData());*/

        for (Map data : dataList) {
            String formInstanceId = UtilMap.getString(data, "formInstanceId");

            Map<String, Object> map = UtilMap.map("formInstId, type", formInstanceId, "供应商");

            sikuService.saveTradingPartner(map);
        }


    }


    private List<Map> getYdFormDataList(String formUuid, String searchCondition, YDConf.FORM_QUERY formQuery) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew = ydClient.queryData(YDParam.builder().formUuid(formUuid)
                    .searchCondition(searchCondition)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), formQuery);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }

    //java md5算法
    public static String md5(String plainText)
    {
        byte[] secretBytes = null;
        try {
            MessageDigest md  = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes("utf-8"));
            secretBytes = md.digest();
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("no such algorithm！");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }


        String md5code = new BigInteger(1, secretBytes).toString(16);
        int length = md5code.length();
        for (int i = 0; i < 32 - length; i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
    //java sha256算法
    public static String sha256Hex(String input) {
        try {
            // 创建一个MessageDigest实例，并指定使用SHA-256算法
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将输入字符串转换为字节数组，并更新摘要
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String genSign(HashMap<String, String> params, String signKey, Integer signMethod)
    {
        params.put("sign_key", signKey);
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(params.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue().trim();
                    if (result == "") {
                        result += key + "=" + val;
                    } else {
                        result += "&" + key + "=" + val;
                    }
                }
            }
            //System.out.println(result);
        } catch(Exception e) {
            throw new RuntimeException("error");
        }
        if(signMethod == 1) {
            return sha256Hex(result);
        }
        return md5(result);
    }

    public static void main (String[] args) throws java.lang.Exception {
        long l = System.currentTimeMillis() / 1000;

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("client_id", "3295ee5021a0dd6436d18f56e7c761c6");
        map.put("client_secret", "fe5539d17722035cba70a2e6220c43a4");
        map.put("grant_type", "client_credentials");
        map.put("phone", "18857526310");
        long currentTimeMillis = System.currentTimeMillis();
        map.put("timestamp", currentTimeMillis+"");

        String signKey = "038bD3BAb4a25D84dc96";
        Integer signMethod = 0;
        String sign = genSign(map, signKey, signMethod);
        System.out.println("sign:"+sign);
        System.out.println("timestamp:"+currentTimeMillis);
    }




}
