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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.Xmls;
import com.cyksj.dto.Result;
import com.cyksj.enums.BusinessType;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsWholesaleOrderDonMapper;
import com.cyksj.mapper.GoodsWholesaleUserAccountMapper;
import com.cyksj.model.entity.GoodsWholesale;
import com.cyksj.model.entity.GoodsWholesaleUserAccount;
import com.cyksj.model.entity.GoodsWholesaleUserDeposit;
import com.cyksj.model.request.OrderRefundReq;
import com.cyksj.model.views.GoodsWholesaleOrderView;
import com.cyksj.model.views.GoodsWholesaleView;
import com.cyksj.model.views.WholesaleUserRequirementView;
import com.cyksj.service.goods.GoodsWholesaleService;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * admin/批发下单
 * 项目名: yhlxj
 * 文件名: CmsGoodsDonWholeSaleController
 * 创建者: JavaZou
 * 创建时间:2024/8/26 11:46
 */
@RequestMapping("/manage/goods/whole/sale")
@RestController
@RequiredArgsConstructor
@Slf4j
public class CmsGoodsDonWholeSaleController {
	private final GoodsWholesaleService goodsWholesaleService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserBindRelationService userBindRelationService;

	private final GoodsWholesaleOrderDonMapper goodsWholesaleOrderDonMapper;

	private final RefreshCacheService refreshCacheService;

	private final GoodsWholesaleUserAccountMapper wholesaleUserAccountMapper;

