package com.yiqi.api.controller.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.app.domain.AppGoodsMarket;
import com.yiqi.app.domain.AppUserAddress;
import com.yiqi.app.domain.vo.AppUserInfoVO;
import com.yiqi.app.service.IAppGoodsMarketService;
import com.yiqi.app.service.IAppUserAddressService;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.GoodsType;
import com.yiqi.common.enums.OrderSourceType;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.enums.SysBoolType;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.common.utils.bean.BeanUtils;
import com.yiqi.order.domain.OrderGoods;
import com.yiqi.order.domain.dto.OrderGoodsDTO;
import com.yiqi.order.domain.dto.OrderGoodsPayDTO;
import com.yiqi.order.domain.dto.OrderGoodsRefundDTO;
import com.yiqi.order.domain.dto.OrderRetailGoodsSkusDTO;
import com.yiqi.order.domain.dto.weapp.*;
import com.yiqi.order.domain.vo.OrderDeliveryPathVO;
import com.yiqi.order.domain.vo.OrderGoodsPayResultVO;
import com.yiqi.order.domain.vo.OrderGoodsSkuInfoVO;
import com.yiqi.order.domain.vo.OrderPayResultVO;
import com.yiqi.order.domain.vo.weapp.AppGoodsOrderInfoQueryVO;
import com.yiqi.order.domain.vo.weapp.AppGoodsOrderInfoVO;
import com.yiqi.order.service.IOrderGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zjw
 * @date 2023/11/15
 */
@Api(tags = "订单商品")
@RestController
@RequestMapping(value = UrlConstants.wxappApi + "/order/goods")
public class WeAppOrderGoodsController extends BaseController {

    @Autowired
    private IAppUserAddressService appUserAddressService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IAppGoodsMarketService appGoodsMarketService;

    @Autowired
    private IAppUserService appUserService;

    @ApiOperation(value = "APP分页获取订单商品列表")
    @PostMapping("/getGoodsOrderListByApp")
    public R<List<AppGoodsOrderInfoQueryVO>> getGoodsOrderListByApp(@RequestBody AppGoodsOrderInfoQueryDTO appGoodsOrderInfoQueryDTO) {
        appGoodsOrderInfoQueryDTO.setAppUserId(AuthHolder.userId());
        return R.ok(orderGoodsService.getGoodsOrderListByApp(appGoodsOrderInfoQueryDTO));
    }

    @GetMapping("/getGoodsOrderInfo")
    @ApiOperation(value = "APP获取商品订单详情")
    public R<AppGoodsOrderInfoVO> getGoodsOrderInfo(@RequestParam("orderId") Long orderId ) {
        AppGoodsOrderInfoVO appGoodsOrderInfoVO = new AppGoodsOrderInfoVO();
        OrderGoods orderGoods = orderGoodsService.getById(orderId);
        BeanUtils.copyProperties(orderGoods, appGoodsOrderInfoVO);
        appGoodsOrderInfoVO.setOrderGoodsSkuList(orderGoodsService.selectOrderGoodsById(orderId));
        AppUserInfoVO userInfo = appUserService.getAppUserInfoById(orderGoods.getAppUserId());
        if (userInfo != null){
            BeanUtils.copyProperties(userInfo, appGoodsOrderInfoVO);
        }
        return R.ok(appGoodsOrderInfoVO);
    }

