package com.ms.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.doudian.open.api.supplyCenter_cargo_detail.data.SupplyCenterCargoDetailData;
import com.doudian.open.api.supplyCenter_cargo_detail.param.SupplyCenterCargoDetailParam;
import com.jinritemai.cloud.base.api.BaseResponse;
import com.jinritemai.cloud.base.core.util.AuthThreadLocalUtil;
import com.ms.api.dto.common.DoudianMessage;
import com.ms.api.dto.dsapi.response.CheckDsAppAuthExpireResponseDTO;
import com.ms.api.dto.dsapi.response.GetAuthInfoResponseDTO;
import com.ms.api.dto.dsapi.response.GetAuthShopMemberInfosResponseDTO;
import com.ms.api.dto.dsapi.response.GetSourceItemInfosResponseDTO;
import com.ms.api.dto.dsorder.AlibabaMessage;
import com.ms.biz.common.R;
import com.ms.biz.common.Ret;
import com.ms.api.dto.dsorder.DsMessageCallbackDTO;
import com.ms.biz.dto.openspi.request.BatchCreateParam;
import com.ms.biz.dto.openspi.request.BatchPayParam;
import com.ms.biz.dto.openspi.response.BatchCreateData;
import com.ms.biz.dto.openspi.response.BatchPayData;
import com.ms.biz.dto.openspi.response.QuerySupplyPlatformAuthData;
import com.ms.biz.service.*;
import com.ms.biz.tool.CommonTool;
import com.ms.biz.tool.SecurityTool;
import com.ms.biz.util.DDApi;
import com.ms.dal.entity.DsMessageConsumerQueue;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.Serializable;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: laixw
 * @Date: 2023/8/22
 */
@Slf4j
@RestController
public class Test {

    @Autowired
    private ShopService shopService;

    @Autowired
    private DsMessageService dsMessageService;

    @Autowired
    private DsApiService dsApiService;

    @Autowired
    private LogisticsService logisticsService;

    @Autowired
    private DistributionOrderService distributionOrderService;

