package com.cyksj.web.controller.external;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.manage.exchange.ExchangeCodeMapper;
import com.cyksj.model.entity.ExchangeCode;
import com.cyksj.model.entity.GoodsDon;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.model.entity.OrderDon;
import com.cyksj.model.request.ExchangeCodeReq;
import com.cyksj.model.views.ExternalExchangeCodeView;
import com.cyksj.service.exchange.ExchangeCodeService;
import com.cyksj.service.mange.MirrorUserCleatService;
import com.cyksj.service.order.OrderCommonService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 项目名: yhlxj
 * 文件名: ExternalController
 * 创建者: JavaZou
 * 创建时间:2024/6/11 15:01
 */
@RestController
@RequestMapping("/external/app")
@RequiredArgsConstructor
public class ExternalController {
	private final HttpServletRequest request;

	private final BeanSearcher beanSearcher;

	private final ExchangeCodeMapper exchangeCodeMapper;

	private final OrderDonMapper orderDonMapper;

	private final OrderCommonService orderCommonService;

	private final GoodsDonSkuMapper skuMapper;

	private final GoodsDonMapper goodsDonMapper;

	private final ExchangeCodeService exchangeCodeService;

	private final MirrorUserCleatService mirrorUserCleatService;

	/**
	 * 知乎 特殊镜像规格 兑换码列表
	 */
	@GetMapping("/get/mirror")
	public Result<SearchResult<ExternalExchangeCodeView>> getMirror() {
		//目前只展示规格id 444 GPT基础镜像2月
		List<Long> showSkuId = List.of(444l);
		SearchResult<ExternalExchangeCodeView> search = beanSearcher.search(ExternalExchangeCodeView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(ExternalExchangeCodeView::getSkuIds, showSkuId.toString())
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 退款 成功 重新生成兑换码
	 */
	@PutMapping("/refund/{id}")
	@Transactional(rollbackFor = Throwable.class)
	public Result<String> refund(@PathVariable Long id) throws Exception {
		ExchangeCode exchangeCode = exchangeCodeMapper.selectById(id);
		Assert.notNull(exchangeCode, "系统异常");
		if (!exchangeCode.getUseStatus()) {
			throw BusinessRuntimeException.getInstance("兑换码未使用");
		}
		if (DateTime.now().after(DateUtil.offsetDay(exchangeCode.getUseTime(), 1))) {
			throw BusinessRuntimeException.getInstance("用户使用超过24小时不可退款");
		}
		if (StrUtil.equals(exchangeCode.getOrderStatus(), "refund")) {
			throw BusinessRuntimeException.getInstance("兑换码已退");
		}
		String skuIds = exchangeCode.getSkuIds();
		List<Long> skuIdList = Jsons.parseList(skuIds, Long.class);
		OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
				.eq(OrderDon::getExCode, exchangeCode.getCode())
				.notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
				.last("limit 1"));
		if (orderDon == null) {
			orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
					.eq(OrderDon::getUserId, exchangeCode.getUserId())
					.eq(OrderDon::getType, OrderDon.Type.EX_CODE)
					.eq(OrderDon::getSkuId, skuIdList.get(0))
					.notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
					.last("limit 1"));
		}
		if (orderDon != null) {
			//将mirror车票清空
			orderDon.setStatus(OrderDon.Status.refund);
			orderDonMapper.updateById(orderDon);

			exchangeCode.setOrderStatus("refund");
			exchangeCodeMapper.updateById(exchangeCode);

			//虚物订单退款,清出车队,车票变为已过期
			try {
				GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
				GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
				orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);

				//清除gtpUser
				if (orderDon.getOrderType() == 1) {
					mirrorUserCleatService.delMirrorUser(goodsDon.getId(), orderDon.getRelationId(), null);
				}

				//重新生成兑换码
				ExchangeCodeReq exchangeCodeReq = new ExchangeCodeReq();
				exchangeCodeReq.setNumber(1);
				exchangeCodeReq.setSkuIds(List.of(orderDon.getSkuId()).toString());
				exchangeCodeService.createExchangeCode(exchangeCodeReq);
			} catch (Exception e) {
			}
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
