/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.finance.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.common.enums.OrderTypeEnum;
import org.springblade.common.enums.PaymentTypeEnum;
import org.springblade.common.utils.SpringUtils;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.api.request.CustomWineOrderSave;
import org.springblade.modules.api.request.SubmitOrderRequest;
import org.springblade.modules.api.response.SubmitOrderResponse;
import org.springblade.modules.api.service.SubmitOrderService;
import org.springblade.modules.custom.entity.*;
import org.springblade.modules.custom.service.*;
import org.springblade.modules.custom.vo.BaseWineVO;
import org.springblade.modules.custom.wrapper.ManufacturerWrapper;
import org.springblade.modules.custom.wrapper.SpecialBaseWineWrapper;
import org.springblade.modules.finance.entity.CustomWineDiy;
import org.springblade.modules.finance.entity.CustomWineOrder;
import org.springblade.modules.finance.entity.OrderDetail;
import org.springblade.modules.finance.service.ICustomWineDiyService;
import org.springblade.modules.finance.service.ICustomWineOrderService;
import org.springblade.modules.finance.service.IOrderDetailService;
import org.springblade.modules.finance.vo.CustomWineOrderVO;
import org.springblade.modules.finance.wrapper.CustomWineDiyWrapper;
import org.springblade.modules.finance.wrapper.CustomWineOrderWrapper;
import org.springblade.modules.finance.wrapper.OrderDetailWrapper;
import org.springblade.modules.mall.entity.GoodsSpec;
import org.springblade.modules.mall.service.IGoodsSpecService;
import org.springblade.modules.platform.entity.UserAddress;
import org.springblade.modules.platform.service.IUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.vo.OrderVO;
import org.springblade.modules.finance.wrapper.OrderWrapper;
import org.springblade.modules.finance.service.IOrderService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;

/**
 * 订单主表 控制器
 *
 * @author BladeX
 * @since 2023-02-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("finance/order")
@Api(value = "订单主表", tags = "订单主表接口")
public class OrderController extends BladeController {

	private final IOrderService orderService;
	private final IOrderDetailService orderDetailService;
	private final ICustomWineOrderService customWineOrderService;
	private final IBottleBodyService bottleBodyService;
	private final IBottleCapService bottleCapService;
	private final IBottleLabelService bottleLabelService;
	private final IWineBoxService wineBoxService;
	private final IWineCaseService wineCaseService;
	private final IBaseWineService baseWineService;
	private final IHandbagService handbagService;
	private final ICustomWineDiyService customWineDiyService;
	private final IManufacturerService manufacturerService;
	private final IGoodsSpecService goodsSpecService;
	private final IUserAddressService userAddressService;


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入order")
	public R<OrderVO> detail(Order order) {
		Order detail = orderService.getOne(Condition.getQueryWrapper(order));
		OrderVO orderVO = OrderWrapper.build().entityVO(detail);
		OrderDetail orderDetail = orderDetailService.getByOrderId(detail.getId());
		orderVO.setOrderDetail(OrderDetailWrapper.build().entityVO(orderDetail));
		if (OrderTypeEnum.CUSTOM_WINE.getValue().equals(detail.getOrderType())) {
			CustomWineOrder customWineOrder = customWineOrderService.lambdaQuery().eq(CustomWineOrder::getOrderId, detail.getId()).one();
			CustomWineOrderVO cvo = CustomWineOrderWrapper.build().entityVO(customWineOrder);
			WineCase wineCase = wineCaseService.getById(customWineOrder.getWineCaseId());
			cvo.setWineCaseImage(wineCase.getImage());
			BottleCap bottleCap = bottleCapService.getById(cvo.getBottleCapId());
			cvo.setBottleCapImage(bottleCap.getImage());

			WineBox wineBox = wineBoxService.getById(cvo.getWineBoxId());
			if (wineBox != null) {
				cvo.setWineBoxImage(wineBox.getImage());
			}
			BaseWine baseWine = baseWineService.getById(cvo.getBaseWineId());
			if (baseWine != null) {
				cvo.setBaseWineImage(baseWine.getImage());
				BaseWineVO baseWineVO = BeanUtil.copyProperties(baseWine, BaseWineVO.class);
				Manufacturer manufacturer = manufacturerService.getById(baseWine.getManufacturerId());
				baseWineVO.setManufacturer(ManufacturerWrapper.build().entityVO(manufacturer));
				orderVO.setBaseWineVO(baseWineVO);
			}
			BottleBody bottleBody = bottleBodyService.getById(cvo.getBottleBodyId());
			if (bottleBody != null) {
				cvo.setBottleBodyImage(bottleBody.getImage());
			}
			Handbag handbag = handbagService.getById(cvo.getHandbagId());
			if (handbag != null) {
				cvo.setHandbagImage(handbag.getImage());
			}
			BottleLabel bottleLabel = bottleLabelService.getById(cvo.getBottleLabelId());
			if (bottleLabel != null) {
				cvo.setLabelImage(bottleLabel.getImage());
			}

			orderVO.setCustomWineOrderVO(cvo);

			CustomWineDiy one = customWineDiyService.lambdaQuery().eq(CustomWineDiy::getOrderNo, detail.getOrderNo()).one();
			orderVO.setDiyInfo(CustomWineDiyWrapper.build().entityVO(one));
		}
		return R.data(orderVO);
	}

	/**
	 * 分页 订单主表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入order")
	public R<IPage<OrderVO>> list(Order order, Query query) {
		QueryWrapper<Order> queryWrapper = Condition.getQueryWrapper(order);
		queryWrapper.orderByDesc("create_time");
		if (!OrderTypeEnum.CUSTOM_WINE.getValue().equals(order.getOrderType())) {
			queryWrapper.ne("order_type", OrderTypeEnum.CUSTOM_WINE.getValue());
		}
		IPage<Order> pages = orderService.page(Condition.getPage(query), queryWrapper);
		return R.data(OrderWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 订单主表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入order")
	public R<IPage<OrderVO>> page(OrderVO order, Query query) {
		IPage<OrderVO> pages = orderService.selectOrderPage(Condition.getPage(query), order);
		return R.data(pages);
	}

	/**
	 * 新增 订单主表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入order")
	public R save(@Valid @RequestBody Order order) {
		return R.status(orderService.save(order));
	}

	/**
	 * 修改 订单主表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入order")
	public R update(@Valid @RequestBody Order order) {
		return R.status(orderService.updateById(order));
	}

	/**
	 * 新增或修改 订单主表
	 */