    @Autowired
    private DsMessageConsumerQueueService dsMessageConsumerQueueService;

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }

    class Aes
    {
        private String key;

        public Aes(String key)
        {
            this.key = key;
        }

        /**
         * @param context
         * @return byte[]
         * @throws Exception
         */
        public byte[] encode(String context) throws Exception
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            return cipher.doFinal(context.getBytes("utf8"));
        }

        public String decode(byte[] encryptBytes) throws Exception
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes, "UTF-8");
        }
    }

    public static void main(String[] args) throws ParseException {
        String dd = "{\"msgType\": \"ORDER_BUYER_VIEW_ORDER_BUYER_REFUND_IN_SALES\",\"msgData\":{\"buyerMemberId\":\"b2b-2216888144113f9b08\",\"currentStatus\":\"refundsuccess\",\"orderId\":3643602985932141341,\"refundAction\":\"SELLER_AGREE_REFUND\",\"sellerMemberId\":\"b2b-22103074731230f732\",\"msgSendTime\":\"2023-11-23 17:48:34\",\"operator\":\"system\",\"refundId\":\"TQ246736332522144113\"}}";
        AlibabaMessage msg= JSONObject.parseObject(dd, AlibabaMessage.class);
        System.out.println(msg.getMsgData().get("buyerMemberId"));

        Long shopId = 111111111L;
        String shopName = SecurityTool.MD5(shopId.toString());
        assert shopName != null;
        shopName = shopName.substring(16);
        System.out.println("店铺[" + shopName + "]");

        Long value = 1L;
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddhhmm00");

        System.out.println(dateFormat1.format(date) + String.format("%1$04d", value));

        String d = "{\"orders\":[{\"pur_order_id\":\"7299756498531418412\",\"order_id\":\"6917543139367389081\",\"post_address\":{\"province\":{\"id\":\"11\",\"name\":\"北京市\"},\"city\":{\"id\":\"110000\",\"name\":\"北京市\"},\"town\":{\"id\":\"110108\",\"name\":\"海淀区\"},\"street\":{\"id\":\"110108012\",\"name\":\"海淀街道\"},\"encrypt_detail\":\"MC8EEAjx7GdmeypB6WkV9DrpH9sEGWv8lSI1N1i9SaxcxKw1aW4waq481ueqVRcEAA==\",\"post_tel\":\"MCEEEDyPE4U3H7NDrnVhSgGOPzsEC9mVHEzJYMyY91uJBAA=\",\"post_receiver\":\"MCgEEHlttu0OuRqxJ3AaFAEvpr8EEjMU+9kRHPkU+MiXyD4zIkdVMgQA\"},\"mask_post_address\":{\"province\":{\"id\":\"11\",\"name\":\"北京市\"},\"city\":{\"id\":\"110000\",\"name\":\"北京市\"},\"town\":{\"id\":\"110108\",\"name\":\"海淀区\"},\"street\":{\"id\":\"110108012\",\"name\":\"海淀街道\"},\"detail\":\"互联*******\",\"post_tel\":\"1********00\",\"post_receiver\":\"电*****\"},\"sku_orders\":[{\"pur_sku_order_id\":\"7299756498531451180\",\"sku_order_id\":\"6917543139367389081\",\"cargo_id\":3649687424122130945,\"cargo_sku_id\":3659175936152832,\"product_id\":3649883085652281308,\"sku_id\":3659175955997568,\"num\":1,\"outer_product_id\":\"686872273204\",\"outer_sku_id\":\"4897420288982\"}]}],\"shop_id\":1111502210}";
        System.out.println(JSON.parseObject(d));
        QuerySupplyPlatformAuthData data = new QuerySupplyPlatformAuthData();
        data.setAuthUrl("abc");
        data.setAuthorized(false);
        System.out.println(JSON.toJSONString(data));
        System.out.println(JSON.parseObject(JSON.toJSONString(data)));

        String str = "{\"data\":\"{\\\"activity_id\\\":\\\"0\\\",\\\"after\\\":\\\"false\\\",\\\"before\\\":\\\"true\\\",\\\"channel_id\\\":\\\"0\\\",\\\"channel_type\\\":0,\\\"process_time\\\":1699455945,\\\"product_id\\\":\\\"3649553844716833566\\\",\\\"shop_id\\\":\\\"121233657\\\",\\\"sku_id\\\":\\\"3384401776121602\\\"}\",\"tag\":\"420\",\"msg_id\":\"66533861744835594630:0:420:1699455945:2560971988:7264840234423027259\"}";
        DoudianMessage msg1 = JSON.parseObject(str, DoudianMessage.class);
        System.out.println(msg1);

        System.out.println(Double.valueOf(CommonTool.doubleTrans(CommonTool.noZeros(2.00d))));
        System.out.println("ni号顺11".length());
        System.out.println("ni号顺11".substring(0, 6));
        try {
            System.out.println(CommonTool.mbSubString("你12324好是的3423423发生45345率的4353发生3453率胜453多负少", 10));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        Pattern p = Pattern.compile("^([T|W])(JT\\d+)$");
        Matcher m = p.matcher("WJT23242342342342");
        if (m.find()) {
            System.out.println(m.group(2));
        }
        System.out.println("TTabc".replaceAll("^T", ""));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println(sdf.parse("2023-09-15 09:50:56"));
        System.out.println(DateUtils.parseDate("2023-09-15 09:50:56", new String[]{"yyyy-MM-dd HH:mm:ss"}));
    }

    public void go()
    {
        Base64.Encoder encode = Base64.getEncoder();
        Base64.Decoder decoder = Base64.getDecoder();

        // 实例化 aes类
        Aes aes = new Aes("D2E31857FB4C4C9439EDED69F5A85775");
        try {
            // 需要加密字符串
            String context = "{\"nihao\": 1122}";
            byte[] aesByte = aes.encode(context);
            // 将ase_encode的结果base64_encode处理
            String aesString = encode.encodeToString(aesByte);
            System.out.println(aesString);

            //将加密后的字符串先base64_decode处理
            aesByte = decoder.decode(aesString);
            //解密
            String desString = aes.decode(aesByte);
            System.out.println(desString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/dsMessageCallback")
    public BaseResponse<Ret> dsMessageCallback(@RequestBody DsMessageCallbackDTO request) {
        try {
            log.info("receive callback: " + JSON.toJSONString(request));
            dsMessageService.addDsMessage(request.getShopId(), request.getPlatformPushMsgId(), request.getBizId(), request.getBizType(), request.getData());
            return R.ok(CommonTool.successResult());
        } catch (RuntimeException e) {
            return R.ok(Ret.fail(e.getMessage()));
        }
    }

    @RequestMapping("/getAuthInfo")
    public String getAuthInfo() { // 30459766L
        GetAuthInfoResponseDTO responseDTO = dsApiService.getAuthInfo(1111502210L);
        System.out.println(responseDTO);
        return "";
    }

    @RequestMapping("/getAuthShopMemberInfos")
    public String getAuthShopMemberInfos() {
        GetAuthShopMemberInfosResponseDTO responseDTO = dsApiService.getAuthShopMemberInfos(117233105L);
        System.out.println(responseDTO);
        return "";
    }

    @RequestMapping("/checkDsAppAuthExpire")
    public String checkDsAppAuthExpire() {
        CheckDsAppAuthExpireResponseDTO responseDTO = dsApiService.checkDsAppAuthExpire(1111502210L, "", "");
        System.out.println(responseDTO);
        return "";
    }
    @RequestMapping("/getProductDetail")
    public String getProductDetail() {
        AuthThreadLocalUtil.set("4463798");
        SupplyCenterCargoDetailParam supplyCenterCargoDetailParam = new SupplyCenterCargoDetailParam();
        supplyCenterCargoDetailParam.setProductId("3649131517940261457");
        SupplyCenterCargoDetailData supplyCenterCargoDetailData = DDApi.supplyCenterCargoDetail(supplyCenterCargoDetailParam);
        System.out.println(supplyCenterCargoDetailData);
        return "";
    }

    @RequestMapping("/getSourceItemInfos")
    public String getSourceItemInfos() {
        GetSourceItemInfosResponseDTO responseDTO = dsApiService.getSourceItemInfos(30459766L, Collections.singletonList("601601136855"));
        System.out.println(responseDTO);
        return "";
    }

    @RequestMapping("/batchCreate")
    public String batchCreate() {
        String d = "{\"orders\":[{\"mask_post_address\":{\"city\":{\"id\":\"330100\",\"name\":\"杭州市\"},\"detail\":\"余杭*路****\",\"post_receiver\":\"淡\",\"post_tel\":\"1********80\",\"province\":{\"id\":\"33\",\"name\":\"浙江省\"},\"street\":{\"id\":\"3301100120000\",\"name\":\"仓前街道\"},\"town\":{\"id\":\"3301100000000\",\"name\":\"余杭区\"}},\"order_id\":\"6923971910449173607\",\"post_address\":{\"city\":{\"id\":\"330100\",\"name\":\"杭州市\"},\"detail\":\"\",\"encrypt_detail\":\"#iyvDRxlWwsSVIGFpTvXG8xnTMrr4#0EtDPSnclpuXoe4cm9PbGRty29BV638tB3sFW50AH8OSuPE1ez4Ckx9S/5oMxilA+OD0fjDbZoer9ypQtxco+kQKx3U6UAw5ySHXuhSOWUEJDxW1eFOV7k2d9DA=*CgwIARCtHBiqICABKAESPgo87zzg3pjRu02NeG4BjIGzZe+xlXTWJqwX/uZ+ngz1LQn5f1fl4pkHOiFAMuZIl4p+Qzy+jG980ovJAiujGgA=#1##\",\"encrypt_post_receiver\":\"#cb9d#9+7ttEli8WI2+7/UyWgbyzHraoj2ol4gx0Wbux9bC21dtYFfxia7c4exWu+RFMOuFAIyKDSAHJm7h5IG4vp3Q6Ntk81t6/4=*CgwIARCtHBiqICABKAESPgo8zZOgfQVdyAFIjGLYlmVRDEm4k25w7b7uff7z6VK1W0QlHcHqXveuc2wL7VoD76BnqgT0C6UY3l2iqalzGgA=#1##\",\"encrypt_post_tel\":\"$o+GrGJidM5c0VEWIKPfzwjrgJJvnyAnBCrKy42/Puig=$HprTzY87R1gt1KIokYLexHyyImj2u85Vks+tb+cEe0HMKNXVLLB2lntDryhEN9K9rkhqU/sLcphmUSJiehCvZSIWXVJLlS3wlQ/y0/2ZFQ==*CgwIARCtHBiqICABKAESPgo8n3VNtx3wRxnHSK3rFN1837emZrTzKeL0GZKc/0ADgVOf8MuBRCNv4fedNyYFKOvIbIstKZsF0gm563L7GgA=$1$$\",\"post_receiver\":\"\",\"post_tel\":\"\",\"province\":{\"id\":\"33\",\"name\":\"浙江省\"},\"street\":{\"id\":\"3301100120000\",\"name\":\"仓前街道\"},\"town\":{\"id\":\"3301100000000\",\"name\":\"余杭区\"}},\"pur_order_id\":\"7303881914703020288\",\"sku_orders\":[{\"cargo_id\":3651912428658262186,\"cargo_sku_id\":3386515436144898,\"num\":2,\"outer_product_id\":\"712130508984\",\"outer_sku_id\":\"4987755988437\",\"product_id\":3651940874226638524,\"pur_sku_order_id\":\"7303881914703036672\",\"sku_id\":3386515436145410,\"sku_order_id\":\"6923971910449173607\"}]}],\"shop_id\":77977}";
        BatchCreateParam param = JSON.parseObject(d, BatchCreateParam.class);
        BatchCreateData data = new BatchCreateData();
        distributionOrderService.batchCreate(param, data);
        System.out.println(data);
        return "";
    }

    @RequestMapping("/batchPay")
    public String batchPay() {
        String d = "{\"params\":{\"pur_order_id\":\"7299756498531418412\"},\"shop_id\":1111502210}";
        BatchPayParam param = JSON.parseObject(d, BatchPayParam.class);
        BatchPayData data = new BatchPayData();
        distributionOrderService.batchPay(param, data);
        return "";
    }

    @RequestMapping("/moveMsg")
    public String moveMsg() {
        dsMessageConsumerQueueService.moveBufferToSolidRedisQueue(2000);
        return "";
    }

    @RequestMapping("/consumeMsg")
    public String consumeMsg() {
        DsMessageConsumerQueue queue = dsMessageConsumerQueueService.lockSolidRedisQueue(0L, false);
        dsMessageService.processDsMessage(queue.getDsMessageId());
        return "";
    }

    @GetMapping("/match-rule")
    public String matchRule() {
        Map<String, String> result = logisticsService.matchLogisticsInfo("1688DS", "顺丰速运", "SF1610042925672", null);
        System.out.println(result);
        return result.toString();
    }
}
