package com.hzya.frame.sys.appApi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.sys.appApi.entity.AppApiDto;
import com.hzya.frame.sys.appApi.entity.AppApiListVo;
import com.hzya.frame.sys.entity.DebugApiDto;
import com.hzya.frame.sys.entity.ModuleDto;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.exception.BaseSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzya.frame.serviceUtil.ServiceUtil;
import com.hzya.frame.sys.appApi.entity.AppApi;
import com.hzya.frame.sys.appApi.service.IAppApiService;
import com.hzya.frame.sys.appApi.dao.IAppApiMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: 应用api  service
 * @tableName:   sys_app_api
 * @entityName:  AppApi
 * @author: 	 gjh
 * @history:	 1.0
 */
@Service(value="appApiService")
public class  AppApiServiceImpl extends ServiceUtil implements IAppApiService{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	protected IAppApiMapper  appapiMapper;


	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 查询列表
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity queryPage(JSONObject object) {
		AppApiDto entity = getData("jsonStr", object, AppApiDto.class);
		//判断分页
		if(entity == null || entity.getPageNum() == null || entity.getPageSize() == null){
			return BaseResult.getFailureMessageEntity("分页查询参数不存在");
		}
		PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
		List<AppApiListVo> appApiListVoList = appapiMapper.queryList(entity);
		PageInfo pageInfo = new PageInfo(appApiListVoList);
		return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
	}
	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 查询列表
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity queryList(JSONObject object) {
		AppApiDto entity = getData("jsonStr", object, AppApiDto.class);
		List<AppApiListVo> appApiListVoList = appapiMapper.queryList(entity);
		return BaseResult.getSuccessMessageEntity("查询数据成功", appApiListVoList);
	}

	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 获取数据
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity queryEntity(JSONObject object) {
		AppApiDto entity = getData("jsonStr", object, AppApiDto.class);
		//判断分页
		if(entity == null || entity.getId() == null || "".equals(entity.getId())){
			return BaseResult.getFailureMessageEntity("请先传递请求主键");
		}
		AppApi appApi = appapiMapper.entity_get(entity.getId());
		return BaseResult.getSuccessMessageEntity("查询数据成功", appApi);
	}
	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 新增数据
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity addEntity(JSONObject object) {
		AppApi entity = getData("jsonStr", object, AppApi.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getApiName() == null || "".equals(entity.getApiName())){
			return BaseResult.getFailureMessageEntity("请先输入接口名称");
		}
		if(entity.getApiCode() == null || "".equals(entity.getApiCode())){
			return BaseResult.getFailureMessageEntity("请先输入接口编码");
		}
		AppApi checkEntity = new AppApi();
		checkEntity.setSts("Y");
		checkEntity.setApiCode(entity.getApiCode());
		int checkCount = appapiMapper.entity_count(checkEntity);
		if(checkCount > 0){
			return BaseResult.getFailureMessageEntity("接口编码已存在");
		}
		entity.setCreate();
		 appapiMapper.entity_insert(entity);
		return BaseResult.getSuccessMessageEntity("保存接口成功",entity.getId());
	}

	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 修改数据
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity editEntity(JSONObject object) {
		AppApi entity = getData("jsonStr", object, AppApi.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getId() == null || "".equals(entity.getId())){
			return BaseResult.getFailureMessageEntity("系统错误");
		}
		if(entity.getApiName() == null || "".equals(entity.getApiName())){
			return BaseResult.getFailureMessageEntity("请先输入接口名称");
		}
		if(entity.getApiCode() == null || "".equals(entity.getApiCode())){
			return BaseResult.getFailureMessageEntity("请先输入接口编码");
		}
		AppApi checkEntity = new AppApi();
		checkEntity.setSts("Y");
		checkEntity.setId(entity.getId());
		checkEntity.setApiCode(entity.getApiCode());
		int checkCount = appapiMapper.entity_count_not_id(checkEntity);
		if(checkCount > 0){
			return BaseResult.getFailureMessageEntity("接口编码已存在");
		}
		entity.setUpdate();
		int i = appapiMapper.entity_update(entity);
		return BaseResult.getSuccessMessageEntity("修改接口成功",entity.getId());
	}

	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 删除数据
	 * @Date 2:18 下午 2023/7/17
	 **/
	@Override
	public JsonResultEntity deleteEntity(JSONObject object) {

		AppApi entity = getData("jsonStr", object, AppApi.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getId() == null || "".equals(entity.getId())){
			return BaseResult.getFailureMessageEntity("系统错误");
		}
		entity.setUpdate();
		int i = appapiMapper.entity_logicDelete(entity);
		return BaseResult.getSuccessMessageEntity("删除接口成功");
	}

