package org.springblade.modules.time;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springblade.common.constant.SystemConstant;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.billRecord.entity.BillRecord;
import org.springblade.modules.guosen.billRecord.service.IBillRecordService;
import org.springblade.modules.guosen.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusAccount;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusRecords;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusStatic;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusAccountService;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusRecordsService;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusStaticService;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.modules.system.service.IParamService;
import org.springframework.beans.factory.annotation.Autowired;
		import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
@EnableScheduling
@RestController
@RequestMapping("sync")
@Slf4j
public class TimeTask {

	@Resource
	private StringRedisTemplate stringRedisTemplate;
	@Resource
	private IBillRecordService billRecordService;
	@Resource
	private IBussinessBonusStaticService bussinessBonusStaticService;
	@Autowired
	private IBussinessBonusAccountService bussinessBonusAccountService;
	@Autowired
	private IBussinessBonusRecordsService bussinessBonusRecordsService;
	@Autowired
	private IParamService paramService;
	@Autowired
	private IBussinessService bussinessService;

	@Scheduled(cron = "0 0 0 * * ?")
	public  void clearRedis() {
		Set<String> keys = stringRedisTemplate.keys(SystemConstant.WITHDRAW_KEY + "*");
		stringRedisTemplate.delete(keys);
	}

	/**
	 * 凌晨0时5分
	 */
	@GetMapping("/testBonus")
	@Scheduled(cron = "0 5 0 * * ?")
	public void generateAdsBonus() {
		//获取前一天的日期
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);

		Date yesterday = calendar.getTime();
		//查询采购商充值记录
		List<BillRecord> billRecords = billRecordService.getBaseMapper().selectList(new QueryWrapper<>(new BillRecord()).lambda()
			.eq(BillRecord::getType, SystemConstant.BillRecordType.ADS.getValue()).like(BillRecord::getCreateTime, df.format(yesterday))
			.eq(BillRecord::getPayStatus, SystemConstant.BillRecordPayStatus.PAYED.getValue()));
		//采购商充值总额
		BigDecimal total = billRecords.stream().map(BillRecord::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
		//分润金额=每一笔充值的服务费-（每一笔充值金额*每一笔充值金额的交易方式的费率），这里遇到充值方式为扫码的时候才进行相减。否则直接=充值服务费
		BigDecimal bussinessFee = billRecords.stream().map(BillRecord::getBussinessFee).reduce(BigDecimal.ZERO, BigDecimal::add);
		//计算支付手续费
		BigDecimal baseRate = new BigDecimal(paramService.getValue("yee_base_rate")).multiply(new BigDecimal(10));//0.21 * 10 = 2.1
		BigDecimal saasBaseRate = new BigDecimal(paramService.getValue("yee_saas_rate")).multiply(new BigDecimal(10));//0.1 * 10 = 1
		BigDecimal yeeRate = baseRate.add(saasBaseRate);
		BigDecimal yeeFee = billRecords.stream().map(record -> {
			return record.getPrice().multiply(yeeRate);
		}).reduce(BigDecimal.ZERO, BigDecimal::add);

		BigDecimal bonusAmt = new BigDecimal(0.00);
		List<Bussiness> platformBusinessList = this.bussinessService.list(new LambdaQueryWrapper<Bussiness>()
						.eq(Bussiness::getBussinessType, SystemConstant.BussinessType.PLATFORM_MERCHANT.getValue())
						.eq(Bussiness::getRegisterStatus, SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()));
		for(Bussiness bussiness : platformBusinessList){
			R<BigDecimal> result = this.bussinessService.queryBalance(bussiness.getMerchantNo());
			if(result.isSuccess()){
				bonusAmt = bonusAmt.add(result.getData());
			}
		}
		BussinessBonusStatic bussinessBonusStatic = new BussinessBonusStatic();
		bussinessBonusStatic.setDate(yesterday);
		bussinessBonusStatic.setFee(yeeFee);
		bussinessBonusStatic.setTotalAmt(total);
		bussinessBonusStatic.setServiceAmt(bussinessFee);
		bussinessBonusStatic.setBonusAmt(bonusAmt);

		bussinessBonusStaticService.save(bussinessBonusStatic);

	}

	@PostMapping("/testBonusRecords")
	@Scheduled(cron = "0 30 0 * * ?")
	public void generateAdsBonusRecords() {
		//获取前一天的日期
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);

		Date yesterday = calendar.getTime();
		BussinessBonusStatic bonusStatic = bussinessBonusStaticService.getBaseMapper().selectOne(new QueryWrapper<>(new BussinessBonusStatic()).lambda()
				.like(BussinessBonusStatic::getDate, df.format(yesterday)));

