package com.bocloud.ims.service.internal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.enums.BoCloudMethod;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.*;
import com.bocloud.ims.entity.common.Dictionary;
import com.bocloud.service.core.CurrentService;
import com.bocloud.service.core.Service;
import com.bocloud.service.http.core.ServiceFactory;
import com.bocloud.service.http.model.RemoteService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SmsDictionaryService.java
 * @Description: 访问SMS字段数据
 *
 * @author: ymh
 * @date: 2021年4月7日 下午6:16:24
 */
@Component
public class SmsDictionaryService implements InitializingBean {

	@Autowired
	private ServiceFactory serviceFactory;
	@Autowired
	private CurrentService currentService;
	private static Service service = Service.create(BoCloudService.SMS);
	private Map<String, Object> headers = new HashMap<>(4);

	public BocloudResult<List<Dictionary>> dictionaries(String pvalue) {
		JSONObject params = new JSONObject();
		params.put("value", pvalue);
		RemoteService remoteService = serviceFactory.build(service, "/v1/dictionaries/children/tree", BoCloudMethod.GET,
				headers, params);
		BocloudResult result = remoteService.invoke();
		if (result.isFailed()) {
			return new BocloudResult<>(false, result.getMessage());
		}
		String data = JSONObject.toJSONString(result.getData());
		List<Dictionary> dictionarys = JSONObject.parseArray(data, Dictionary.class);
		return new BocloudResult<>(true, dictionarys, "查询成功");
	}

	public BocloudResult<List<Dictionary>> childrens(String pvalue) {
		JSONObject params = new JSONObject();
		params.put("value", pvalue);
		RemoteService remoteService = serviceFactory.build(service, "/v1/dictionaries/children", BoCloudMethod.GET, headers, params);
		BocloudResult result = remoteService.invoke();
		if (result.isFailed()) {
			return new BocloudResult<>(false, result.getMessage());
		}
		String data = JSONObject.toJSONString(result.getData());
		List<Dictionary> dictionarys = JSONObject.parseArray(data, Dictionary.class);
		return new BocloudResult<>(true, dictionarys, "查询成功");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.headers.put(BocloudToken.INTERNAL_TOKEN, currentService.getToken());
		this.headers.put("source", currentService.getService().getName());
	}

}
