/**
 *
 */
package org.springblade.finance.controller;

import cn.hutool.core.bean.BeanUtil;
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.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.excel.utils.ExcelUtil;
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.finance.dto.OrderUsersExcel;
import org.springblade.finance.entity.DealUserAccounts;
import org.springblade.finance.entity.OrderUsers;
import org.springblade.finance.entity.YksytOrderUsers;
import org.springblade.finance.service.DealUserAccountsService;
import org.springblade.finance.service.YksytOrderUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wookvn
 *
 */
@RestController
@RequestMapping("finance/yksytOrderUsers")
@Api(value = "互联网2-用户发展量", tags = "互联网2-用户发展量接口")
public class YksytOrderUsersController extends  BladeController{

	@Autowired
	private YksytOrderUsersService yksytOrderUsersService;

	@Autowired
	private DealUserAccountsService dealUserAccountsService;


	/**
	 * @param query
	 * @return
	 */
	@GetMapping("/list")
	@ApiOperation(value = "分页查询互联网2用户发展量")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "dealUserIds", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
		@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
		@ApiImplicitParam(name = "startDate", value = "开始日期(格式：yyyy-MM-dd/yyyy-MM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endDate", value = "结束日期(格式：yyyy-MM-dd/yyyy-MM)", dataType = "string", required = false)
	})
	public R<IPage<YksytOrderUsers>> list(String[] dealUserIds, String spid, String startDate, String endDate, Query query){
		if(query.getSize() == null){
			query.setSize(5);
		}
		LambdaQueryWrapper<YksytOrderUsers> queryWrapper = Wrappers.<YksytOrderUsers>lambdaQuery();
		if(dealUserIds != null && dealUserIds.length > 0) {
			List<String> strings = Arrays.asList(dealUserIds);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in(YksytOrderUsers::getDealAccountId, collect);
		}
		if(StringUtils.isNotEmpty(spid)) {
			queryWrapper.eq(YksytOrderUsers::getSpid, spid);
		}
		if(StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
			int dateType = parseDateString(startDate);
			if(dateType != 0) {
				Integer intStartDate = Integer.valueOf(startDate.replaceAll("\\-", ""));
				Integer intEndDate = Integer.valueOf(endDate.replaceAll("\\-", ""));
				queryWrapper.between(dateType == 1 ? YksytOrderUsers::getTheDay : YksytOrderUsers::getTheMonth, intStartDate, intEndDate);
			}
		}
		return R.data(yksytOrderUsersService.page(Condition.getPage(query), queryWrapper.orderByDesc(YksytOrderUsers::getTheDay, YksytOrderUsers::getChannelId)));
	}

	/**
	 *
	 * @param dealUserid
	 * @param spid
	 * @param startDate
	 * @param endDate
	 */
	@GetMapping("/export")
	@ApiOperation(value = "导出用户发展量")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "dealUserid", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
		@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
		@ApiImplicitParam(name = "startDate", value = "开始日期(格式：yyyy-MM-dd/yyyy-MM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endDate", value = "结束日期(格式：yyyy-MM-dd/yyyy-MM)", dataType = "string", required = false)
	})
	public void export(String[] dealUserid, String spid, String startDate, String endDate, HttpServletResponse response) {
		LambdaQueryWrapper<YksytOrderUsers> queryWrapper = Wrappers.<YksytOrderUsers>lambdaQuery();
		if(dealUserid != null && dealUserid.length > 0) {
			List<String> strings = Arrays.asList(dealUserid);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in(YksytOrderUsers::getDealAccountId, collect);
		}
		if(StringUtils.isNotEmpty(spid)) {
			queryWrapper.eq(YksytOrderUsers::getSpid, spid);
		}
		if(StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
			int dateType = parseDateString(startDate);
			if(dateType != 0) {
				Integer intStartDate = Integer.valueOf(startDate.replaceAll("\\-", ""));
				Integer intEndDate = Integer.valueOf(endDate.replaceAll("\\-", ""));
				queryWrapper.between(dateType == 1 ? YksytOrderUsers::getTheDay : YksytOrderUsers::getTheMonth, intStartDate, intEndDate);
			}
		}
		List<YksytOrderUsers> resultList = yksytOrderUsersService.list(queryWrapper);
		List<OrderUsersExcel> orderUsersExcelList = new ArrayList<OrderUsersExcel>();
		if(resultList != null && resultList.size() > 0) {
			BigDecimal dayTotal = BigDecimal.ZERO, monthTotal = BigDecimal.ZERO;
			for(YksytOrderUsers item : resultList) {
				orderUsersExcelList.add(BeanUtil.copyProperties(item, OrderUsersExcel.class));
				dayTotal = dayTotal.add(item.getDayOrder());
				monthTotal = monthTotal.add(item.getMonthOrder());
			}
			OrderUsersExcel collectUserModel = new OrderUsersExcel();
			collectUserModel.setChannelName("合计");
			collectUserModel.setDayOrder(dayTotal);
			collectUserModel.setMonthOrder(monthTotal);
			orderUsersExcelList.add(collectUserModel);
		}
//		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("用户发展量表", Charsets.UTF_8.name()) + ".xlsx");
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		EasyExcel.write(baos, OrderUsersExcel.class).sheet("用户发展量表数据").doWrite(orderUsersExcelList);
//		return baos.toByteArray();
		ExcelUtil.export(response, "互联网2用户发展量表", "互联网2用户发展量表数据", orderUsersExcelList, OrderUsersExcel.class);
	}

	/**
	 *
	 * @param dateStr
	 * @return 0 - 无效； 1 - 日期； 2 - 月份
	 */
	private static int parseDateString(String dateStr) {
		try {
			DateTimeFormatter.ofPattern("yyyy-MM-dd").parse(dateStr);
			return 1; //Integer.valueOf(dateStr.replaceAll("\\-", ""));
		} catch (Exception e) {}
		try {
			DateTimeFormatter.ofPattern("yyyy-MM").parse(dateStr);
			return 2; //Integer.valueOf(dateStr.replaceAll("\\-", ""));
		} catch (Exception e) {}
		return 0;
	}

}
