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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopDistributeMoneyApplyMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.entity.UserMirrorShopDistributeMoneyApply;
import com.cyksj.model.request.DistributeApplyMoneyReq;
import com.cyksj.model.request.UserMirrorShopInfoApplyReq;
import com.cyksj.model.views.*;
import com.cyksj.service.mange.statistics.StatisticsDataService;
import com.cyksj.service.mange.usermirror.UserMirrorCommonService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * admin/镜像店铺
 * 项目名: yhlxj2
 * 文件名: UserMirrorShopController
 * 创建者: JavaZou
 * 创建时间:2024/10/18 17:07
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/mirror/shop")
public class UserMirrorShopController {

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserMapper userMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserMirrorCommonService userMirrorCommonService;

	private final UserMirrorShopDistributeMoneyApplyMapper moneyApplyMapper;

	private final StatisticsDataService statisticsDataService;


	/**
	 * 店铺列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<UserMirrorShopView>> getYhShopDistributeView(String nickname, String startTime, String endTime) {
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (StrUtil.isNotBlank(nickname)) {
			List<Long> userIds = userMapper.selectListByNickname(nickname);
			builder.field(YhShopDistributeView::getUserId, userIds).op(Operator.InList);
		}
		String timeSql = StrUtil.EMPTY;
		if (StrUtil.isNotBlank(startTime)) {
			timeSql += String.format("and od.created_time >= '%s'", startTime);
		}
		if (StrUtil.isNotBlank(endTime)) {
			timeSql += String.format("and od.created_time < '%s'", endTime);
		}
		if (StrUtil.isNotBlank(timeSql)) {
			builder.put("time", timeSql);
			//按时间筛选 固定推广人分销情况 倒序
			builder.orderBy(YhShopDistributeView::getDistributeOrdersMoney).desc();
		}
		SearchResult<UserMirrorShopView> search = beanSearcher.search(UserMirrorShopView.class, builder.build());
		search.getDataList().forEach(view -> {
			if (view.getDistributeOrdersMoney().compareTo(BigDecimal.ZERO) > 0) {
				Optional.ofNullable(userMirrorShopMapper.selectSoldMaxGoods(view.getUserId())).ifPresent(title -> view.setGoodsTitle(title));
			}
			Optional.ofNullable(userMapper.selectById(view.getUserId())).ifPresent(user -> view.setNickname(user.getNickname()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 修改店铺状态
	 */
	@PutMapping("/update/shop/status/{id}")
	public Result<String> updateShopStatusById(@PathVariable Long id) {
		Optional.ofNullable(userMirrorShopMapper.selectById(id)).ifPresent(shop->{
			shop.setStatus(!shop.getStatus());
			userMirrorShopMapper.updateById(shop);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 提现详情记录
	 */
	@GetMapping("/get/user/apply/detail/record/{userId}")
	public Result<UserMirrorShopView> getUserApplyDetailRecord(@PathVariable Long userId) {
		UserMirrorShopView userDistributeViews = moneyApplyMapper.getApplyDetailByUserId(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(userDistributeViews);
	}

	//--------------------------------------提现管理-----------------------------------------------

	/**
	 * 提现列表
	 */
	@GetMapping("/get/apply/list")
	public Result<SearchResult<UserMirrorShopDistributeMoneyApplyView>> applyMoneyList() {
		SearchResult<UserMirrorShopDistributeMoneyApplyView> search = beanSearcher.search(UserMirrorShopDistributeMoneyApplyView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 店铺提现 审核
	 */
	@PutMapping("/verify/applyMoney")
	@NoSubmit
	public Result<String> verifyApplyMoney(@RequestBody @Validated DistributeApplyMoneyReq distributeApplyMoneyReq) {
		userMirrorCommonService.verifyApplyMoney(distributeApplyMoneyReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult("审核操作成功");
	}

	/**
	 * 修改审核图片
	 */
	@PutMapping("/verify/applyMoney/img")
	public Result<String> updateVerifyImg(@RequestBody DistributeApplyMoneyReq distributeApplyMoneyReq) {
		userMirrorCommonService.updateVerifyImg(distributeApplyMoneyReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	//--------------------------------------加盟费管理-----------------------------------------------

	/**
	 * 加盟费 订单列表
	 */
	@GetMapping("/get/fee/list")
	public Result<SearchResult<UserMirrorShopFeeOrderDonView>> getFeeList() {
		SearchResult<UserMirrorShopFeeOrderDonView> search = beanSearcher.search(UserMirrorShopFeeOrderDonView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 加盟费 退款
	 */
	@PutMapping("/fee/refund/{orderId}")
	public Result<String> refundUserMirrorShopFee(@PathVariable Long orderId) throws Exception {
		userMirrorCommonService.refundUserMirrorShopFee(orderId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 店铺申请修改记录列表
	 */
	@GetMapping("/get/apply/info/list")
	public Result<SearchResult<UserMirrorShopApplyInfoView>> getUserShopApply() {
		SearchResult<UserMirrorShopApplyInfoView> search = beanSearcher.search(UserMirrorShopApplyInfoView.class, MapUtils.flatBuilder(request.getParameterMap())
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 店铺审核修改店铺信息
	 */
	@PutMapping("/verify")
	public Result<String> verifyYhShopApply(@RequestBody UserMirrorShopInfoApplyReq applyReq) {
		userMirrorCommonService.verifyUserMIrrorShopApply(applyReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 一键审核店铺信息
	 */
	@PutMapping("/batch/verify")
	public Result<String> batchVerify(@RequestBody UserMirrorShopInfoApplyReq verifyReq) {
		List<Long> ids = verifyReq.getIds();
		if (CollUtil.isEmpty(ids)) {
			throw BusinessRuntimeException.getInstance("请选择对应的审核记录");
		}
		ids.forEach(id -> {
			verifyReq.setId(id);
			userMirrorCommonService.verifyUserMIrrorShopApply(verifyReq);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 店铺头部数据
	 */
	@GetMapping("/get/head/data")
	public Result<BackgroundDataView> getHeadData(Long startTime, Long endTime) {
		BackgroundDataView backgroundDataView = new BackgroundDataView();
		Date startDate = null;
		Date endDate = null;
		if (startTime != null) {
			startDate = DateUtil.date(startTime);
		}
		if (endTime != null) {
			endDate = DateUtil.date(endTime);
		}
		//分销金额数据统计
		statisticsDataService.userMirrorShopDistribute(backgroundDataView, startDate, endDate);
		return GatewayResponse.SUCCESS.newBuilder().toResult(backgroundDataView);
	}

	/**
	 * 提现列表
	 */
	@GetMapping("/get/applyMoney/list")
	public Result<SearchResult<UserMirrorShopDistributeMoneyApply>> getApplyMoneyList() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		SearchResult<UserMirrorShopDistributeMoneyApply> search = beanSearcher.search(UserMirrorShopDistributeMoneyApply.class,
				MapUtils.flatBuilder(request.getParameterMap())
						.field(UserMirrorShopDistributeMoneyApply::getUserId, cpsUserId)
						.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
}
