package com.cyksj.web.controller.manage.exchange;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.BusinessType;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.manage.cms.CmsUserMapper;
import com.cyksj.model.entity.CmsUser;
import com.cyksj.model.excel.ExcelExchangeCodeData;
import com.cyksj.model.request.ExchangeCodeReq;
import com.cyksj.model.views.ExchangeCodeView;
import com.cyksj.service.exchange.ExchangeCodeService;
import com.cyksj.service.mange.cms.service.CmsUserService;
import com.cyksj.web.util.EasyExcelUtils;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 *项目名: netflix
 *文件名: ExchangeCodeController
 *创建者: JavaZou
 *创建时间:2022/11/7 14:37
 */
@RestController
@RequestMapping("/manage/exchange/code")
@RequiredArgsConstructor
public class ExchangeCodeController {

	private final HttpServletRequest request;

	private final BeanSearcher beanSearcher;

	private final ExchangeCodeService exchangeCodeService;

	private final CmsUserMapper cmsUserMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final OrderDonMapper orderDonMapper;

	private final CmsUserService cmsUserService;

	/**
	 * 生成兑换码 并导出
	 */
	@GetMapping("/createAndExport")
	@SaCheckPermission("exchangeCode:add")
	@Log(module = "兑换码/生成兑换码", businessType = BusinessType.POST, isSaveRequestData = true)
	public void createAndExportCode(ExchangeCodeReq exchangeCodeReq, HttpServletResponse response) throws Exception {
		if (ObjectUtil.hasEmpty(exchangeCodeReq.getSkuIds(), exchangeCodeReq.getNumber())) {
			throw BusinessRuntimeException.getInstance("必填项为空");
		}
		long adminId = StpUtil.getLoginIdAsLong();
		CmsUser cmsUser = cmsUserMapper.selectById(adminId);
		exchangeCodeReq.setOperator(cmsUser.getNickname());
		List<ExcelExchangeCodeData> data =  exchangeCodeService.createExchangeCode(exchangeCodeReq);
		EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelExchangeCodeData.class, data, "银河兑换码","银河兑换码", ExcelTypeEnum.XLSX, null);
	}

	/**
	 * 兑换码列表
	 */
	@GetMapping("/get")
	@SaCheckPermission("exchangeCode:view")
	public Result<SearchResult<ExchangeCodeView>> getExchangeCodeView(Long goodsId, Long skuId) {
		long adminId = StpUtil.getLoginIdAsLong();
		String condition = StrUtil.EMPTY;
		if (goodsId != null) {
			condition = String.format(" and JSON_CONTAINS(goods_ids,'%s')", goodsId);
		}
		if (skuId != null) {
			condition += String.format(" and JSON_CONTAINS(sku_ids,'%s')", skuId);
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (StrUtil.isNotEmpty(condition)) {
			builder.put("condition", condition);
		}
		if (!cmsUserService.isRootRole(adminId)) {
			CmsUser cmsUser = cmsUserMapper.selectById(adminId);
			builder.field(ExchangeCodeView::getOperator, cmsUser.getNickname());
		}
		SearchResult<ExchangeCodeView> search = beanSearcher.search(ExchangeCodeView.class, builder.build());
		search.getDataList().forEach(data -> {
			try {
				List<Long> skuIds = Jsons.parseList(data.getSkuIds(), Long.class);
				data.setTitle(skuMapper.selectExchangeTitle(skuIds));
//				if (data.getUseStatus()) {
//					Optional.ofNullable(orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
//							.eq(OrderDon::getExCode, data.getCode())
//							.last("limit 1"))).ifPresent(exCodeOrder -> data.setOrderId(exCodeOrder.getId()));
//				}
			} catch (Exception e) {
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 导出兑换码
	 */
	@GetMapping("/export")
	@SaCheckPermission("exchangeCode:export")
	public void exportExchangeCode(HttpServletResponse response, Long goodsId, Long skuId) {
		long adminId = StpUtil.getLoginIdAsLong();
		String condition = StrUtil.EMPTY;
		if (goodsId != null) {
			condition = String.format(" and JSON_CONTAINS(goods_ids,'%s')", goodsId);
		}
		if (skuId != null) {
			condition += String.format(" and JSON_CONTAINS(sku_ids,'%s')", skuId);
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (StrUtil.isNotEmpty(condition)) {
			builder.put("condition", condition);
		}
		if (!cmsUserService.isRootRole(adminId)) {
			CmsUser cmsUser = cmsUserMapper.selectById(adminId);
			builder.field(ExchangeCodeView::getOperator, cmsUser.getNickname());
		}
		List<ExcelExchangeCodeData> data = beanSearcher.searchAll(ExcelExchangeCodeData.class, builder.build());
		EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelExchangeCodeData.class, data, "银河兑换码", "银河兑换码", ExcelTypeEnum.XLSX, null);
	}
}
