package org.springblade.gateway.yeepay_gateway.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.yeepay_gateway.vo.WechatConfigQueryVO;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.entity.saas.WechatConfigAddDto;
import org.springblade.yeePay.entity.saas.WechatConfigQueryDto;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 15:26 2021/12/23
 * @Modified By:
 */
@Service
public class AppYeepayService {
	@Autowired
	private YeepaySaasService yeepaySaasService;
	@Autowired
	private YeePayConst yeePayConst;

	/**
	 * 查询微信配置
	 *
	 * @return
	 */
	@SneakyThrows
	public R<List<WechatConfigQueryVO>> getWechatConfigQuery() {
		YopResponse yopResponse = yeepaySaasService.wechatConfigQuery(
			WechatConfigQueryDto.builder()
				.parentMerchantNo(yeePayConst.getPlatformServiceNo())
				.merchantNo(yeePayConst.getMerchantNo())
				/*.appIdType(YeepayApiConstant.appIdType.OFFICIAL_ACCOUNT)*/.build());
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!Objects.equals(res.getString("code"), "00000")) {
			throw new ServiceException(res.getString("message"));
		}
		String configResult = res.getString("configResult");
		if (StringUtils.isNotEmpty(configResult)) {
			return R.data(new ObjectMapper().readValue(res.getString("configResult"), new TypeReference<List<WechatConfigQueryVO>>() {
			}));
		} else {
			return R.data(Collections.emptyList());
		}
	}

	/**
	 * 添加微信配置
	 *
	 * @param wechatConfigAddDto
	 * @return
	 */
	public R wechatConfigAdd(WechatConfigAddDto wechatConfigAddDto) {
		wechatConfigAddDto.setMerchantNo(yeePayConst.getMerchantNo());
		wechatConfigAddDto.setParentMerchantNo(yeePayConst.getPlatformServiceNo());
		YopResponse yopResponse = yeepaySaasService.wechatConfigAdd(wechatConfigAddDto);
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!Objects.equals(res.getString("code"), "00000")) {
			throw new ServiceException(res.getString("message"));
		}
		return R.success("配置成功！");
	}
}
