/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.gateway.shop_gateway.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springblade.common.cache.PlatformCache;
import org.springblade.common.config.entity.PlatformConfig;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.enums.TransferStatus;
import org.springblade.common.enums.WithdrawStatus;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.flow.shop.entity.ProcessAudit;
import org.springblade.flow.shop.service.impl.AuditShopService;
import org.springblade.gateway.shop_gateway.entity.dto.ShopAuditDto;
import org.springblade.gateway.shop_gateway.entity.vo.BalanceAccountInfoVO;
import org.springblade.gateway.shop_gateway.service.IAppShopService;
import org.springblade.ldt.bills.entity.TransferRec;
import org.springblade.ldt.bills.entity.WithdrawRec;
import org.springblade.ldt.bills.service.ITransferRecService;
import org.springblade.ldt.bills.service.IWithdrawRecService;
import org.springblade.ldt.mall.entity.Mall;
import org.springblade.ldt.mall.service.IMallService;
import org.springblade.ldt.shop.entity.Audit;
import org.springblade.ldt.shop.entity.Shop;
import org.springblade.ldt.shop.mapper.ShopMapper;
import org.springblade.ldt.shop.service.IAuditService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springblade.wx.config.ConfigForClient;
import org.springblade.wx.config.ConfigForMall;
import org.springblade.wx.config.ConfigForShop;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.common.YeepayApiConstant;
import org.springblade.yeePay.entity.ConfigAppDto;
import org.springblade.yeePay.entity.saas.settlement.SettleBalanceQueryDto;
import org.springblade.yeePay.service.YeepayCommonService;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 服务实现类
 *
 * @author BladeX
 * @since 2021-08-30
 */
@Service
@AllArgsConstructor
public class AppShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IAppShopService {

	private AuditShopService auditShopService;
	private IAuditService auditService;
	private ILoginUserService loginUserService;
	private IMallService mallService;
	private YeepayCommonService yeepayCommonService;
	private YeePayConst yeePayConst;
	private ConfigForClient configForClient;
	private ConfigForMall configForMall;
	private ConfigForShop configForShop;
	private IWithdrawRecService withdrawRecService;
	private ITransferRecService transferRecService;
	private YeepaySaasService yeepaySaasService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void submitAudit(ShopAuditDto shopAuditDto) {
		Shop shop = shopAuditDto.getShop();
		Long mallId = shop.getMallId();
		Mall mall = mallService.getById(mallId);
		if (!Objects.isNull(mall)) {
			String tenantId = mall.getTenantId();
			shop.setTenantId(tenantId);
		} else {
			shop.setTenantId(AppConstant.PLATFORM_TENANT_ID);
		}
		if (shop.getAgenter() != null) {
			LoginUser loginUser = loginUserService.getById(shop.getAgenter());
			String avatar = Optional.ofNullable(loginUser).map(LoginUser::getAvatar).orElse("");
			shop.setAgentAvatar(avatar);
			String nickName = Optional.ofNullable(loginUser).map(LoginUser::getNickName).orElse("");
			shop.setAgentName(nickName);
		}
		boolean isEdit = shop.getId() != null;
		shop.setCreateTime(new Date());
		this.saveOrUpdate(shop);
		Audit audit = shopAuditDto.getAudit();
		if (isEdit) {
			//修改资料时
			auditService.updateById(audit);
			return;
		}
		//新增的商户资料才开启审核流程
		audit.setEntityId(shop.getId());
		ProcessAudit processAudit = ProcessAudit.builder()
			.audit(audit)
			.build();
		auditShopService.startProcess(processAudit);
	}

	@Override
	public String getTenantId(Long shopId) {
		Shop shop = this.getById(shopId);
		if (shop == null) {
			return AppConstant.PLATFORM_TENANT_ID;
		}
		Long mallId = shop.getMallId();
		if (mallId == null) {
			return AppConstant.PLATFORM_TENANT_ID;
		}
		Mall mall = mallService.getById(mallId);
		String tenantId = Optional.ofNullable(mall).map(Mall::getTenantId).orElse(AppConstant.PLATFORM_TENANT_ID);
		return tenantId;
	}

	/**
	 * 配置商户的小程序信息（易宝报备商户信息）
	 *
	 * @param shop
	 * @return
	 */
	@Override
	public R configApp(Shop shop) {
		ConfigAppDto configAppDto = ConfigAppDto.builder()
			.merchantNo(shop.getMerchantNo())
			.parentMerchantNo(yeePayConst.getPlatformServiceNo())
			.build();

		ConfigAppDto.AppInfo clientApp = new ConfigAppDto.AppInfo();
		clientApp.setAppId(configForClient.getAppId());
		clientApp.setAppSecret(configForClient.getAppSecret());
		clientApp.setAppIdType("MINI_PROGRAM");

		ConfigAppDto.AppInfo shopApp = new ConfigAppDto.AppInfo();
		shopApp.setAppIdType("MINI_PROGRAM");
		shopApp.setAppId(configForShop.getAppId());
		shopApp.setAppSecret(configForShop.getAppSecret());

		ConfigAppDto.AppInfo mallApp = new ConfigAppDto.AppInfo();
		mallApp.setAppSecret(configForMall.getAppSecret());
		mallApp.setAppId(configForMall.getAppId());
		mallApp.setAppIdType("MINI_PROGRAM");

		configAppDto.setAppIdList(new ConfigAppDto.AppInfo[]{clientApp, shopApp, mallApp});

		return yeepayCommonService.configApp(configAppDto);
	}

