package com.cyksj.web.controller.invoice;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.request.UserInvoiceOrderReq;
import com.cyksj.model.views.UserInvoiceChoseOrderViews;
import com.cyksj.model.views.UserInvoiceFrontView;
import com.cyksj.model.views.UserInvoiceHeadView;
import com.cyksj.model.views.UserInvoiceOrderViews;
import com.cyksj.service.invoice.UserInvoiceApplyRecordService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目名: yhlxj
 * 文件名: UserInvoiceFrontController
 * 创建者: JavaZou
 * 创建时间:2024/12/13 16:22
 */
@RestController
@RequestMapping("/applets/invoice")
@RequiredArgsConstructor
public class UserInvoiceFrontController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserInvoiceApplyRecordService userInvoiceApplyRecordService;

	private final UserBindRelationService userBindRelationService;

	/**
	 * 发票 用户可选AI车票订单
	 */
	@GetMapping("/get/orders")
	public Result<SearchResult<UserInvoiceChoseOrderViews>> getOrders() {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		String dateCondition;
		DateTime now = DateTime.now();
		String thisSixMontStr = DateUtil.thisYear() + "-06-01";
		//当前时间达到6月份 可开发票的订单只能是24年的 去年的发票只能截至到次年5月底
		if (now.isAfter(DateUtil.parse(thisSixMontStr))) {
			dateCondition = String.format(" and o.created_time >= '%s'", DateUtil.beginOfYear(now));
		} else {
			dateCondition = String.format(" and o.created_time >= '%s'", DateUtil.offsetMonth(DateUtil.beginOfYear(now), -12));
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		//过滤appid 品如
		List<String> appIds = Lists.newArrayList("2021003159660212");
		//1月底后 过滤木棉订单
		if (now.isAfter(DateUtil.parse("2025-02-01"))) {
			appIds.add("2021003171697073");
		}
		builder.field(UserInvoiceChoseOrderViews::getShopId, appIds).op(Operator.NotIn);
		SearchResult<UserInvoiceChoseOrderViews> search = beanSearcher.search(UserInvoiceChoseOrderViews.class, builder
				.put("dc", dateCondition)
				.field(UserInvoiceChoseOrderViews::getUserId, userIdList).op(Operator.InList)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 提交发票申请
	 */
	@PostMapping("/apply")
	public Result<Long> apply(@RequestBody UserInvoiceOrderReq req) {
		long userId = StpUserUtil.getLoginIdAsLong();
		req.setUserId(userId);
		Long recordId = userInvoiceApplyRecordService.applyOrderInvoice(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult(recordId);
	}

	/**
	 * 用户发票申请列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<UserInvoiceFrontView>> get() {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		SearchResult<UserInvoiceFrontView> search = beanSearcher.search(UserInvoiceFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserInvoiceFrontView::getUserId, userIdList).op(Operator.InList)
				.orderBy(UserInvoiceFrontView::getId).desc()
				.build());
		search.getDataList().forEach(data->{
			data.setOrderViews(beanSearcher.searchAll(UserInvoiceOrderViews.class, MapUtils.builder().field(UserInvoiceOrderViews::getRecordId, data.getId()).build()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 用户申请的发票抬头列表
	 */
	@GetMapping("/get/head")
	public Result<List<UserInvoiceHeadView>> getHead() {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		List<String> collect = beanSearcher.searchAll(UserInvoiceHeadView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserInvoiceHeadView::getUserId, userIdList).op(Operator.InList)
				.orderBy(UserInvoiceHeadView::getId).desc()
				.build()).stream().map(UserInvoiceHeadView::getHead).distinct().collect(Collectors.toList());
		List<UserInvoiceHeadView> list = new ArrayList<>(collect.size());
		collect.forEach(head -> {
			UserInvoiceHeadView userInvoiceHeadView = beanSearcher.searchFirst(UserInvoiceHeadView.class, MapUtils.builder().field(UserInvoiceHeadView::getUserId, userIdList).op(Operator.InList)
					.field(UserInvoiceHeadView::getHead, head)
					.orderBy(UserInvoiceHeadView::getId).desc()
					.build());
			list.add(userInvoiceHeadView);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(list);
	}
}
