/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.user.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.app.param.OrderShopParam;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.UserAddr;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.user.comment.dto.ScoreOrderMergerDto;
import com.yami.shop.user.comment.service.ScoreOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;


/**
 * 积分订单信息管理实现
 *
 * @author LHD
 * @version 1.0.0
 * @since 2019-11-01
 */
@RestController
@AllArgsConstructor
@RequestMapping("/p/score" )
@Api(tags = "积分商品订单接口")
public class ScoreOrderController {


    private final MapperFacade mapperFacade;
    private final UserExtensionService userExtensionService;

    private final ProductService productService;
    private final ScoreOrderService scoreOrderService;
    private final SkuService skuService;
    private final UserAddrService userAddrService;
    private final BasketService basketService;
    private final UserService userService;
//    private final UserScoreRecordService scoreRecordService;




    @GetMapping("/prodScorePage")
    @ApiOperation(value = "积分商品列表", notes = "获取积分商城首页商品列表")
    @ApiImplicitParams({
    })
    public ResponseEntity<IPage<ProductDto>> prodScorePage(PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = productService.pageByScore(page);
        return ResponseEntity.ok(productDtoIPage);
    }


    /**
     * 积分商品购买
     */
    @PostMapping("/confirm")
    @ApiOperation(value = "购买，生成订单信息", notes = "传入下单所需要的参数进行下单")
    public ResponseEntity<ScoreOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
        if(orderParam.getOrderItem().getProdCount() < 1){
            throw  new YamiShopBindException("请至少选择一件商品!");
        }
        String userId = SecurityUtils.getUser().getUserId();
        // 订单的地址信息
        UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
        UserAddrDto userAddrDto = mapperFacade.map(userAddr, UserAddrDto.class);
        // 获取用户提交的商品
        ShopCartItemDto shopCartItemDto = basketService.getShopCartItem(orderParam.getOrderItem());
        //拼接商品信息
        ProductItemDto productItemDto = mapperFacade.map(shopCartItemDto,ProductItemDto.class);
        if (Objects.isNull(shopCartItemDto)) {
            throw new GlobalException("请选择您需要的商品进行购买");
        }

        // 将要返回给前端的完整的订单信息
        ScoreOrderMergerDto scoreOrderMergerDto = new ScoreOrderMergerDto();
        scoreOrderMergerDto.setUserAddr(userAddrDto);
        scoreOrderMergerDto.setShopId(Constant.PLATFORM_SHOP_ID);
        double actualTotal = shopCartItemDto.getProductTotalAmount();
        int totalCount = orderParam.getOrderItem().getProdCount();
        scoreOrderMergerDto.setUserId(userId);
        scoreOrderMergerDto.setTotal(actualTotal);
        scoreOrderMergerDto.setActualTotal(actualTotal);
        productItemDto.setActualTotal(actualTotal);
        //积分订单直接设置积分支付
        scoreOrderMergerDto.setIsScorePay(1);
        scoreOrderMergerDto.setTotalCount(totalCount);
        scoreOrderMergerDto.setTransfee( 0.0);
        scoreOrderMergerDto.setProductItemDto(productItemDto);
        scoreOrderService.putConfirmScoreOrderCache(userId,scoreOrderMergerDto);
        return ResponseEntity.ok(scoreOrderMergerDto);
    }

    /**
     * 立即购买  提交积分订单
     */
    @PostMapping("/submit")
    @ApiOperation(value = "提交订单，返回支付流水号", notes = "提交积分订单，用户开始进行支付")
    public ResponseEntity<OrderNumbersDto> submitOrders(@Valid @RequestBody OrderShopParam orderShopParam) {
        String userId = SecurityUtils.getUser().getUserId();
        ScoreOrderMergerDto mergerOrder = scoreOrderService.getConfirmScoreOrderCache(SecurityUtils.getUser().getUserId());
        UserExtension user = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId,userId));
        if (mergerOrder == null) {
            throw new GlobalException("订单已过期，请重新下单");
        }
        if(user.getScore() == null){
            user.setScore(0);
        }
        ProductItemDto productItemDto = mergerOrder.getProductItemDto();
        if(productItemDto.getScorePrice() > user.getScore()) {
            throw new GlobalException("用户积分不足");
        }
        StringBuilder orderNumbers = new StringBuilder();
        mergerOrder.setRemarks(orderShopParam.getRemarks());
        Order scoreOrder = scoreOrderService.submit(userId,mergerOrder);
        orderNumbers.append(scoreOrder.getOrderNumber());
        // 移除缓存
        skuService.removeSkuCacheBySkuId(mergerOrder.getProductItemDto().getSkuId(),mergerOrder.getProductItemDto().getProdId());
        productService.removeProductCacheByProdId(mergerOrder.getProductItemDto().getProdId());
        scoreOrderService.removeConfirmScoreOrderCache(userId);
        return ResponseEntity.ok(new OrderNumbersDto(orderNumbers.toString(),false));
    }

//    /**
//     * 分页查询
//     * @param page 分页对象
//     * @return 分页数据
//     */
//    @GetMapping("/info" )
//    @ApiOperation(value="获取用户积分", notes="返回用户的积分信息")
//    public ResponseEntity<IPage<UserScoreRecord>> getScoreRecord(PageParam<UserScoreRecord> page) {
//        String userId = SecurityUtils.getUser().getUserId();
//        IPage<UserScoreRecord> scoreRecord = scoreRecordService.page(page,new LambdaQueryWrapper<UserScoreRecord>()
//                .eq(UserScoreRecord::getIoType,1)
//                .eq(UserScoreRecord::getUserId,userId)
//                .orderByDesc(UserScoreRecord::getCreateTime));
//        return ResponseEntity.ok(scoreRecord);
//    }

}
