/*
 *      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.modules.guosen.bussinessuserwithdraw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.common.constant.SystemConstant;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.modules.guosen.bussinessInfo.entity.BussinessInfo;
import org.springblade.modules.guosen.bussinessInfo.service.IBussinessInfoService;
import org.springblade.modules.guosen.bussinessTransferOrder.entity.BussinessTransferOrder;
import org.springblade.modules.guosen.bussinessTransferOrder.service.IBussinessTransferOrderService;
import org.springblade.modules.guosen.bussinessuserinfo.entity.BussinessUserInfo;
import org.springblade.modules.guosen.bussinessuserinfo.service.IBussinessUserInfoService;
import org.springblade.modules.guosen.bussinessuserwithdraw.dto.BussinessUserWithdrawDTO;
import org.springblade.modules.guosen.bussinessuserwithdraw.dto.WithdrawTransferOrder;
import org.springblade.modules.guosen.bussinessuserwithdraw.excel.WithdrawExcel;
import org.springblade.modules.system.service.IParamService;
import org.springblade.yeePay.service.BussinessPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.guosen.bussinessuserwithdraw.entity.BussinessUserWithdraw;
import org.springblade.modules.guosen.bussinessuserwithdraw.vo.BussinessUserWithdrawVO;
import org.springblade.modules.guosen.bussinessuserwithdraw.wrapper.BussinessUserWithdrawWrapper;
import org.springblade.modules.guosen.bussinessuserwithdraw.service.IBussinessUserWithdrawService;
import org.springblade.core.boot.ctrl.BladeController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-10-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-bussiness-user-withdraw/bussinessuserwithdraw")
@Api(value = "", tags = "接口")
public class BussinessUserWithdrawController extends BladeController {

	private final IBussinessUserWithdrawService bussinessUserWithdrawService;
	private final BussinessPayService bussinessPayService;
	@Autowired
	private IParamService paramService;
	@Autowired
	private IBussinessInfoService bussinessInfoService;
	@Autowired
	private IBussinessUserInfoService userInfoService;
	@Autowired
	private IBussinessTransferOrderService transferOrderService;
	@Autowired
	private IBussinessService bussinessService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入bussinessUserWithdraw")
	public R<BussinessUserWithdrawVO> detail(BussinessUserWithdraw bussinessUserWithdraw) {
		BussinessUserWithdraw detail = bussinessUserWithdrawService.getOne(Condition.getQueryWrapper(bussinessUserWithdraw));
		return R.data(BussinessUserWithdrawWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入bussinessUserWithdraw")
	public R<IPage<BussinessUserWithdrawVO>> list(BussinessUserWithdraw bussinessUserWithdraw, Query query, BladeUser bladeUser) {
		Date createTime = bussinessUserWithdraw.getCreateTime();
		String createTimeFormat = null;
		if(createTime != null){
			bussinessUserWithdraw.setCreateTime(null);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			createTimeFormat = sdf.format(createTime);
		}
		LambdaQueryWrapper<BussinessUserWithdraw> lambda = Condition.getQueryWrapper(bussinessUserWithdraw).lambda();
		lambda.like(createTime != null, BussinessUserWithdraw::getCreateTime, createTimeFormat);
		lambda.eq(StringUtil.isNotBlank(bussinessUserWithdraw.getBussinessOrderId()), BussinessUserWithdraw::getBussinessOrderId, bussinessUserWithdraw.getBussinessOrderId());
		String roleName = bladeUser.getRoleName();
		if(roleName.equals("商户")){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda().eq(Bussiness::getAccountId, bladeUser.getUserId()));
			lambda.eq(BussinessUserWithdraw::getBussinessId, bussiness.getId());
		}
		IPage<BussinessUserWithdraw> pages = bussinessUserWithdrawService.page(Condition.getPage(query), lambda.orderByDesc(BussinessUserWithdraw::getCreateTime));
		return R.data(BussinessUserWithdrawWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入bussinessUserWithdraw")
	public R<IPage<BussinessUserWithdrawVO>> page(BussinessUserWithdrawVO bussinessUserWithdraw, Query query) {
		IPage<BussinessUserWithdrawVO> pages = bussinessUserWithdrawService.selectBussinessUserWithdrawPage(Condition.getPage(query), bussinessUserWithdraw);
		return R.data(pages);
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入bussinessUserWithdraw")
	public R save(@Valid @RequestBody BussinessUserWithdraw bussinessUserWithdraw) {
		return R.status(bussinessUserWithdrawService.save(bussinessUserWithdraw));
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入bussinessUserWithdraw")
	public R update(@Valid @RequestBody BussinessUserWithdraw bussinessUserWithdraw) {
		return R.status(bussinessUserWithdrawService.updateById(bussinessUserWithdraw));
	}

	/**
	 * 新增或修改 
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入bussinessUserWithdraw")
	public R submit(@Valid @RequestBody BussinessUserWithdraw bussinessUserWithdraw) {
		return R.status(bussinessUserWithdrawService.saveOrUpdate(bussinessUserWithdraw));
	}

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(bussinessUserWithdrawService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 提现统计
	 */
	@GetMapping("/withdrawStat")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "提现统计", notes = "传入withdraw")
	public R<BigDecimal> withdrawStat(BussinessUserWithdraw withdraw) {
		BigDecimal bigDecimal = this.bussinessUserWithdrawService.withdrawStat(withdraw);
		return R.data(bigDecimal);
	}

	/**
	 *
	 */
	@PostMapping("/payToUser")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "向用户付款", notes = "传入ids")
	public R payToUser(@Valid @RequestBody BussinessUserWithdraw withdraw) {
		String maintain = paramService.getValue("maintain");
		if(StringUtil.isNotBlank(maintain)){
			if(maintain.equals("0")){ //进入维护时间
				return R.fail("系统维护时间为每天晚上22:00-凌晨07:00");
			}
		}
		Long userInfoId = withdraw.getUserInfoId();
		BussinessUserInfo userInfo = userInfoService.getById(userInfoId);
		if(userInfo.getRegisterStatus().intValue() != SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("用户未完成进件，请勿发起付款");
		}
		BussinessInfo bussinessInfo = bussinessInfoService.getByBussinessId(userInfo.getBussinessId());
		R<WithdrawTransferOrder> result = this.bussinessUserWithdrawService.initWithdrawOrder(withdraw);
		if(result.isSuccess()) {
			WithdrawTransferOrder withdrawTransferOrder = result.getData();
			R firstTransferResult = bussinessPayService.transferOrder(withdrawTransferOrder.getTransferOrder(), bussinessInfo.getParentMerchantNo());
			BussinessUserWithdraw dbWithdraw = withdrawTransferOrder.getWithdraw();
			BussinessTransferOrder firstTransferOrder = withdrawTransferOrder.getTransferOrder();
			if (firstTransferResult.isSuccess()) {
				dbWithdraw.setFailReason("受理成功，请等待结果");
				dbWithdraw.setReturnMsg(firstTransferResult.getMsg());
				this.bussinessUserWithdrawService.updateById(dbWithdraw);
				if(firstTransferResult.getMsg().equals("REQUEST_RECEIVE")){
					this.bussinessPayService.handleFirstTransferScene(firstTransferOrder.getId());
				}else if(firstTransferResult.getMsg().equals("SUCCESS")){
					firstTransferOrder.setTransferStatus(SystemConstant.TransferOrderStatus.SUCCESS.getValue());
					this.transferOrderService.updateById(firstTransferOrder);
					String withdrawRate = paramService.getValue("yee_withdraw_rate");
					BussinessTransferOrder secondTransferOrder = new BussinessTransferOrder();
					secondTransferOrder.setFromMerchantNo(firstTransferOrder.getToMerchantNo());
					secondTransferOrder.setToMerchantNo(dbWithdraw.getMerchantNo());
					secondTransferOrder.setTransferUsage("提现前转账给小微商户");
					secondTransferOrder.setOrderAmount((dbWithdraw.getOrderAmount().add(new BigDecimal(withdrawRate))).toString());
					secondTransferOrder.setFeeChargeSide("OUTSIDE");
					secondTransferOrder.setRequestNo(UUID.randomUUID().toString().replaceAll("-","").toUpperCase());
					secondTransferOrder.setTransferScene(SystemConstant.TransferScene.FOR_WITHDRAW_SECOND_TRANSFER.getValue());
					secondTransferOrder.setTransferStatus(SystemConstant.TransferOrderStatus.WAIT.getValue());
					this.transferOrderService.save(secondTransferOrder);
					dbWithdraw.setSecondTransferOrderId(secondTransferOrder.getId());
					this.bussinessUserWithdrawService.updateById(dbWithdraw);
					R secondTransferResult = this.bussinessPayService.transferOrder(secondTransferOrder, firstTransferOrder.getToMerchantNo());
					if(secondTransferResult.isSuccess()){
						if(secondTransferResult.getMsg().equals("REQUEST_RECEIVE")){
							this.bussinessPayService.handleSecondTransferScene(secondTransferOrder.getId());
						}else if(secondTransferResult.getMsg().equals("SUCCESS")){
							secondTransferOrder.setTransferStatus(SystemConstant.TransferOrderStatus.SUCCESS.getValue());
							this.transferOrderService.updateById(secondTransferOrder);
							this.bussinessPayService.withdrawOrder(dbWithdraw, userInfo.getParentMerchantNo());
						}
					}else{
						dbWithdraw.setFailReason("代付失败");
						dbWithdraw.setReturnMsg(secondTransferResult.getMsg());
						dbWithdraw.setWithdrawStatus(SystemConstant.WithdrawOrderStatus.FAIL.getValue());
						this.bussinessUserWithdrawService.updateById(dbWithdraw);
						return R.fail("代付失败");
					}
				}
				return R.success("受理成功，请等待结果");
			} else {
				dbWithdraw.setFailReason("代付失败");
				dbWithdraw.setReturnMsg(firstTransferResult.getMsg());
				dbWithdraw.setWithdrawStatus(SystemConstant.WithdrawOrderStatus.FAIL.getValue());
				this.bussinessUserWithdrawService.updateById(dbWithdraw);
				return R.fail("代付失败");
			}
		}
		return result;
	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-withdraw")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出代付数据", notes = "传入user")
	public void exportUser(@ApiIgnore BussinessUserWithdrawDTO withdrawDTO, BladeUser bladeUser, HttpServletResponse response) {
		Integer withdrawStatus = withdrawDTO.getWithdrawStatus();
		String createTimeStr = withdrawDTO.getCreateTimeStr();
		String createTimeFormat = null;
		if(StringUtil.isNotBlank(createTimeStr)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			createTimeFormat = sdf.format(DateUtil.parse(createTimeStr, "yyyy-MM-dd"));
		}
		LambdaQueryWrapper<BussinessUserWithdraw> lambda = new LambdaQueryWrapper<>();
		lambda.eq(withdrawStatus != null, BussinessUserWithdraw::getWithdrawStatus, withdrawStatus);
		lambda.like(StringUtil.isNotBlank(createTimeStr), BussinessUserWithdraw::getCreateTime, createTimeFormat);
		if(bladeUser.getRoleName().equals("商户")){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
							.eq(Bussiness::getAccountId, bladeUser.getUserId()));
			Assert.notNull(bussiness, "商户不存在");
			lambda.eq(BussinessUserWithdraw::getBussinessId, bussiness.getId());
		}
		List<WithdrawExcel> list = this.bussinessUserWithdrawService.exportWithdraw(lambda);
		ExcelUtil.export(response, "代付数据" + DateUtil.time(), "代付数据表", list, WithdrawExcel.class);
	}
	
}
