package com.sptg.gateway.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sptg.estate.api.dto.HealthCodeDto;
import com.sptg.estate.api.vo.HealthCodeVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/app/health")
public class HealthCodeController {

	@Value("${healthcode.productId}")
	private  String  PRODUCT_ID;		//平台服务id
	@Value("${healthcode.productSecret}")
	private  String  PRODUCT_SECRET;		//平台服务秘钥

	private  static String CODE_URL = "http://120.92.153.151:3000/hio/api/health_code/info";

	@PostMapping("/getCode")
	public Map<String,Object> getHealthCode(@RequestBody HealthCodeDto healthCodeDto){
		//发送API请求
		Map<String,Object> map = new HashMap<>();
		String result = HttpRequest.get(CODE_URL)
			.header(Header.CONTENT_TYPE, "application/json")
			.header("ProductKey",PRODUCT_ID)
			.header("ProductSecret", PRODUCT_SECRET)
			.form("name",healthCodeDto.getUserName())
			.form("id_card",healthCodeDto.getIdCardNumber())
			.execute().body();

		//解析响应报文
		JSONObject rsObject = JSON.parseObject(result);
		if("ok".equals(rsObject.getString("status"))){
			map.put("result_code",1);
			map.put("result_msg",new HealthCodeVO.HealthCodeVOBuilder()
					.withCode(rsObject.getJSONObject("data").getString("image_url"))
					.withColor(rsObject.getJSONObject("data").getString("color"))
					.build());
		}else {
			map.put("result_code",0);
			map.put("result_msg",rsObject.getJSONObject("error").getString("message"));
		}
		return map;
	}

	public static void main(String[] args) {
		String result = HttpRequest.get(CODE_URL)
			.header(Header.CONTENT_TYPE, "application/json")
			.header("ProductKey","19fccd26af234791" )
			.header("ProductSecret", "bb21153d067446d5")
			.form("name","梁汉强")
			.form("id_card","440981199612222852")
			.execute().body();
		System.out.println(result);
	}
}
