package com.mvc.service.iotcard;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.mvc.model.iotcard.*;
import com.mvc.utils.HttpUtil;
import com.mvc.utils.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;

/**
 * 物联网卡信息服务(上海秩易物联网卡开放平台)
 */
@Service
public class IotCardShzyService {
    private static Logger log = LoggerFactory.getLogger(IotCardShzyService.class);

    private static final String APP_ID = "8178129034";
    private static final String SECRET_KEY = "1C115A715ECA25B68F2F02F94A477E70";
    private static final String API_INQUIRECARDDATA = "https://admin.zhiyiiot.com/api/open/inquireCardData";//通过接入号/ICCID单卡/批量获取卡信息

    @Resource
    private RestTemplate restTemplate;

    /**
     * 根据CCID获取单卡信息(从第三方API)
     *
     * @param ccid
     * @return
     */
    public TIotcardInfoModel queryCardInfoByCCID(String ccid) {
        ShyzQueryParamModel paramModel = generateQueryModel(ccid);
        String json = postInParam(API_INQUIRECARDDATA, paramModel);
        if (StringUtils.isNotEmpty(json)) {
            ShyzResultModel result = JSON.parseObject(json, new TypeReference<>() {
            });
            if (result.getCode() == 1) {
                if(!result.getData().getList().isEmpty()){
                    return new TIotcardInfoModel(result.getData().getList().get(0));
                }
            }else {
                log.warn("查询物联网卡信息失败",result.getMsg());
            }
        }

        return null;
    }

    private String postInParam(String url, Object model) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 将对象转换为表单参数
        MultiValueMap<String, String> formParams = HttpUtil.convertToFormParams(model);
        try {
            // 创建请求实体
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            } else {
                log.error("获取物联网卡信息异常1");
                log.error(response.getBody());
            }
        } catch (Exception ex) {
            log.error("获取物联网卡信息异常2");
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
        return null;
    }

    private ShyzQueryParamModel generateQueryModel(String iccid) {
        ShyzQueryParamModel paramModel = new ShyzQueryParamModel(APP_ID, iccid);
        try {
            // 创建配置，确保字段按升序排列
            SerializeConfig config = new SerializeConfig();
            config.setAsmEnable(false);
            //字段正序排列
            Map<String, Object> sortedMap = new TreeMap<>(JSON.parseObject(JSON.toJSONString(paramModel)));
            //使用自定义过滤器过滤空字段
            String jsonString = JSON.toJSONString(sortedMap, new IgnoreNullValueFilter());
            String sign = jsonString + SECRET_KEY;       //拼接加密原文
            sign = SecurityUtil.toMD5(sign);             //MD5加密
            sign = Base64.getEncoder().encodeToString(sign.getBytes());//BASE64编码
            sign = URLEncoder.encode(sign, "UTF-8");//URL编码
            paramModel.setSign(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return paramModel;
    }
}
