package com.xhpc.evcs.api;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.common.domain.Requirement;
import com.xhpc.evcs.cdjgpc.dto.CDEquipAuthRequest;
import com.xhpc.evcs.cdjgpc.dto.CDRequirementInfo;
import com.xhpc.evcs.cdjgpc.dto.CDRequirementInfoList;
import com.xhpc.evcs.cdjgpc.dto.CDTaskInfo;
import com.xhpc.evcs.cwj.dto.CWJPageRequest;
import com.xhpc.evcs.cwj.dto.CWJStartChargeRequest;
import com.xhpc.evcs.dto.*;
import com.xhpc.evcs.encryption.Aes128Cbc;
import com.xhpc.evcs.encryption.CryptoMngr;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.encryption.HMAC;
import com.xhpc.evcs.utils.JSONUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@RestController()
public class CheckChargeOrderController {

    /**
     * 推送订单核对结果信息
     * @param commonRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/v1/check_charge_orders")
    public CommonResponse check_charge_orders(@RequestBody CommonRequest<CheckChargeOrderRequestData> commonRequest) throws IOException {
        //todo 正在开发
        String operatorID = commonRequest.getOperatorId();
        StationInfo stationInfo = new StationInfo();
        stationInfo.setOperatorId(operatorID);
        String data = commonRequest.getData();
        CheckChargeOrderRequestData req = JSONUtil.readParams(data, CheckChargeOrderRequestData.class);
        CommonResponse response = new CommonResponse();
        response.setRet(EvcsConst.RET_SUCC);
        CheckChargeOrderResponseData resp = new CheckChargeOrderResponseData();
        resp.setCheckOrderSeq(req.getCheckOrderSeq());
        resp.setStartTime(req.getStartTime());
        resp.setEndTime(req.getEndTime());
        resp.setDisputeOrders(new DisputeOrder[]{});
        resp.setTotalDisputeMoney(0.0);
        resp.setTotalDisputeOrder(0);
        resp.setTotalDisputePower(0.0);
        response.setData(JSONUtil.toJSONString(resp));
        return response;
    }
    public static void main(String[] args) {

        try {
//            CommonRequest<CDRequirementInfo> commonRequest = new CommonRequest<>();
//            CDTaskInfo requirementInfo = new CDTaskInfo();
//            requirementInfo.setTaskName("任务名称");
//            requirementInfo.setTaskCode("任务编码");
//            requirementInfo.setDemandDate("2025-07-28");
//            requirementInfo.setStationID("充电站ID");
//            requirementInfo.setOperatorID("MA6DFCTD5");
//            requirementInfo.setEquipmentOwnerID("MA7D6FPW6");
//            requirementInfo.setEleNo("所属户号");
//            requirementInfo.setDeliveryTime("2025-07-29 00:00:00");
//            List<CDRequirementInfoList> list =new ArrayList<>();
//            CDRequirementInfoList cdRequirementInfoList = new CDRequirementInfoList();
//            cdRequirementInfoList.setRes(100.0);
//            cdRequirementInfoList.setStartTime("2025-07-29 00:00:00");
//            cdRequirementInfoList.setEndTime("2025-07-29 02:00:00");
//            list.add(cdRequirementInfoList);
//            requirementInfo.setList(list);
//            String dataYu = JSONUtil.toJSONString(requirementInfo);
//            commonRequest.setData(dataYu);
//            commonRequest.setOperatorId("MA7D6FPW6");




//            String[] st =new String[1];
//            st[0] = "33";
//            CommonRequest<XDTPlaceholderRules> commonRequest = new CommonRequest<>();
//            XDTPlaceholderRules xdtPlaceholderRules = new XDTPlaceholderRules();
//            xdtPlaceholderRules.setStationIDs(st);
//            CommonRequest<XDTPlaceHolderOrderStatus> commonRequest = new CommonRequest<>();
//
//            XDTPlaceHolderOrderStatus xdtPlaceHolderOrderStatus = new XDTPlaceHolderOrderStatus();
//            xdtPlaceHolderOrderStatus.setPlaceholderOrderID("8083600080000101250806101922");
//            xdtPlaceHolderOrderStatus.setStatus(2);
//            xdtPlaceHolderOrderStatus.setRefundMoney(10.0);
//
//
//
//            Map<String,Long> map =new HashMap<>();
//            map.put("placeholderOrderId",158470L);
//
//
//            String data = JSONUtil.toJSONString(map);
//            commonRequest.setData(data);
//            commonRequest.setOperatorId("MA25CNM38");
//            String s = encryptReqOut("8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6", "Ut5UFdqDthiJyncU", commonRequest);
//
//


//            PageRequest pageRequest1 = new PageRequest();
//            pageRequest1.setPageNo(1);
//            pageRequest1.setPageSize(20);
//            String data = JSONUtil.toJSONString(pageRequest1);
//
//            CommonRequest<PageRequest> pageRequest = new CommonRequest<>();
//
//            pageRequest.setData(data);
//            pageRequest.setOperatorId("MA1MY0GF9");
//            String dataYu = encryptReqOut("EOAVn9uGuUuLzfCq", "ruExy9reF1W1YVMj", "ww6FpuxoR1vAiGt8", pageRequest);
////
//            System.out.println("=====加密====sss==============="+dataYu);


//            CommonRequest<TokenRequest> commonRequestYu = new CommonRequest<>();
//            TokenRequest tokenRequest = new TokenRequest();
//            tokenRequest.setOperatorId("MA1MY0GF9");
//            tokenRequest.setOperatorSecret("2FYSvpUqBz6GydDc");
//            String data1 = JSONUtil.toJSONString(tokenRequest);
//            commonRequestYu.setData(data1);
//            commonRequestYu.setOperatorId("MA1MY0GF9");


//
//            CommonRequest<StartChargeRequest> chargeRequest = new CommonRequest<>();
//
//            StartChargeRequest cwjStartChargeRequest = new StartChargeRequest();
//            cwjStartChargeRequest.setStartChargeSeq("MA1MY0GF9202508061022122228");
//            cwjStartChargeRequest.setConnectorId("8083600090000201");
//
//            String data1 = JSONUtil.toJSONString(cwjStartChargeRequest);
//            chargeRequest.setData(data1);
//            chargeRequest.setOperatorId("MA1MY0GF9");



            CommonRequest<XDTPlaceholderRules> equipBizRequest = new CommonRequest<>();

            XDTPlaceholderRules equipBizRequest1 = new XDTPlaceholderRules();
            String[] st =new String[1];
            st[0] = "2";
            equipBizRequest1.setStationIDs(st);
            String data2 = JSONUtil.toJSONString(equipBizRequest1);
            equipBizRequest.setData(data2);
            equipBizRequest.setOperatorId("MA25CNM38");


//            CommonRequest<StationStatusRequest> chargeRequest1 = new CommonRequest<>();
//
//            StationStatusRequest stationStatusRequest = new StationStatusRequest();
//            String [] st ={"1"};
//            stationStatusRequest.setStationIds(st);
//            String data2 = JSONUtil.toJSONString(stationStatusRequest);
//            chargeRequest1.setData(data2);
//            chargeRequest1.setOperatorId("MA1MY0GF9");


            CommonRequest<CWJPageRequest> chargeRequest1 = new CommonRequest<>();

            CWJPageRequest cwjPageRequest = new CWJPageRequest();
            cwjPageRequest.setPageNo(1);
            cwjPageRequest.setPageSize(10);
            String data3 = JSONUtil.toJSONString(cwjPageRequest);
            chargeRequest1.setData(data3);
            chargeRequest1.setOperatorId("MA1MY0GF9");


            //
            String s = encryptReqOut("EOAVn9uGuUuLzfCq", "ruExy9reF1W1YVMj", "ww6FpuxoR1vAiGt8", chargeRequest1);
//
            System.out.println("==========sss==============="+s);

//            String date= "ywyEEd5aKPJOTraAY/gXBxX6qL9+xRX4dEBcxpmT1ylQ/2kIMRcIYozP9GR/DIYQqRm9a6/s5ZnVkjEHsOEbNdVUF00crSZfRIDHbfiDkQdLjJiBVuCU7b1lu5+QYR2CJzFfLIKZc9QYpt+/1PToDvzcbrvR4eLwSANt3H5sh+CSxnPjPhGaJNwOtQnMLLxOthBctkcW+aSF4O3s2KqnCvAB3O9OiQSLxfW1UZ0I0x0JvAMxY+Z4ncc4k16noCWCojVxFYQGITvXMH8ySQQ25A==";
//            String s2 = decryptString(date, "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6");
//
//
//            System.out.println("===解密=======sss==============="+s2);
//
//
            String date3= "QozR1HIMpMBoT9zTUV9Lyx6ayW7rDdBpEh8KT47490rDo2Zs+2nfup3PTiXO53he6dm8HGrvd3WYuNo2Inibwu1bpU79PMVPKt8mCvpsKH2Q6G8HT6IjC8FJRkdD3tjZv+kihGnpaGpc0jeiAdpm45NQr742K4SnK/EnjVUk427aZjzJTcYSjYunzPQm8/wG502akvZqpNoftTsEFdXsUrpKT+ERJX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ej4Tx4+fMHTzHllC4GB8omZz57FTa6fP5NaCQ5qXhQ1UyI96/D1z3Qa19u2og+DLfIdb+0KKWDIqyI0w5DTzMquiUYnN1Y4Ne5gKzeeIY7gvRFQIRGF0zIRs5Q4IaBGsk4UvFRff7Zwqp+izgmoKLPFulBbC2QfETG5HBxgekPJwvVkUpiSMHrjQjvKoMUiXIBXoiNyrEgpmm8OIsdDO6+wiriSvqN1F9ie1Qnf5iGj9n50eti/9zo8K5E9YNykVGCSsXju4Hz3xq+i0a7FEkKTUHQXuG1E3aTv6Z039tz69MbDSCEyyy4f9GzuyH1WSaedICClUxjp6tEvChtVEHnqTwvT+aE/dIhch/ZFYHyLvwdUF1dII6r6TwWw54dWs49Fcq1S1mp9mZwu4QN1U0mju0";
            String s2 = decryptString(date3, "EOAVn9uGuUuLzfCq", "ruExy9reF1W1YVMj");

            System.out.println("===解密=======sss3==============="+s2);


        }catch (Exception e){

        }
    }

    public static String encryptReqOut(String dataSecret, String dataSecretIV, String sigSecret, CommonRequest commonRequest)
            throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
            IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException, JsonProcessingException {

        String data = Aes128Cbc.encrypt(commonRequest.getData(), dataSecret, dataSecretIV);
        commonRequest.setData(data);
        Calendar cal = Calendar.getInstance();
        DateTime dt = new DateTime(cal);
        commonRequest.setTimeStamp(dt.toString(DatePattern.PURE_DATETIME_PATTERN));
        commonRequest.setSeq(String.valueOf(DateUtil.millisecond(dt)));
        String sig =
                HMAC.hmacDigest(commonRequest.getOperatorId() + data + commonRequest.getTimeStamp() + commonRequest.getSeq(),
                        sigSecret);
        commonRequest.setSig(sig);
        final String jsonString = JSONUtil.toJSONString(commonRequest);
//        log.debug("enc to out:{} ", jsonString);
        return jsonString;
    }


    public static String decryptString(String encryptedMsg, String dataSecret, String dataSecretIV) throws NoSuchAlgorithmException,
            IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
            InvalidAlgorithmParameterException, NoSuchPaddingException {

        if (encryptedMsg == null || encryptedMsg.length() == 0) return "";
        byte[] decryptedBytes = decryptBytes(encryptedMsg, dataSecret, dataSecretIV);
        return new String(decryptedBytes);
    }

    public static byte[] decryptBytes(String encryptedMsg, String dataSecret, String dataSecretIV) throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {

        if (encryptedMsg.startsWith("{") || encryptedMsg.startsWith("[")) {
            throw new IllegalArgumentException("不是合法的加密字符串");
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(CryptoMngr.ALGORITHM);
        keyGenerator.init(128);
        byte[] ds = (dataSecret).getBytes(StandardCharsets.UTF_8);
        ds = Arrays.copyOf(ds, 16);
        SecretKey key = new SecretKeySpec(ds, "AES");
        byte[] dsiv = (dataSecretIV).getBytes(StandardCharsets.UTF_8);
        dsiv = Arrays.copyOf(dsiv, 16);
        SecretKey IV = new SecretKeySpec(dsiv, "AES");
        byte[] cipherText = Base64.getDecoder().decode(encryptedMsg.getBytes());
        byte[] decryptedBytes = CryptoMngr.decrypt(key.getEncoded(), IV.getEncoded(), cipherText);
        return decryptedBytes;
    }
}