	/**
	 * 新增批发平台
	 */
	@PostMapping("/post")
	public Result<String> saveWholesale(@RequestBody GoodsWholesale wholesale) throws Exception {
		goodsWholesaleService.saveOrUpdateWholesale(wholesale);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 编辑批发平台
	 */
	@PutMapping("/update")
	public Result<String> updateWholesale(@RequestBody GoodsWholesale wholesale) throws Exception {
		goodsWholesaleService.saveOrUpdateWholesale(wholesale);
		refreshCacheService.refreshWholesaleGoods();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 平台批发排序
	 */
	@PutMapping("/sorted")
	public Result<String> sortedWholesale(@RequestBody GoodsWholesale wholesale) throws Exception {
		Long id = wholesale.getId();
		Integer sorted = wholesale.getSorted();
		GoodsWholesale byId = goodsWholesaleService.getById(id);
		if (byId != null) {
			byId.setSorted(sorted);
			goodsWholesaleService.updateById(byId);
			refreshCacheService.refreshWholesaleGoods();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除批发平台
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteWholesaleById(@PathVariable Long id) {
		GoodsWholesale byId = goodsWholesaleService.getById(id);
		if (byId != null) {
			byId.setDeleted(false);
			goodsWholesaleService.updateById(byId);
			refreshCacheService.refreshWholesaleGoods();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 批发平台列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<GoodsWholesaleView>> getWholesale() {
		SearchResult<GoodsWholesaleView> search = beanSearcher.search(GoodsWholesaleView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data->{
			try {
				data.setWholesaleConfig(Jsons.parseList(data.getConfig(), GoodsWholesale.GoodsWholesaleConfig.class));
			} catch (Exception e) {
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 批发平台上下架
	 */
	@PutMapping("/update/status/{id}")
	public Result<String> updateStatusById(@PathVariable Long id) {
		GoodsWholesale byId = goodsWholesaleService.getById(id);
		if (byId != null) {
			byId.setStatus(!byId.getStatus());
			goodsWholesaleService.updateById(byId);
			refreshCacheService.refreshWholesaleGoods();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 用户批发情况
	 */
	@GetMapping("/get/user/requirement/info")
	public Result<SearchResult<WholesaleUserRequirementView>> userRequirementInfo() {
		SearchResult<WholesaleUserRequirementView> search = beanSearcher.search(WholesaleUserRequirementView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data->{
			List<Long> userIdList = null;
			try {
				userIdList = userBindRelationService.getRelationUserIdList(data.getUserId(), null);
				Integer total = goodsWholesaleOrderDonMapper.getUserWholesaleNumByUserIds(userIdList, null);
				data.setTotal(total);
				String content = data.getContent();
				if (StrUtil.isNotBlank(content)) {
					String[] split = content.split("\\|");
					String str = split[1];
					if (str.contains("[")) {
						data.setSource(str);
						data.setNum(split[0]);
					} else {
						data.setNum(str);
						data.setSource(split[0]);
					}
				}
			} catch (Exception e) {
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}


	//----------------------------------------------------------------------- 押金管理

	/**
	 * 押金列表
	 * @return
	 */
	@GetMapping("/get/deposit")
	public Result<SearchResult<GoodsWholesaleUserDeposit>> getDeposit() {
		SearchResult<GoodsWholesaleUserDeposit> search = beanSearcher.search(GoodsWholesaleUserDeposit.class, MapUtils.flatBuilder(request.getParameterMap())
				.build());
		search.getDataList().forEach(data -> {
			List<Long> userIdList = userBindRelationService.getRelationUserIdList(data.getUserId(), null);
			Integer total = goodsWholesaleOrderDonMapper.getUserWholesaleNumByUserIds(userIdList, null);
			data.setTotal(total);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 押金退款
	 */
	@PostMapping("/deposit/refund/{id}")
	@Log(module = "批发押金退款", businessType = BusinessType.POST, isSaveRequestData = true)
	public Result<String> depositRefund(@PathVariable Long id) throws Exception {
		long adminId = StpUtil.getLoginIdAsLong();
		goodsWholesaleService.depositRefund(id, adminId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 押金退款回调
	 */
	@PostMapping("/deposit/refund/notify")
	public Result<String> depositRefundWxNotify(HttpServletResponse response) throws Exception {
		String xml = IoKit.toString(request.getInputStream());
		log.info("=== 押金退款成功的回调: \n {}", xml);

		// 解析xml
		Map<String, String> map = Xmls.toMap(xml);

		// 退款失败
		if (!StrUtil.equals("SUCCESS", map.get("return_code"))) {
			throw BusinessRuntimeException.getInstance("退款失败.");
		}

		goodsWholesaleService.wxRefundNotify(map);

		String toWechatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

		OutputStream out = null;
		try {
			out = response.getOutputStream();
			IoKit.write(toWechatXmlResponse, out);
		} catch (Throwable e) {
			throw BusinessRuntimeException.getInstance(e == null ? null : e.getMessage());
		} finally {
			IoKit.close(out);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 批发订单
	 */
	@GetMapping("/get/order/list")
	public Result<SearchResult<GoodsWholesaleOrderView>> getOrderList() {
		SearchResult<GoodsWholesaleOrderView> search = beanSearcher.search(GoodsWholesaleOrderView.class, MapUtils.flatBuilder(request.getParameterMap())
				.orderBy(GoodsWholesaleOrderView::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 批发订单退款
	 */
	@PostMapping("/refund/order")
	@Log(module = "批发订单退款", businessType = BusinessType.POST, isSaveRequestData = true)
	public Result<String> wholesaleOrderRefund(@RequestBody @Validated OrderRefundReq refundReq) throws Exception {
		long adminId = StpUtil.getLoginIdAsLong();
		refundReq.setAdminId(adminId);
		goodsWholesaleService.wholesaleOrderRefund(refundReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 上传账号
	 */
	@GetMapping("/upload/account")
	public Result<String> uploadAccount(MultipartFile file, Long orderId) throws IOException {
		List<Object> acountList = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(0).doReadSync();
		goodsWholesaleService.uploadAccount(acountList, orderId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 订单账号详情
	 */
	@GetMapping("/get/order/account/{orderId}")
	public Result<SearchResult<GoodsWholesaleUserAccount>> getOrderAccount(@PathVariable Long orderId) {
		SearchResult<GoodsWholesaleUserAccount> search = beanSearcher.search(GoodsWholesaleUserAccount.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(GoodsWholesaleUserAccount::getOrderId, orderId)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 新增订单账号信息
	 */
	@PostMapping("/post/order/account")
	public Result<String> insertOrderAccount(@RequestBody List<GoodsWholesaleUserAccount> goodsWholesaleUserAccounts) {
		goodsWholesaleService.insertOrderAccount(goodsWholesaleUserAccounts);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑订单账号信息
	 */
	@PutMapping("/update/order/account")
	public Result<String> updateOrderAccount(@RequestBody List<GoodsWholesaleUserAccount> goodsWholesaleUserAccounts) {
		goodsWholesaleService.updateOrderAccount(goodsWholesaleUserAccounts);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

}
