package com.cyksj.web.controller.cps;

import cn.hutool.core.util.StrUtil;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.manage.coupon.CouponDistributePopularizeMapper;
import com.cyksj.model.entity.GoodsDon;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserDistributePopularize;
import com.cyksj.model.views.UserDistributePopularizeView;
import com.cyksj.service.cps.CpsPopularizeService;
import com.cyksj.service.user.UserService;
import com.cyksj.web.util.StpCpsManageUser;
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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/*
 *项目名: netflix
 *文件名: CpsPopularizeController
 *创建者: JavaZou
 *创建时间:2023/5/15 15:03
 */
@RestController
@RequestMapping("/cps/manage/popularize")
@RequiredArgsConstructor
public class CpsPopularizeController {
	private final CpsPopularizeService cpsPopularizeService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final EnvCommonService envCommonService;

	private final CouponDistributePopularizeMapper couponDistributePopularizeMapper;

	private final UserService userService;

	/**
	 * 渠道推广链接列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<UserDistributePopularizeView>> getList() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("userId", String.format("and user_id = %s", cpsUserId));
		SearchResult<UserDistributePopularizeView> search = beanSearcher.search(UserDistributePopularizeView.class, builder.build());
		search.getDataList().forEach(data -> {
			data.setPopularizeLink(String.format(envCommonService.DISTRIBUTE_DEFAULT_URL_PREFIX, data.getCode()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 默认链接详情
	 */
	@GetMapping("/get/default")
	public Result<UserDistributePopularizeView> getDefaultDetail() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		User user = userService.getById(cpsUserId);
		UserDistributePopularizeView view = Optional.ofNullable(cpsPopularizeService.getDefaultPopularizeDetail(cpsUserId)).orElseGet(() -> {
			UserDistributePopularizeView newPopularizeView = new UserDistributePopularizeView();
			newPopularizeView.setOrders(0);
			newPopularizeView.setOrdersMoney(BigDecimal.ZERO);
			newPopularizeView.setWMoney(BigDecimal.ZERO);
			newPopularizeView.setGotMoney(BigDecimal.ZERO);
			return newPopularizeView;
		});
		if (StrUtil.isEmpty(user.getShowId())) {
			user.setShowId(userService.getUserShowId(user.getId()));
		}
		view.setPopularizeLink(String.format(envCommonService.DISTRIBUTE_DEFAULT_URL_PREFIX, user.getShowId()));
		//优惠码
		view.setCouponCode(couponDistributePopularizeMapper.getCouponCodeByUid(cpsUserId));
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}

	/**
	 * 新增推广链接
	 */
	@PostMapping("/post")
	@NoSubmit
	public Result<String> insert(@RequestBody UserDistributePopularize popularize) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		popularize.setUserId(cpsUserId);
		cpsPopularizeService.insert(popularize);
		return GatewayResponse.SUCCESS.newBuilder().toResult(String.format("%s?dsCode=%s", envCommonService.getDomain2(), popularize.getCode()));
	}

	/**
	 * 编辑推广链接
	 */
	@PutMapping("/put")
	@NoSubmit
	public Result<String> update(@RequestBody UserDistributePopularize popularize) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		popularize.setUserId(cpsUserId);
		cpsPopularizeService.update(popularize);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除推广链接
	 */
	@DeleteMapping("/delete/{id}")
	@NoSubmit
	public Result<String> deleteById(@PathVariable Long id) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		cpsPopularizeService.deleteById(cpsUserId, id);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 获取所有平台列表
	 */
	@GetMapping("/get/all/goods")
	public Result<List<GoodsDon>> getAllGoodsList(Boolean isNoBuyout) {
		MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
		//过滤买断制 平台
		String conditionSql;
		if (isNoBuyout != null && isNoBuyout) {
			mapBuilder.field(GoodsDon::getSpecialType).op(Operator.IsNull);
			conditionSql = "(select count(*) from goods_don_sku sku where sku.goods_id = g.id and sku.months = 300) = 0";
		} else {
			conditionSql = "(special_type is null or special_type != 'giftCard')";
		}
		conditionSql += "  and exists (select id from goods_don_sku sku where sku.goods_id = g.id limit 1)";
		List<GoodsDon> goodsDons = beanSearcher.searchAll(GoodsDon.class, mapBuilder
				.put("condition", conditionSql)
				.field(GoodsDon::getType, 1)
				.field(GoodsDon::getStatus, 1)
				.field(GoodsDon::getDeleted, true)
				.onlySelect(GoodsDon::getId, GoodsDon::getCategory, GoodsDon::getType, GoodsDon::getTitle, GoodsDon::getSecondType).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(goodsDons);
	}

	/**
	 * 复制客服活码链接
	 * 用于cps用户实物分销
	 */
	@GetMapping("/get/service/code")
	public Result<String> getServiceCodeUrl() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		return GatewayResponse.SUCCESS.newBuilder().toResult(cpsPopularizeService.getServiceCodeUrl(cpsUserId));
	}

}