//	@PostMapping("/submit")
//	@ApiOperationSupport(order = 6)
//	@ApiOperation(value = "新增或修改", notes = "传入order")
//	public R submit(@Valid @RequestBody Order order) {
//		return R.status(orderService.saveOrUpdate(order));
//	}

	
	/**
	 * 删除 订单主表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(orderService.removeByIds(Func.toLongList(ids)));
	}

	@PostMapping("/deliverGoods")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "发货")
	public R deliverGoods(@ApiParam(value = "主键集合", required = true) @RequestParam Long orderId,
						  @ApiParam(value = "物流公司", required = true) @RequestParam String wlCompany,
						  @ApiParam(value = "物流编号", required = true) @RequestParam String wlNo) {
		orderService.deliverGoods(orderId, wlCompany, wlNo);
		return R.success("ok");
	}

	@ApiOperation(value = "数据报表")
	@GetMapping("/dataReport")
	public R dataReport() {
		return R.data(orderService.dataReport());
	}

	@ApiOperation(value = "数据报表")
	@GetMapping("/dataReportByDate")
	public R dataReportByDate(String queryType) {
		return R.data(orderService.dataReportByDate(queryType));
	}

	@ApiLog("提交下单（通用）")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "提交下单")
	public R<SubmitOrderResponse> submitOrder(@Valid @RequestBody SubmitOrderRequest request) {
		request.setDistributeMode(1);
		request.setOrderType(OrderTypeEnum.GOODS.getValue());
		GoodsSpec spec = goodsSpecService.getById(request.getGoodsSpecId());
		request.setGoodsInfoId(spec.getGoodsId());
		SubmitOrderService submitOrderService = SpringUtils.getBean(OrderTypeEnum.getInstanceByValue(request.getOrderType()));
		Assert.notNull(submitOrderService, "获取实现类失败");
		List<UserAddress> list = userAddressService.lambdaQuery().eq(UserAddress::getUserId, request.getUserId()).eq(UserAddress::getDefaultState, 2).list();
		if (CollUtil.isEmpty(list)) {
			return R.fail("用户没有设置默认地址");
		}
		request.setUserAddressId(list.get(0).getId());
		String orderNo = submitOrderService.submitOrder(request);


		Order order = orderService.getByOrderNo(orderNo);
		orderService.orderPaySuccess(order, PaymentTypeEnum.WX_PAY.getValue());
		return data(new SubmitOrderResponse(orderNo));
	}

	@PostMapping("/saveOrder")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "定制酒下单接口")
	public R saveOrder(@Valid @RequestBody CustomWineOrderSave customWineOrderSave) throws Exception {
		List<UserAddress> list = userAddressService.lambdaQuery().eq(UserAddress::getUserId, customWineOrderSave.getUserId()).eq(UserAddress::getDefaultState, 2).list();
		if (CollUtil.isEmpty(list)) {
			return R.fail("用户没有设置默认地址");
		}
		customWineOrderSave.setUserAddressId(list.get(0).getId());
		String orderNo = customWineOrderService.saveOrder(customWineOrderSave, customWineOrderSave.getUserId());

		Order order = orderService.getByOrderNo(orderNo);
		orderService.orderPaySuccess(order, PaymentTypeEnum.WX_PAY.getValue());
		return data(new SubmitOrderResponse(orderNo));
	}

}
