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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserOrderVerifyRecordMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserPayRecordMapper;
import com.cyksj.model.entity.EquipmentUserOrderVerifyRecord;
import com.cyksj.model.entity.EquipmentUserPayRecord;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.model.entity.User;
import com.cyksj.model.views.EquipmentBenefitsView;
import com.cyksj.model.views.EquipmentUserDistributeDetailView;
import com.cyksj.model.views.EquipmentUserDistributeViews;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

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

/*
 *项目名: netflix
 *文件名: EquipmentController
 *创建者: JavaZou
 *创建时间:2023/2/24 9:39
 */
@RestController
@RequestMapping("/manage/equipment/distribute")
@RequiredArgsConstructor
public class EquipmentController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserMapper userMapper;

	private final CouponMapper couponMapper;

	private final EquipmentUserPayRecordMapper payRecordMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final EquipmentUserOrderVerifyRecordMapper equipmentUserOrderVerifyRecordMapper;

	/**
	 * 实物分销列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<EquipmentUserDistributeViews>> getEquipmentDistribute() {
		SearchResult<EquipmentUserDistributeViews> search = beanSearcher.search(EquipmentUserDistributeViews.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data -> {
			data.setRecordNum(payRecordMapper.selectCount(Wrappers.lambdaQuery(EquipmentUserPayRecord.class)
					.eq(EquipmentUserPayRecord::getShareId, data.getShareId())));
			data.setBenefitsViews(beanSearcher.searchAll(EquipmentBenefitsView.class, MapUtils.builder().field(EquipmentBenefitsView::getSharId, data.getShareId()).build()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 分销明细
	 */
	@GetMapping("/get/detail/{shareId}")
	public Result<SearchResult<EquipmentUserDistributeDetailView>> getDistributeDetail(@PathVariable Long shareId) {
		SearchResult<EquipmentUserDistributeDetailView> search = beanSearcher.search(EquipmentUserDistributeDetailView.class,
				MapUtils.flatBuilder(request.getParameterMap())
						.field(EquipmentUserDistributeDetailView::getShareId, shareId)
						.build());
		search.getDataList().forEach(data -> {
			User user = userMapper.selectById(data.getUserId());
			Optional.ofNullable(user).ifPresent(u -> data.setNickname(u.getNickname()));
			String couponName = couponMapper.getCouponNameByCouponUserId(data.getCouponUserId());
			data.setCouponName(couponName);
			GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(data.getSkuId());
			Optional.ofNullable(goodsDonSku).ifPresent(sku -> data.setSpecVal(sku.getSpecVal()));
			EquipmentUserOrderVerifyRecord equipmentUserOrderVerifyRecord = equipmentUserOrderVerifyRecordMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserOrderVerifyRecord.class)
					.eq(EquipmentUserOrderVerifyRecord::getOrderId, data.getOrderId())
					.last("limit 1"));
			data.setVerifyRecord(equipmentUserOrderVerifyRecord);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 发送奖励记录
	 */
	@PutMapping("/verify/reward/record")
	public Result<SearchResult> verifyRewardRecord(@RequestBody EquipmentUserOrderVerifyRecord verifyRecord) {
		Long orderId = verifyRecord.getOrderId();
		EquipmentUserPayRecord equipmentUserPayRecord = payRecordMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserPayRecord.class).eq(EquipmentUserPayRecord::getOrderId, orderId).last("limit 1"));
		if (equipmentUserPayRecord == null) {
			throw BusinessRuntimeException.getInstance("实物分销订单不存在");
		}
		if (equipmentUserPayRecord.getStatus() == EquipmentUserPayRecord.Status.refund) {
			throw BusinessRuntimeException.getInstance("实物分销订单已退款");
		}
		BigDecimal money = verifyRecord.getMoney();
		String img = verifyRecord.getImg();
		if (StrUtil.isEmpty(img)) {
			throw BusinessRuntimeException.getInstance("转账截图不为空");
		}
		if (money == null) {
			throw BusinessRuntimeException.getInstance("转账金额不为空");
		}
		if (verifyRecord.getId() == null) {
			verifyRecord.setSharedId(equipmentUserPayRecord.getShareId());
			verifyRecord.setUserId(equipmentUserPayRecord.getUserId());
			try {
				equipmentUserOrderVerifyRecordMapper.insert(verifyRecord);
			} catch (DuplicateKeyException e) {
				throw BusinessRuntimeException.getInstance("其他客服已转账..");
			}
		} else {
			equipmentUserOrderVerifyRecordMapper.updateById(verifyRecord);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

}