		List<BussinessBonusAccount> accountList = bussinessBonusAccountService.list();
		for(BussinessBonusAccount account : accountList){
			BussinessBonusRecords record = new BussinessBonusRecords();
			record.setBonusAccountId(account.getId());
			record.setBonusAccountName(account.getAccount());
			record.setBonusStatus(SystemConstant.BussinessBonusStatus.WATING.getValue());
			record.setRate(account.getRate());
			record.setBonusDate(yesterday);
			BigDecimal bonusAmt = bonusStatic.getBonusAmt();
			record.setPrice((bonusAmt.multiply(account.getRate())).setScale(2, BigDecimal.ROUND_HALF_UP));
			bussinessBonusRecordsService.saveOrUpdate(record);
		}
	}

	@PostMapping("/testBonusStat")
	public void testBonusStat(@Param(value = "beginDateStr") String beginDateStr, @Param(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 bussinessFee = billRecords.stream().map(BillRecord::getBussinessFee).reduce(BigDecimal.ZERO, BigDecimal::add);
			//计算支付手续费
			BigDecimal baseRate = new BigDecimal(paramService.getValue("yee_base_rate")).multiply(new BigDecimal(10));//0.21 * 10 = 2.1
			BigDecimal saasBaseRate = new BigDecimal(paramService.getValue("yee_saas_rate")).multiply(new BigDecimal(10));//0.1 * 10 = 1
			BigDecimal yeeRate = baseRate.add(saasBaseRate);
			BigDecimal fee = billRecords.stream().map(record -> {
				return record.getPrice().multiply(yeeRate);
			}).reduce(BigDecimal.ZERO, BigDecimal::add);

			BigDecimal bonusAmt = new BigDecimal(0.00);
			List<Bussiness> platformBusinessList = this.bussinessService.list(new LambdaQueryWrapper<Bussiness>()
							.eq(Bussiness::getBussinessType, SystemConstant.BussinessType.PLATFORM_MERCHANT.getValue())
							.eq(Bussiness::getRegisterStatus, SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()));
			for(Bussiness bussiness : platformBusinessList){
				R<BigDecimal> result = this.bussinessService.queryBalance(bussiness.getMerchantNo());
				if(result.isSuccess()){
					bonusAmt = bonusAmt.add(result.getData());
				}
			}

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

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

	/**
	 * 晚上22点
	 */
	@Scheduled(cron = "0 0 22 * * ?")
	public void closeSystem() {
		LambdaQueryWrapper<org.springblade.modules.system.entity.Param> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(org.springblade.modules.system.entity.Param::getParamKey, "maintain");
		org.springblade.modules.system.entity.Param param = paramService.getOne(lambdaQueryWrapper);
		if(param != null){
			param.setParamValue("0");
			paramService.saveOrUpdate(param);
		}
	}

	/**
	 * 早上7点
	 */
	@Scheduled(cron = "0 0 7 * * ?")
	public void openSystem() {
		LambdaQueryWrapper<org.springblade.modules.system.entity.Param> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(org.springblade.modules.system.entity.Param::getParamKey, "maintain");
		org.springblade.modules.system.entity.Param param = paramService.getOne(lambdaQueryWrapper);
		if(param != null){
			param.setParamValue("1");
			paramService.saveOrUpdate(param);
		}
	}

	/**
	 * 早上5点
	 */
//	@Scheduled(cron = "0 0 5 * * ?")
//	public void transferFormPlatformToBusiness() {
//		String toMerchantNo = paramService.getValue("self_merchant_no");
//		//获取前一天的日期
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//		Calendar calendar = Calendar.getInstance();
//		calendar.add(Calendar.DATE, -1);
//
//		Date yesterday = calendar.getTime();
//		BussinessBonusStatic bonusStatic = bussinessBonusStaticService.getBaseMapper().selectOne(new QueryWrapper<>(new BussinessBonusStatic()).lambda()
//				.like(BussinessBonusStatic::getDate, df.format(yesterday)));
//
//		if(bonusStatic.getBonusAmt() != null && bonusStatic.getBonusAmt().compareTo(new BigDecimal(2)) == 1){
//			BussinessTransferOrder transferOrder = new BussinessTransferOrder();
//			transferOrder.setRequestNo(UUID.randomUUID().toString().replaceAll("-","").toUpperCase());
//			transferOrder.setOrderAmount(bonusStatic.getBonusAmt().toString());
//			transferOrder.setFromMerchantNo(yeePayConst.getParentMerchantNo());
//			transferOrder.setToMerchantNo(toMerchantNo);
//			transferOrder.setTransferUsage("采购");
//			transferOrder.setFeeChargeSide("OUTSIDE");
//			boolean save = bussinessTransferOrderService.save(transferOrder);
//			BussinessInfo bussinessInfo = this.bussinessInfoService.getByMerchantNo(transferOrder.getFromMerchantNo());
//			if(save){
//				//发起充值服务费转账。
//				bussinessTransferOrderService.transferOrder(transferOrder, bussinessInfo.getParentMerchantNo());
//			}else{
//				log.error("=======================分润转账业务订单保存失败========================");
//				log.error(JSONUtil.toJsonStr(transferOrder));
//			}
//		}
//	}

	/**
	 * 仅用于测试
	 */
//	@GetMapping("/testBonus111")
//	public void testsss(){
//		List<BussinessBonusAccount> bonusAccountList = bussinessBonusAccountService.list();
//		BussinessBonusAccount account = bonusAccountList.stream().filter(item -> item.getReceiverAccountName().equals("广州士多啤梨传媒有限公司")).collect(Collectors.toList()).get(0);
//		System.out.println(account);
//	}
}
