package com.cyksj.web.controller.invoice;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UpgradeOrderDonMapper;
import com.cyksj.mapper.vip.VipOrderDonMapper;
import com.cyksj.model.entity.OrderDon;
import com.cyksj.model.entity.UpgradeOrderDon;
import com.cyksj.model.entity.VipOrderDon;
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.Comparator;
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;

	private final UpgradeOrderDonMapper upgradeOrderDonMapper;

	private final VipOrderDonMapper vipOrderDonMapper;

	private final OrderDonMapper orderDonMapper;

	/**
	 * 发票 用户可选AI车票订单
	 */
	@GetMapping("/get/orders")
	public Result<List<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");
		}
		Integer orderCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
				.in(OrderDon::getUserId, userIdList)
				.notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
		builder.field(UserInvoiceChoseOrderViews::getShopId, appIds).op(Operator.NotIn)
				.put("dc", dateCondition)
				.field(UserInvoiceChoseOrderViews::getUserId, userIdList).op(Operator.InList);
		List<UserInvoiceChoseOrderViews> list = new ArrayList<>();
		if (orderCount > 0) {
			//普通订单
			String order_sql = "(select id,goods_id,sku_id,order_no,money,user_id,pay_time,shop_id,created_time,1 as type from order_don where money > 0 and status not in ('close','noPayment','refund') and type = 'ALI_PAY')";
			List<UserInvoiceChoseOrderViews> orderViewsList = beanSearcher.searchAll(UserInvoiceChoseOrderViews.class, builder.put("order", order_sql).build());
			if (CollUtil.isNotEmpty(orderViewsList)) {
				list.addAll(orderViewsList);
			}
		}
		Integer upgradeOrders = upgradeOrderDonMapper.selectCount(Wrappers.lambdaQuery(UpgradeOrderDon.class)
				.in(UpgradeOrderDon::getUserId, userIdList)
				.notIn(UpgradeOrderDon::getStatus, Constant.noOrderAllStatus));
		if (upgradeOrders > 0) {
			//增值订单
			String upgrade_order_sql = "(select id,goods_id,sku_id,order_no,money,user_id,pay_time,shop_id,created_time,2 as type from upgrade_order_don where goods_id = 26 and money > 0 and status not in ('close','noPayment','refund') and type = 'ALI_PAY')";
			List<UserInvoiceChoseOrderViews> upgradeOrderList = beanSearcher.searchAll(UserInvoiceChoseOrderViews.class, builder.put("order", upgrade_order_sql).build());
			if (CollUtil.isNotEmpty(upgradeOrderList)) {
				list.addAll(upgradeOrderList);
			}
		}
		Integer vipOrderCount = vipOrderDonMapper.selectCount(Wrappers.lambdaQuery(VipOrderDon.class)
				.in(VipOrderDon::getUserId, userIdList)
				.notIn(VipOrderDon::getStatus, Constant.noOrderAllStatus));
		if (vipOrderCount > 0) {
			//会员订单
			String vip_order_sql = "(select id,goods_id,0 as sku_id,order_no,money,user_id,pay_time,shop_id,created_time,3 as type from vip_order_don where money > 0 and status not in ('close','noPayment','refund') and type = 'ALI_PAY')";
			List<UserInvoiceChoseOrderViews> vipOrderList = beanSearcher.searchAll(UserInvoiceChoseOrderViews.class, builder.put("order", vip_order_sql).build());
			if (CollUtil.isNotEmpty(vipOrderList)) {
				list.addAll(vipOrderList);
			}
		}
		if (CollUtil.isNotEmpty(list)) {
			list.sort(Comparator.comparing(UserInvoiceChoseOrderViews::getPayTime).reversed());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(list);
	}

	/**
	 * 提交发票申请
	 */
	@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);
	}
}