	@Override
	public Long userBalanceWithdraw(WithdrawRec withdrawRec) {
		if (ObjectUtils.isEmpty(withdrawRec) || ObjectUtils.isEmpty(withdrawRec.getOwnerId())) {
			throw new ServiceException(ResultCode.PARAM_MISS);
		}
		Shop shop = getById(withdrawRec.getOwnerId());
		if (ObjectUtils.isEmpty(shop)) {
			throw new ServiceException(ResultCode.NOT_FOUND);
		}

		BigDecimal feeRate = getFeeRate(withdrawRec.getPrice());
		//国信手续费
		BigDecimal fee = withdrawRec.getPrice().multiply(feeRate);
		withdrawRec.setPlatformFee(fee);
		//实际提现金额
		BigDecimal actualPrice = withdrawRec.getPrice().subtract(fee);
		withdrawRec.setActualPrice(actualPrice);
		withdrawRec.setWithdrawStatus(WithdrawStatus.WAITING.getValue());
		withdrawRecService.saveOrUpdate(withdrawRec);

		return withdrawRec.getId();
	}

	@Override
	public Long userPointWithdraw(WithdrawRec withdrawRec) {
		//1.保存提现记录
		Long withdrawId = userBalanceWithdraw(withdrawRec);

		//2.转账金额 = 提现金额 - 提现金额 * 国信手续费率
		BigDecimal fee = withdrawRec.getPrice().multiply(getFeeRate(withdrawRec.getPrice()));
		BigDecimal actualPrice = withdrawRec.getPrice().subtract(fee);

		//3.保存转账记录
		TransferRec transferRec = new TransferRec();
		transferRec.setChannel(withdrawRec.getChannel());
		transferRec.setTransferStatus(TransferStatus.REQUEST_RECEIVE);
		transferRec.setOwnerId(withdrawRec.getOwnerId());
		transferRec.setPrice(actualPrice);
		transferRec.setActualPrice(actualPrice);
		transferRec.setFeeChargeSide(YeepayApiConstant.feeChargeSide.OUTSIDE);
		transferRec.setPlatformFee(BigDecimal.ZERO);//转账平台暂时不收取手续费
		transferRec.setWithdrawId(withdrawId);//提现记录id
		transferRec.setTenantId(withdrawRec.getTenantId());
		transferRecService.saveOrUpdate(transferRec);

		return transferRec.getId();
	}

	/**
	 * 提现处理国信手续费
	 *
	 * @param amount 提现金额
	 * @return 手续费率
	 */
	private BigDecimal getFeeRate(BigDecimal amount) {

		PlatformConfig platformConfig = PlatformCache.platFormConfig();
		Assert.notNull(platformConfig, "提现异常，请联系管理员！");
		List<PlatformConfig.WithdrawConfig> items = platformConfig.getWithdrawConfigList();
		//手续费率
		BigDecimal feeRate = BigDecimal.ZERO;
		for (PlatformConfig.WithdrawConfig item : items) {
			BigDecimal min = BigDecimal.valueOf(item.getMinBalance());
			BigDecimal max = BigDecimal.valueOf(item.getMaxBalance());
			//最小提现金额 <= 提现金额 <= 最大提现金额
			boolean flag = amount.compareTo(min) >= 0 && amount.compareTo(max) <= 0;
			if (flag) {
				feeRate = BigDecimal.valueOf(item.getRate());
			}
		}
		return feeRate;
	}

	@Override
	public BalanceAccountInfoVO queryBalance(Long shopId) {
		Shop shop = this.getById(shopId);
		SettleBalanceQueryDto settleBalanceQueryDto = new SettleBalanceQueryDto(YeepayApiConstant.operatePeriod.ALL.name(), null);
		settleBalanceQueryDto.setMerchantNo(shop.getMerchantNo());
		settleBalanceQueryDto.setParentMerchantNo(yeePayConst.getPlatformServiceNo());
		JSONObject settleBalance = JSON.parseObject(yeepaySaasService.settleBalanceQuery(settleBalanceQueryDto).getStringResult());

		BigDecimal availd = BigDecimal.valueOf(settleBalance.getDouble("settlableAmount"));
		BigDecimal settle = BigDecimal.valueOf(settleBalance.getDouble("unsettledAmount"));
		BigDecimal today = settle.subtract(availd);

		BalanceAccountInfoVO balanceAccountInfoVO = BalanceAccountInfoVO.builder()
			.totalNum(shop.getTotalBalance().toString())
			.availableNum(availd.toString())
			.todayNum(today.toString())
			.build();
		return balanceAccountInfoVO;
	}
}
