/*
 *      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.billRecord.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.annotation.AccessLimit;
import org.springblade.common.constant.SystemConstant;
import org.springblade.core.boot.ctrl.BladeController;
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.billRecord.dto.BillRecordDTO;
import org.springblade.modules.guosen.billRecord.entity.BillRecord;
import org.springblade.modules.guosen.billRecord.service.IBillRecordService;
import org.springblade.modules.guosen.billRecord.vo.BillRecordVO;
import org.springblade.modules.guosen.billRecord.wrapper.BillRecordWrapper;
import org.springblade.modules.guosen.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusStatic;
import org.springblade.modules.guosen.bussiness.entity.BussinessDebit;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusStaticService;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.modules.guosen.bussinessGoods.dto.BussinessGoodsDTO;
import org.springblade.modules.guosen.bussinessGoods.entity.BussinessGoods;
import org.springblade.modules.guosen.bussinessInfo.entity.BussinessInfo;
import org.springblade.modules.guosen.bussinessInfo.service.IBussinessInfoService;
import org.springblade.modules.guosen.bussinessPurchaseRecord.service.IBussinessPurchaseRecordService;
import org.springblade.modules.guosen.bussinessuserwithdraw.entity.BussinessUserWithdraw;
import org.springblade.yeePay.entity.PayGateWayDto;
import org.springblade.yeePay.entity.RechargeDto;
import org.springblade.yeePay.service.YeePayService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-06-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-billRecord/billrecord")
@Api(value = "支付记录", tags = "支付记录")
public class BillRecordController extends BladeController {

	private final IBillRecordService billRecordService;
	private final IBussinessService bussinessService;
	private final IBussinessBonusStaticService bussinessBonusStaticService;
	private final YeePayService yeePayService;
	private final IBussinessInfoService bussinessInfoService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入billRecord")
	public R<BillRecordVO> detail(BillRecord billRecord) {
		BillRecord detail = billRecordService.getOne(Condition.getQueryWrapper(billRecord));
		return R.data(BillRecordWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入billRecord")
	@AccessLimit(second = 1, maxCount = 1)
	public R<IPage<BillRecordVO>> list(BillRecord billRecord, Query query) {
		IPage<BillRecord> pages = billRecordService.page(Condition.getPage(query), Condition.getQueryWrapper(billRecord).lambda().orderByDesc(BillRecord::getCreateTime));
		return R.data(BillRecordWrapper.build().pageVO(pages));
	}

	/**
	 * 分页
	 */
	@GetMapping("/getBussinessList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入billRecord")
	public R<IPage<BillRecordVO>> getBussinessList(BillRecord billRecord, Query query) {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
			.eq(Bussiness::getAccountId, user.getUserId()));
		if(bussiness != null){
			billRecord.setUserId(bussiness.getId());
		}
		Date createTime = billRecord.getCreateTime();
		String createTimeFormat = null;
		if(billRecord.getCreateTime() != null){
			billRecord.setCreateTime(null);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			createTimeFormat = sdf.format(createTime);
		}
		billRecord.setType(SystemConstant.BillRecordType.ADS.getValue());
		LambdaQueryWrapper<BillRecord> lambda = Condition.getQueryWrapper(billRecord).lambda();
		lambda.like(createTime != null, BillRecord::getCreateTime, createTimeFormat);
		IPage<BillRecord> pages = billRecordService.page(Condition.getPage(query),lambda.orderByDesc(BillRecord::getCreateTime));
		return R.data(BillRecordWrapper.build().pageVO(pages));
	}


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

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入billRecord")
	@AccessLimit(second = 2, maxCount = 1)
	public R save(@Valid @RequestBody BillRecord billRecord) {
		if(billRecord.getType() == SystemConstant.BillRecordType.ADS.getValue()){//采购商，获取当前登录对象
			BladeUser user = AuthUtil.getUser();
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
			Assert.notNull(bussiness,"当前账户为非采购商账户，不能为采购商采购");
			billRecord.setUserId(bussiness.getId());
			BigDecimal leastPrice = bussiness.getLeastPrice();
			if(leastPrice != null && billRecord.getPrice().compareTo(leastPrice) == -1){
				return R.fail("充值金额最低为" + leastPrice.toString());
			}
			BigDecimal serviceRate = bussiness.getServiceRate();
			BigDecimal price = billRecord.getPrice();
			BigDecimal bussinessFee = serviceRate.multiply(price).divide(new BigDecimal(1000));
			billRecord.setBussinessFee(bussinessFee);
		}
		return R.status(billRecordService.save(billRecord));
	}

	/**
	 * 采购商新增
	 */
	@PostMapping("/adSave")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入billRecord")
	@AccessLimit(second = 2, maxCount = 1)
	public R adSave(@Valid @RequestBody BillRecordDTO billRecord) {BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness,"当前账号为非采购商");
		if(bussiness.getRegisterStatus() == null || bussiness.getRegisterStatus().intValue() != SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("请先完成商户进件审核");
		}
		billRecord.setUserId(bussiness.getId());
		BigDecimal leastPrice = bussiness.getLeastPrice();
		List<BussinessGoodsDTO> purchaseList = billRecord.getPurchaseList();
		if(purchaseList == null || purchaseList.size() <= 0){
			return R.fail("采购商品不能为空");
		}
		if(leastPrice != null && billRecord.getPrice().compareTo(leastPrice) == -1){
			return R.fail("采购金额最低为" + leastPrice.toString());
		}
		R result = this.billRecordService.merchantRechargeOrder(bussiness, billRecord);
		return result;
	}

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入billRecord")
	public R submit(@Valid @RequestBody BillRecord billRecord) {

		Assert.notNull(billRecord.getUserId(),"支付人用户id不能为空");
		return R.status(billRecordService.saveOrUpdate(billRecord));
	}


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


	/**
	 * 获取订单详情
	 */
	@GetMapping("/getOrderDetail")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "通过bankOrderId获取订单详情", notes = "传入bankOrderId")
	public R getOrderDetail(@RequestParam String bankOrderId) {
		Assert.notNull(bankOrderId, "bankOrderId不能为空");
		return R.data(billRecordService.getOrderDetail(bankOrderId));
	}

	@PostMapping("/testStatBillRecord")
	@ApiOperationSupport(order = 9)
	public R testStatBillRecord(@RequestParam(value = "beginDateStr") String beginDateStr, @RequestParam(value = "endDateStr") String endDateStr){
		Date beginDate = DateUtil.parse(beginDateStr, "yyyy-MM-dd");
		Date endDate = DateUtil.parse(endDateStr, "yyyy-MM-dd");
		String fromDateStr = beginDateStr;
		while(beginDate.before(DateUtil.plusDays(endDate, 1))){
			//查询采购商充值记录
			List<BillRecord> billRecords = billRecordService.getBaseMapper().selectList(new QueryWrapper<>(new BillRecord()).lambda()
				.eq(BillRecord::getType, SystemConstant.BillRecordType.ADS.getValue()).like(BillRecord::getCreateTime, fromDateStr)
				.eq(BillRecord::getPayStatus, SystemConstant.BillRecordPayStatus.PAYED.getValue()));
			//采购商充值总额
			BigDecimal total = billRecords.stream().map(BillRecord::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
			//采购商充值技术服务总费用-即可分配利润
			BigDecimal bonusAmt = billRecords.stream().map(BillRecord::getBussinessFee).reduce(BigDecimal.ZERO, BigDecimal::add);


			BussinessBonusStatic bussinessBonusStatic = new BussinessBonusStatic();
			bussinessBonusStatic.setDate(beginDate);
			bussinessBonusStatic.setFee(BigDecimal.ZERO);
			bussinessBonusStatic.setTotalAmt(total);
			bussinessBonusStatic.setServiceAmt(bonusAmt);
			bussinessBonusStatic.setBonusAmt(bonusAmt);

			bussinessBonusStaticService.save(bussinessBonusStatic);
			beginDate = DateUtil.plusDays(beginDate, 1);
			fromDateStr = DateUtil.format(beginDate, "yyyy-MM-dd");
		}

		return R.status(true);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/billStat")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "采购统计", notes = "传入billRecord")
	public R<BigDecimal> billStat(BillRecord billRecord, BladeUser bladeUser) {
		String roleName = bladeUser.getRoleName();
		if(roleName.equals("商户")){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda().eq(Bussiness::getAccountId, bladeUser.getUserId()));
			billRecord.setUserId(bussiness.getId());
		}
		BigDecimal billStat = billRecordService.billStat(billRecord);
		return R.data(billStat);
	}

	/**
	 * 自定义分页
	 */
	@PostMapping("/gatewayPay")
	@ApiOperationSupport(order = 10)
	@AccessLimit(second = 2, maxCount = 1)
	public R gatewayPay(@RequestBody @Valid PayGateWayDto payGateWayDto) {
		LambdaQueryWrapper<BillRecord> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(BillRecord::getOrderId, payGateWayDto.getOrderId());
		BillRecord billRecord = billRecordService.getOne(lambdaQueryWrapper);
		if(billRecord == null){
			R.fail("订单不存在");
		}
		Long bussinessId = billRecord.getUserId();
		BussinessInfo info = bussinessInfoService.getByBussinessId(bussinessId);
		if(info != null && info.getRegisterStatus().intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			payGateWayDto.setMerchantNo(info.getMerchantNo());
			return yeePayService.payByGateWay(payGateWayDto);
		}else{
			return R.fail("请先完成商户进件");
		}
	}
}
