package com.izouma.dingdong.web.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.domain.OrderGoodsSpec;
import com.izouma.dingdong.domain.merchant.GoodsSpecification;
import com.izouma.dingdong.domain.user.ShoppingCart;

import com.izouma.dingdong.repo.OrderGoodsSpecRepo;
import com.izouma.dingdong.service.OrderGoodsSpecService;
import com.izouma.dingdong.service.user.ShoppingCartService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.user.ShoppingCartRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
import com.izouma.dingdong.web.BaseController;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/shoppingCart")
@AllArgsConstructor
public class ShoppingCartController extends BaseController {

    private ShoppingCartService   shoppingCartService;
    private ShoppingCartRepo      shoppingCartRepo;
    private OrderGoodsSpecService orderGoodsSpecService;
    private OrderGoodsSpecRepo    orderGoodsSpecRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ShoppingCart save(@RequestBody ShoppingCart record) {
        if (record.getId() != null) {
            ShoppingCart orig = shoppingCartRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return shoppingCartRepo.save(orig);
        }
        return shoppingCartRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<ShoppingCart> all(PageQuery pageQuery) {
        return shoppingCartRepo.findAll(toSpecification(pageQuery, ShoppingCart.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public ShoppingCart get(@PathVariable Long id) {
        return shoppingCartRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        shoppingCartRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<ShoppingCart> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    /**
     * 选择规格后加入购物车
     *
     * @param goodsId               商品Id
     * @param goodsSpecificationIds 规格Id,无规格时，可不填，为null即可
     * @param num                   数量
     * @return 购物车列表
     */
    @PostMapping("/cart")
    @ApiOperation("选择规格后就加入购物车")
    public ShoppingCart cart(Long goodsId, String goodsSpecificationIds, Integer num, Double longitude, Double latitude) {
        //无规格时，goodsSpecifications可不填
        OrderGoodsSpec orderGoodsSpec = orderGoodsSpecService.add(goodsId, goodsSpecificationIds, num);
        return shoppingCartService.add(SecurityUtils.getAuthenticatedUser()
                .getId(), orderGoodsSpec, longitude, latitude);
    }

    @GetMapping("/delGoods")
    @ApiOperation("从购物车中删除商品")
    public ShoppingCart delGoods(Long specId) {
        //orderGoodsSpecRepo.deleteById(orderGoodsSpec);
        return shoppingCartService.sub(specId);
    }

    @GetMapping("/my")
    public Page<ShoppingCart> my(PageQuery pageQuery) {
        List<ShoppingCart> carts = shoppingCartRepo.findAllByUserId(SecurityUtils.getAuthenticatedUser().getId());
        return new PageImpl<>(carts, toPageRequest(pageQuery), pageQuery.getSize());
    }

    @GetMapping("/my/merchant")
    public List<OrderGoodsSpec> myMerchant(Long merchantId) {
        ShoppingCart cart = shoppingCartRepo.findByUserIdAndMerchantId(SecurityUtils.getAuthenticatedUser()
                .getId(), merchantId);
        if (ObjectUtil.isEmpty(cart)) {
            return null;
        }
        List<OrderGoodsSpec> specs = cart.getOrderGoodsSpecs();
        if (CollUtil.isEmpty(specs)) {
            return null;
        }
        return specs;
    }

    //清除购物车
    @GetMapping("/clearCart")
    @ApiOperation("清除购物车")
    public void clearCart() {
        Long id = SecurityUtils.getAuthenticatedUser().getId();
        List<Long> list = shoppingCartRepo.findAllByUserId(id).stream().map(ShoppingCart::getId)
                .collect(Collectors.toList());
        list.forEach(l -> orderGoodsSpecRepo.deleteAllByShoppingCartIdAndOrderInfoIdIsNull(l));
        shoppingCartRepo.deleteAllByUserId(id);
    }

    @GetMapping("/again")
    @ApiOperation("再来一单")
    public ShoppingCart again(Long orderId, Double longitude, Double latitude) {
        return shoppingCartService.again(orderId, longitude, latitude);
    }

    @GetMapping("/changeNum")
    @ApiOperation("改数量")
    public ShoppingCart changeNum(Long specId, Integer num) {
        return shoppingCartService.changeNum(specId, num);
    }
}

