package com.ningdatech.carapi.irs.service.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ningdatech.cache.model.cache.CacheKey;
import com.ningdatech.cache.repository.CachePlusOps;
import com.ningdatech.carapi.irs.service.DriverService;
import com.ningdatech.carapi.irs.service.RefreshKeyService;
import com.ningdatech.carapi.irs.utils.Md5Utils;
import com.ningdatech.carapi.scheduler.contants.TaskContant;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @since 2023/04/23 15:21
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DriverServiceImpl implements DriverService {

    private final RestTemplate restTemplate;
    private final RefreshKeyService refreshKeyService;
    private final CachePlusOps cachePlusOps;

    @Override
    public String vehicleLicenseQuery(String carPlate) {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret);

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/001003007/dataSharing/vehicleQmInfo.htm";


        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可0000-00\",\"subPowerMatters\":\"许可0000-0101\",\"accesscardId\":\"33071918******784523\",\"materialName\":\"社会团体变更登记申请表\",\"sponsorName\":\"阿里巴巴（中国）有限公司\",\"sponsorCode\":\"91330100799655058B\",\"projectId\":\"330000261711151100004\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        //map.add("sfzmhm",idCard);
        map.add("HPHM",carPlate);
        String res = null;
        try {
            log.info("请求参数 :{}", JSON.toJSONString(map));
            res = restTemplate.postForObject(url, map ,String.class);
            log.info("[RestTemplateTest-行驶证信息查询] http request :{}", res);
        } catch (Exception e) {
            log.error("[RestTemplateTest-行驶证信息查询] http request error", e);
        }
        return res;
    }

    @Override
    public String vehicleLicenseQuery(String carPlate,Integer index) {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";

        // 请求秘钥
        CacheKey requestKey = new CacheKey(TaskContant.RedisKey.IRS_VEHICLE_LICENSE_REQUEST_SECRET);
        // 刷新密钥
        CacheKey refreshKey = new CacheKey(TaskContant.RedisKey.IRS_VEHICLE_LICENSE_REFRESH_SECRET);

        // 根据key获取缓存中的请求秘钥和刷新密钥
        String requestSecret = cachePlusOps.get(requestKey);
        String refreshSecret = cachePlusOps.get(refreshKey);
        if (index == 0) {
            // 任务第一次调用接口，获取刷新秘钥和请求秘钥,并保存到redis中
            try {
                if (Objects.nonNull(refreshSecret)){
                    requestSecret = refreshKeyService.refreshRequestSecret(appKey, requestKey, refreshKey, refreshSecret);
                    if (requestSecret == null) {
                        requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                    }
                }else {
                    requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                }
            } catch (Exception e) {
                log.error("获取刷新密钥失败:{},此次车辆行驶证查询车牌号为{}", e.getMessage(), carPlate);
                return null;
            }
        } else if (Objects.isNull(refreshSecret)) {
            try {
                requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                if (requestSecret == null) {
                    return null;
                }
            } catch (Exception e) {
                log.error("获取刷新密钥失败:{},此次车辆行驶证查询车牌号为{}", e.getMessage(), carPlate);
                return null;
            }
        }
        // 不是第一次调用,看请求秘钥是否过期
        // 刷新密钥有效期两天，而定时任务每天都会执行一次，每次任务执行又会更新刷新密钥，所以刷新密钥不会过期
        // 只需判断请求秘钥是否过期
        else if (Objects.isNull(requestSecret)) {
            try {
                // 调用IRS刷新秘钥接口，更新刷新密钥和请求秘钥
                requestSecret = refreshKeyService.refreshRequestSecret(appKey, requestKey, refreshKey, refreshSecret);
                if (requestSecret == null) {
                    requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                }
            } catch (Exception e) {
                log.error("刷新请求密钥失败:{},此次车辆行驶证查询车牌号为{}", e.getMessage(), carPlate);
                return null;
            }
        }

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        log.info("请求参数中请求秘钥为：" + requestSecret);
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/001003007/dataSharing/vehicleQmInfo.htm";


        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可0000-00\",\"subPowerMatters\":\"许可0000-0101\",\"accesscardId\":\"33071918******784523\",\"materialName\":\"社会团体变更登记申请表\",\"sponsorName\":\"阿里巴巴（中国）有限公司\",\"sponsorCode\":\"91330100799655058B\",\"projectId\":\"330000261711151100004\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        //map.add("sfzmhm",idCard);
        map.add("HPHM",carPlate);
        log.info("请求参数 :{}", JSON.toJSONString(map));
        String res = restTemplate.postForObject(url, map, String.class);
        log.info("[RestTemplateTest-行驶证信息查询] http request :{}", res);
        return res;
    }

    @Override
    public String drivingLicenseQuery(String idCard) {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret);

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/001003007/dataSharing/driverLicenseInfo.htm";

        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可-0000-00\",\"subPowerMatters\":\"许可-0000-0101\",\"accesscardId\":\"33071918111111784523\",\"materialName\":\"社会团体变更登记申请表\",\"sponsorName\":\"阿里巴巴（中国）有限公司\",\"sponsorCode\":\"91330100799655058B\",\"projectId\":\"330000261711151100004\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        map.add("cardId",idCard);
        String res = null;
        try {
            log.info("请求参数 :{}", JSON.toJSONString(map));
            res = restTemplate.postForObject(url, map ,String.class);
            log.info("[RestTemplateTest-驾驶证查询] http request :{}", res);
        } catch (Exception e) {
            log.error("[RestTemplateTest-驾驶证查询] http request error", e);
        }
        return res;
    }

    /**
     * 根据车架号查询行驶证信息
     * @return java.lang.String
     * @author CMM
     * @since 2023/05/22 21:23
     */
    @Override
    public List<String> vehicleLicenseTest() {

        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret);

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/001003007/dataSharing/vehicleQmInfo.htm";

        List<String> cjhList = Lists.newArrayList();

        //cjhList.add("LZ5N2DE57HB611625");
        //cjhList.add("LZ5N2DE57HB611623");
        //cjhList.add("LZ5N2DE57HB611633");
        //cjhList.add("LZ5N2DE57HB611626");
        //cjhList.add("LZ5N2DE57HB611632");
        //cjhList.add("LZ5N2DE57HB611624");

        cjhList.add("LUZAGBGA3NA136300");
        cjhList.add("LUZAGBGA7NA168084");

        //String hphm = "浙C52502";
        //cjhList.add(hphm);

        List<String> resList = Lists.newArrayList();
        for (String cjh : cjhList) {
            MultiValueMap<String, Object> map = new LinkedMultiValueMap();
            // 附加信息
            map.add("additional", "{\"powerMatters\":\"许可0000-00\",\"subPowerMatters\":\"许可0000-0101\",\"accesscardId\":\"33071918******784523\",\"materialName\":\"社会团体变更登记申请表\",\"sponsorName\":\"阿里巴巴（中国）有限公司\",\"sponsorCode\":\"91330100799655058B\",\"projectId\":\"330000261711151100004\"}");
            map.add("appKey", appKey);
            map.add("requestTime", requestTime);
            map.add("sign", sign);
            map.add("clsbdh", cjh);
            //map.add("HPHM",cjh);
            String res = null;
            try {
                log.info("请求参数 :{}", JSON.toJSONString(map));
                res = restTemplate.postForObject(url, map, String.class);
                log.info("[RestTemplateTest-行驶证信息查询] http request :{}", res);
            } catch (Exception e) {
                log.error("[RestTemplateTest-行驶证信息查询] http request error", e);
            }
            resList.add(res);
        }
        return resList;
    }
}