	/**
	 * @param object
	 * @return com.hzya.frame.web.entity.JsonResultEntity
	 * @Author lvleigang
	 * @Description 根据用户id查询菜单树
	 * @Date 9:48 上午 2023/6/29
	 **/
	@Override
	public JsonResultEntity debugApi(JSONObject object) {
		DebugApiDto entity = getData("jsonStr", object, DebugApiDto.class);
		try {
			String body = doApi(entity);
			return BaseResult.getSuccessMessageEntity(body);
		} catch (BaseSystemException e) {
			return BaseResult.getFailureMessageEntity(e.getMessage());
		}
	}

	private String doApi(DebugApiDto entity) {
		//校验是否有servecr传参
		if (entity == null) {
			throw new BaseSystemException("请先传递对象");
		}
		if (!checkStr(entity.getUrl())) {
			throw new BaseSystemException("请先传递url");
		}
		if (!checkStr(entity.getMethod())) {
			throw new BaseSystemException("请先传递请求类型");
		}
		HttpRequest httpRequest = HttpRequest.of(entity.getUrl());
		httpRequest.method(Method.valueOf(entity.getMethod().toUpperCase()));
		if(entity.getHeaders() != null ){
			Map headers = JSON.parseObject(entity.getHeaders());
			if(headers != null && headers.size() > 0){
				httpRequest.addHeaders(headers);
			}
		}else if(entity.getHeader() != null ){
			Map headers = JSON.parseObject(entity.getHeader());
			if(headers != null && headers.size() > 0){
				httpRequest.addHeaders(headers);
			}

		}
		if(entity.getBody() != null ){
			httpRequest.body(entity.getBody(),"application/json");
		}
		try {
			String body = httpRequest.execute().body();
			if(body == null){
				throw new BaseSystemException("请求错误，请检查请求地址以及请求参数");
			}
			if(body.contains("HTTP Status 404 – Not Found")){
				throw new BaseSystemException("请求错误，请检查请求地址以及请求参数");
			}
			try {
				JSON.parse(body);
			} catch (Exception e) {
				throw new BaseSystemException("请求错误，请检查请求地址以及请求参数");
			}
			return body;
		} catch (Exception e) {
			throw new BaseSystemException("请求错误，请检查请求地址以及请求参数");
		}
	}


	public JsonResultEntity testToken(JSONObject object) {
		JSONObject entity = getstrObj("jsonStr", object);
		if (entity == null) {
			return BaseResult.getFailureMessageEntity("对象为空");
		}
		if (!checkStr(entity.getString("body"))) {
			return BaseResult.getFailureMessageEntity("对象body为空");
		}
		JSONObject body = getstrObj("body", entity);
		if (!checkStr(body.getString("user"))) {
			return BaseResult.getFailureMessageEntity("对象body.user为空");
		}
		JSONObject user = getstrObj("user", body);
		if (!checkStr(user.getString("token"))) {
			return BaseResult.getFailureMessageEntity("对象body.user.token为空");
		}
		if(StpUtil.getTokenValue().equals(user.getString("token"))){
			return BaseResult.getSuccessMessageEntity("校验token成功,业务处理成功获取name:"+user.getString("name"));
		}else {
			return BaseResult.getFailureMessageEntity("校验token失败");
		}
	}

	/**
	 * 根据id获取
	 *
	 * @param id
	 * @return
	 */
	@Override
	public AppApi getByid(String id) {
		if (StrUtil.isNotEmpty(id)){
			AppApi appApi = appapiMapper.entity_get_join_dictionary(id);
			return appApi;
		}
		return null;
	}
}
