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

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
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.enums.AppConstant;
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.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.gateway.common_gateway.entity.dto.BillStatisticsDTO;
import org.springblade.gateway.common_gateway.entity.vo.BillStatisticsVO;
import org.springblade.ldt.account.entity.Account;
import org.springblade.ldt.account.vo.AccountVO;
import org.springblade.ldt.account.wrapper.AccountWrapper;
import org.springblade.ldt.bills.entity.BalanceBills;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.entity.PointBills;
import org.springblade.ldt.bills.service.IPointBillsService;
import org.springblade.ldt.bills.vo.PointBillsVO;
import org.springblade.ldt.bills.wrapper.PointBillsWrapper;
import org.springblade.ldt.mall.service.IMallService;
import org.springblade.ldt.shop.service.IShopService;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-09-06
 */
@RestController
@AllArgsConstructor
@RequestMapping("common/pointbills")
@Api(value = "", tags = "渠道积分接口")
public class AppPointBillsController extends BladeController {

	private final IPointBillsService pointBillsService;

	private final ILoginUserService loginUserService;

	private final IShopService shopService;

	private final IMallService mallService;

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入pointBills")
	public R<IPage<PointBillsVO>> list(PointBills pointBills, Query query) {
		String format = DateUtil.format(pointBills.getCreateTime(), "yyyy-MM");
		pointBills.setCreateTime(null);
		IPage<PointBills> pages = pointBillsService.page(Condition.getPage(query), Condition.getQueryWrapper(pointBills)
			.lambda()
			.like(format != null, PointBills::getCreateTime, format)
			.orderByDesc(PointBills::getCreateTime));
		return R.data(PointBillsWrapper.build(loginUserService,shopService,mallService).pageVO(pages));
	}

	/**
	 * 分页
	 */
	@GetMapping("/channelList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入pointBills")
	public R<IPage<PointBillsVO>> channelList(PointBills pointBills, Query query,Long userId) {
		String format = DateUtil.format(pointBills.getCreateTime(), "yyyy-MM");
		pointBills.setCreateTime(null);

		QueryWrapper<PointBills> queryWrapper = new QueryWrapper();
		queryWrapper.lambda()
			.eq(PointBills::getPayStatus,AppConstant.BillPayStatus.付款成功.name())
			.like(format!=null,PointBills::getCreateTime,format)
			.gt(PointBills::getPrice,BigDecimal.ZERO)
			.and(wrapper ->wrapper.eq(PointBills::getReceiveId,userId)
				.or().eq(PointBills::getPayId,userId))
			.orderByDesc(PointBills::getCreateTime);

		IPage<PointBills> pages = pointBillsService.page(Condition.getPage(query),queryWrapper);
		return R.data(PointBillsWrapper.build(loginUserService,shopService,mallService).pageVO(pages));
	}


	@GetMapping("/getPointBillStatistics")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "获取渠道积分统计数据", notes = "传入billStatisticsDTO")
	public R getPointBillStatistics(BillStatisticsDTO billStatisticsDTO) {

		Assert.notNull(billStatisticsDTO.getQueryDate(), "查询日期不能为空");
		String year = DateUtil.format(billStatisticsDTO.getQueryDate(), "YYYY");

		//获取统计数据
		int count = pointBillsService.count(Condition.getQueryWrapper(new PointBills()).lambda()
			.eq(billStatisticsDTO.getPayId() != null, PointBills::getPayId, billStatisticsDTO.getPayId())
			.eq(billStatisticsDTO.getReceiveId() != null, PointBills::getReceiveId, billStatisticsDTO.getReceiveId())
			.between(PointBills::getCreateTime, DateUtil.beginOfMonth(billStatisticsDTO.getQueryDate()), DateUtil.endOfMonth(billStatisticsDTO.getQueryDate())));

		//获取合计多少元
		QueryWrapper<PointBills> pointBillsQueryWrapper = Condition.getQueryWrapper(new PointBills());
		pointBillsQueryWrapper.select("SUM(" + billStatisticsDTO.getQueryColumn() + ") as totalMoney")
			.eq(billStatisticsDTO.getPayId() != null, "pay_id", billStatisticsDTO.getPayId())
			.eq(billStatisticsDTO.getReceiveId() != null, "receive_id", billStatisticsDTO.getReceiveId())
			.eq("pay_status", AppConstant.BillPayStatus.付款成功.name())
			.between("create_time", DateUtil.beginOfMonth(billStatisticsDTO.getQueryDate()), DateUtil.endOfMonth(billStatisticsDTO.getQueryDate()));
		Map<String, Object> map = pointBillsService.getMap(pointBillsQueryWrapper);
		BigDecimal totalMoney = BigDecimal.ZERO;
		if (MapUtil.isNotEmpty(map)) {
			totalMoney = Convert.toBigDecimal(map.get("totalMoney"));
		}
		//获取图表数据
		QueryWrapper<PointBills> queryWrapper = Condition.getQueryWrapper(new PointBills());
		queryWrapper.select("DATE_FORMAT(create_time, '%c') as month, sum("+billStatisticsDTO.getQueryColumn()+") as money")
			.eq("DATE_FORMAT(create_time, '%Y')", year)
			.eq("pay_status", AppConstant.BillPayStatus.付款成功.name())
			.eq(billStatisticsDTO.getPayId() != null, "pay_id", billStatisticsDTO.getPayId())
			.eq(billStatisticsDTO.getReceiveId() != null, "receive_id", billStatisticsDTO.getReceiveId())
			.groupBy("month");

		List<Map<String, Object>> listMaps = pointBillsService.listMaps(queryWrapper);
		List<String> monthList = listMaps.stream().map(item -> Convert.toStr(item.get("month"))+"月").collect(Collectors.toList());
		List<BigDecimal> dataList = listMaps.stream().map(item -> Convert.toBigDecimal(item.get("money"))).collect(Collectors.toList());

		BillStatisticsVO statisticsVO = BillStatisticsVO.builder()
			.payNum(count)
			.totalMoney(totalMoney)
			.monthList(monthList)
			.dataList(dataList).build();
		return R.data(statisticsVO);
	}

}
