package org.springblade.gateway.mall_gateway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springblade.common.cache.PlatformCache;
import org.springblade.common.config.yeepay.OpenProduct;
import org.springblade.common.constant.CallbackServeUrl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.ldt.fee.entity.ProductFee;
import org.springblade.ldt.fee.service.IProductFeeService;
import org.springblade.ldt.mall.entity.Mall;
import org.springblade.ldt.mall.service.IMallService;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.common.YeePayProductFeeState;
import org.springblade.yeePay.entity.saas.InvitationDto;
import org.springblade.yeePay.entity.saas.changeservice.ProductFeeModifyDto;
import org.springblade.yeePay.entity.saas.changeservice.ProductFeeQueryDto;
import org.springblade.yeePay.service.YeePayService;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/mall/yeepay/product/fee")
@Api(tags = "大B商户易宝费率控制")
@AllArgsConstructor
@Slf4j
public class MallYeePayProductController {
	private final IMallService mallService;

	private final YeepaySaasService yeepaySaasService;

	private final YeePayConst yeePayConst;

	private final IProductFeeService productFeeService;

	private final YeePayService yeePayService;

	@ApiOperation("查询商户产品费率列表")
	@GetMapping("query")
	public R query(@RequestParam String id){
		Mall mall = mallService.getById(id);
		Assert.notNull(mall,"找不到该商场信息");
		YopResponse yopResponse = yeepaySaasService.productFeeQuery(ProductFeeQueryDto.builder()
			.merchantNo(mall.getMerchantNo())
			.parentMerchantNo(yeePayConst.getPlatformServiceNo())
			.build());
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!StringUtils.equals(res.getString("returnCode"), "NIG00000")) {
			throw new ServiceException(res.getString("returnMsg"));
		}
		List<InvitationDto.ProductInfo> productInfo = res.getJSONArray("productInfo").toJavaList(InvitationDto.ProductInfo.class);
		productInfo.forEach(product->{
			product.setProductName(product.getProductCode().getText());
		});
		return R.data(productInfo);
	}

	@ApiOperation("设置商户产品费率")
	@PostMapping("modify")
	@Transactional
	public R modify(@RequestParam String id,
					@RequestParam String modifyProductInfo){
		Mall mall = mallService.getById(id);
		Assert.notNull(modifyProductInfo,"请填写相关信息");
		//保存产品费率更改信息
		YopResponse yopResponse = yeepaySaasService.productFeeModify(ProductFeeModifyDto.builder()
			.parentMerchantNo(yeePayConst.getPlatformServiceNo())
			.merchantNo(mall.getMerchantNo())
			.productInfo(JSON.parseArray(modifyProductInfo,ProductFeeModifyDto.ModifyProductInfo.class))
			.notifyUrl(new StringBuilder(CallbackServeUrl.CALL_BACK_SERVE_URL)
				.append("/mall/yeepay/product/fee/modifyProductFeeNotify").toString())
			.requestNo(UUID.randomUUID().toString())
			.build());
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!StringUtils.equals(res.getString("returnCode"), "NIG00000")) {
			throw new ServiceException(res.getString("returnMsg"));
		}
		//保存更改记录
		ProductFee productFee = res.toJavaObject(ProductFee.class);
		productFee.setProductInfo(modifyProductInfo);
		productFeeService.save(productFee);
		return R.data(res);
	}

	@ApiOperation("产品费率变更通知")
	@PostMapping("modifyProductFeeNotify")
	@TenantIgnore
	public void modifyProductFeeNotify(HttpServletRequest request){
		JSONObject jsonObject = yeePayService.deCodeNotifyData(request.getParameterMap().get("cipherText")[0]);
		log.info("产品费率变更通知内容:{}",jsonObject);
		Assert.notNull(jsonObject,"产品费率变更通知回调信息为空");
		ProductFee productFee = jsonObject.toJavaObject(ProductFee.class);
		ProductFee oldProductFee = productFeeService.getOne(Wrappers.<ProductFee>lambdaQuery()
			.eq(ProductFee::getRequestNo, productFee.getRequestNo())
			.eq(ProductFee::getMerchantNo, productFee.getMerchantNo())
			.eq(ProductFee::getApplicationNo, productFee.getApplicationNo()));
		if(oldProductFee!=null){
			log.error("修改前数据:{}",oldProductFee);
			oldProductFee.setApplicationStatus(productFee.getApplicationStatus());
			oldProductFee.setAgreementSignUrl(productFee.getAgreementSignUrl());
			oldProductFee.setAuditOpinion(productFee.getAuditOpinion());
			oldProductFee.setProgressDescription(productFee.getProgressDescription());
			productFeeService.update(oldProductFee,Wrappers.<ProductFee>lambdaQuery()
				.eq(ProductFee::getId,oldProductFee.getId()));
		}
	}

	@ApiOperation("获取产品费率是否需要处理")
	@GetMapping("productFeeTip")
	public R productFeeTip(@RequestParam String id){
		Mall mall = mallService.getById(id);
		if(ObjectUtils.isNotEmpty(mall)){
			//查询最新一条数据
			int count = productFeeService.count(Wrappers.<ProductFee>lambdaQuery()
				.eq(ProductFee::getMerchantNo, mall.getMerchantNo())
				.ne(ProductFee::getApplicationStatus,YeePayProductFeeState.COMPLETED.name()));
			return R.data(count);
		}
		return R.data(0);
	}

	@ApiOperation("根据商户获取平台默认产品费率")
	@GetMapping("getProductFeeByMall")
	public R getProductFeeByShop(){
		List<InvitationDto.ProductInfo> productInfos = PlatformCache.productInfo(OpenProduct.MERCHANT_PRODUCTS);
		return R.data(productInfos);
	}
}