    /**
     * 新增零售 普通商品订单-购物车
     */
    @PostMapping("/insertOrderGoodsByAppMarket")
    @ApiOperation(value = "APP新增零售商品订单-购物车")
    public R<OrderGoods> insertOrderGoodsByAppMarket(@RequestBody @Validated AppGoodsMarketOrderDTO appGoodsMarketOrderDTO) {
        OrderGoodsDTO orderGoodsDTO = new OrderGoodsDTO();
        BeanUtils.copyProperties(appGoodsMarketOrderDTO, orderGoodsDTO);
        orderGoodsDTO.setOrderSource(OrderSourceType.APP.getCode());
        orderGoodsDTO.setAppUserId(AuthHolder.userId());
        orderGoodsDTO.setSourceType(SourceType.MANAGER.getCode());
        orderGoodsDTO.setGoodsType(GoodsType.NORMAL.getCode());
        // 校验收货地址是否存在
        long count = appUserAddressService.count(new QueryWrapper<AppUserAddress>().lambda().eq(AppUserAddress::getId, orderGoodsDTO.getAppUserAddressId()));
        if (count == 0){
            throw new ServiceException("收货地址不存在，请输入有效地址");
        }
        // 查询物料所有信息
        List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS = orderGoodsService.getOrderSkuInfoByGoodsMarket();
        // 计算购物车的总价
        BigDecimal totalPriceByGoodsMarket = orderGoodsSkuInfoVOS.stream().map(item -> item.getSalePrice().multiply(new BigDecimal(item.getBuyNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (BigDecimal.ZERO.equals(totalPriceByGoodsMarket)){
            error("商品总价不能为0");
        }
        orderGoodsDTO.setTotalPrice(totalPriceByGoodsMarket);

        orderGoodsDTO.setDeductAmount(new BigDecimal(0));

        OrderGoods orderGoods = orderGoodsService.cereateRetailOrderGoods(orderGoodsDTO, orderGoodsSkuInfoVOS);

        // app清空选中购物车
        appGoodsMarketService.remove(new QueryWrapper<AppGoodsMarket>().lambda()
                .eq(AppGoodsMarket::getAppUserId, AuthHolder.userId())
                .eq(AppGoodsMarket::getIsSelect, SysBoolType.YES.getCode()));

        return R.ok(orderGoods);
    }

    /**
     * 新增零售 普通商品订单-单商品直接下单
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @PostMapping("/insertOrderOneGoodsByApp")
    @ApiOperation(value = "APP新增零售商品订单-单商品直接下单")
    public R<OrderGoods> insertOrderOneGoodsByApp(@RequestBody @Validated AppGoodsOrderDTO appGoodsOrderDTO) {
        OrderGoodsDTO orderGoodsDTO = new OrderGoodsDTO();
        BeanUtils.copyProperties(appGoodsOrderDTO, orderGoodsDTO);
        orderGoodsDTO.setOrderSource(OrderSourceType.APP.getCode());
        orderGoodsDTO.setAppUserId(AuthHolder.userId());
        orderGoodsDTO.setSourceType(SourceType.MANAGER.getCode());
        orderGoodsDTO.setGoodsType(GoodsType.NORMAL.getCode());
        // 校验收货地址是否存在
        long count = appUserAddressService.count(new QueryWrapper<AppUserAddress>().lambda().eq(AppUserAddress::getId, orderGoodsDTO.getAppUserAddressId()));
        if (count == 0){
            throw new ServiceException("收货地址不存在，请输入有效地址");
        }
        // 设置下单商品
        List<OrderRetailGoodsSkusDTO> list = new ArrayList<>();
        list.add(appGoodsOrderDTO.getOrderRetailGoodsSkusDTO());
        orderGoodsDTO.setRetailGoodsVOList(list);

        // 计算购物车的总价
        List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS = orderGoodsService.getOrderSkuInfoByOrderSkuId(orderGoodsDTO);
        BigDecimal totalPrice = orderGoodsSkuInfoVOS.stream().map(item -> item.getSalePrice().multiply(new BigDecimal(item.getBuyNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (BigDecimal.ZERO.equals(totalPrice)){
            error("商品总价不能为0");
        }
        orderGoodsDTO.setTotalPrice(totalPrice);
        orderGoodsDTO.setDeductAmount(new BigDecimal(0));
        OrderGoods orderGoods = orderGoodsService.cereateRetailOrderGoods(orderGoodsDTO, orderGoodsSkuInfoVOS);
        return R.ok(orderGoods);
    }

    /**
     * 零售普通商品订单-支付
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/rePayOrder")
    @ApiOperation(value = "APP零售商品订单-支付")
    public R<OrderPayResultVO> rePayOrder(@RequestBody @Valid AppGoodsOrderRePayDTO appGoodsOrderRePayDTO) {
        OrderGoodsDTO orderGoodsDTO = new OrderGoodsDTO();
        BeanUtils.copyProperties(appGoodsOrderRePayDTO, orderGoodsDTO);
        orderGoodsDTO.setId(appGoodsOrderRePayDTO.getOrderId());
        orderGoodsDTO.setOrderSource(OrderSourceType.APP.getCode());
        return R.ok(orderGoodsService.rePayOrder(orderGoodsDTO));
    }

    /**
     * 新增零售商品订单-下单
     */
    @PostMapping("/orderGoodsPay")
    @ApiOperation(value = "新增零售商品订单-支付")
    public R<OrderPayResultVO> orderGoodsPay(@RequestBody @Valid OrderGoodsPayDTO orderGoodsPayDTO) {
        OrderPayResultVO resultVO = orderGoodsService.orderGoodsPay(orderGoodsPayDTO);
        return R.ok(resultVO);
    }


    /**
     * 零售普通商品订单-取消订单
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/cancelOrder")
    @ApiOperation(value = "零售商品订单-取消订单")
    public AjaxResult cancelOrder(@RequestBody AppOrderGoodsCancelDTO appOrderGoodsCancelDTO) {
        return toAjax(orderGoodsService.cancelOrder(appOrderGoodsCancelDTO));
    }


    /**
     * 生活服务商品订单-商品直接下单
     */
    @PostMapping("/insertOrderOneGoodsByAppLifeService")
    @ApiOperation(value = "APP生活服务商品订单-商品直接下单")
    public R<OrderGoods> insertOrderOneGoodsByAppLifeService(@RequestBody @Validated AppGoodsOrderLifeServiceDTO appGoodsOrderDTO) {
        OrderGoodsDTO orderGoodsDTO = new OrderGoodsDTO();
        BeanUtils.copyProperties(appGoodsOrderDTO, orderGoodsDTO);
        orderGoodsDTO.setOrderSource(OrderSourceType.APP.getCode());
        orderGoodsDTO.setAppUserId(AuthHolder.userId());
        orderGoodsDTO.setSourceType(SourceType.MANAGER.getCode());
        orderGoodsDTO.setGoodsType(GoodsType.LIFE_SERVICE.getCode());

        // 设置下单商品
        List<OrderRetailGoodsSkusDTO> list = new ArrayList<>();
        list.add(appGoodsOrderDTO.getOrderRetailGoodsSkusDTO());
        orderGoodsDTO.setRetailGoodsVOList(list);

        // 计算购物车的总价
        List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS = orderGoodsService.getOrderSkuInfoByOrderSkuId(orderGoodsDTO);
        BigDecimal totalPrice = orderGoodsSkuInfoVOS.stream().map(item -> item.getSalePrice().multiply(new BigDecimal(item.getBuyNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (BigDecimal.ZERO.equals(totalPrice)){
            error("商品总价不能为0");
        }
        orderGoodsDTO.setTotalPrice(totalPrice);
        orderGoodsDTO.setDeductAmount(new BigDecimal(0));
        OrderGoods orderGoods = orderGoodsService.cereateRetailOrderGoods(orderGoodsDTO, orderGoodsSkuInfoVOS);
        return R.ok(orderGoods);
    }

    /**
     * 汽车美容商品订单-商品直接下单
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @PostMapping("/insertOrderOneGoodsByAppCar")
    @ApiOperation(value = "APP汽车美容商品订单-商品直接下单")
    public R<OrderGoods> insertOrderOneGoodsByAppCar(@RequestBody @Validated AppGoodsOrderCarDTO appGoodsOrderDTO) {
        OrderGoodsDTO orderGoodsDTO = new OrderGoodsDTO();
        BeanUtils.copyProperties(appGoodsOrderDTO, orderGoodsDTO);
        orderGoodsDTO.setOrderSource(OrderSourceType.APP.getCode());
        orderGoodsDTO.setAppUserId(AuthHolder.userId());
        orderGoodsDTO.setSourceType(SourceType.MANAGER.getCode());
        orderGoodsDTO.setGoodsType(GoodsType.CAR.getCode());

        // 设置下单商品
        List<OrderRetailGoodsSkusDTO> list = new ArrayList<>();
        list.add(appGoodsOrderDTO.getOrderRetailGoodsSkusDTO());
        orderGoodsDTO.setRetailGoodsVOList(list);

        // 计算购物车的总价
        List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS = orderGoodsService.getOrderSkuInfoByOrderSkuId(orderGoodsDTO);
        BigDecimal totalPrice = orderGoodsSkuInfoVOS.stream().map(item -> item.getSalePrice().multiply(new BigDecimal(item.getBuyNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (BigDecimal.ZERO.equals(totalPrice)){
            error("商品总价不能为0");
        }
        orderGoodsDTO.setTotalPrice(totalPrice);
        orderGoodsDTO.setDeductAmount(new BigDecimal(0));
        OrderGoods orderGoods = orderGoodsService.cereateRetailOrderGoods(orderGoodsDTO, orderGoodsSkuInfoVOS);
        return R.ok(orderGoods);
    }

    /**
     * 生活服务/汽车美容-确认完成
     */
    @GetMapping("/confirmFinish")
    @ApiOperation(value = "生活服务/汽车美容订单-确认完成")
    public AjaxResult confirmFinish(@RequestParam("orderId") Long orderId) {
        return toAjax(orderGoodsService.confirmFinish(orderId));
    }

    /**
     * 商品订单-APP申请退款
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/applyRefundOrderGoods")
    @ApiOperation(value = "商品订单退款-APP申请退款")
    public R applyRefundOrderGoods(@RequestBody @Valid AppOrderGoodsRefundDTO appOrderGoodsRefundDTO) {
        return R.ok(orderGoodsService.applyRefundOrderGoods(appOrderGoodsRefundDTO));
    }

    /**
     * APP取消退款
     */
    @GetMapping("/cancelRefund")
    @ApiOperation(value = "商品订单退款-APP取消退款")
    public R cancelRefund(@RequestParam("orderId") Long orderId) {
        return R.ok(orderGoodsService.cancelRefund(orderId));
    }

    /**
     * 查询订单物流轨迹
     */
    @GetMapping("/getDeliveryPath")
    @ApiOperation(value = "查询订单物流轨迹")
    public R<OrderDeliveryPathVO> getDeliveryPath(@RequestParam("orderId") Long orderId) throws Exception {
        return R.ok(orderGoodsService.getDeliveryPath(orderId));
    }
    //</editor-folder>

}
