/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.ListRelatedProductsDto;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.event.ProdChangeEvent;
import com.yami.shop.bean.event.ProdChangeStatusEvent;
import com.yami.shop.bean.model.Brand;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.bean.param.ProductParam;
import com.yami.shop.bean.param.ProductScoreParam;
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.platform.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Objects;
import com.yami.shop.common.util.R;

/**
 * 商品信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-11-26
 */
@Controller
@RequestMapping("/prod/prod")
@AllArgsConstructor
@Api(tags="商品列表、商品发布controller")
public class ProductController {

    private final ProductService productService;
    private final SkuService skuService;
    private final BasketService basketService;
    private final BrandService brandService;
    private final ApplicationContext applicationContext;
    private final OfflineHandleEventService offlineHandleEventService;


    /**
     * 分页获取商品信息
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('prod:prod:page')")
    public R<IPage<Product>> page(ProductParam product, PageParam<Product> page) {
       /* IPage<Product> products = productService.page(page,
                new LambdaQueryWrapper<Product>()
                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
                        .eq(product.getStatus() != null, Product::getStatus, product.getStatus())
                        .orderByDesc(Product::getPutawayTime)
                        .ne(Product::getStatus,-1));*/
       //TODO gai eq(Product::getProdType,ProdType.PROD_TYPE_NORMAL)
        IPage<Product> products = productService.getPageAngShopName(page,product);
        return R.SUCCESS(products);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:info')")
    public R<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId);
        List<Sku> skuList = skuService.listByProdId(prodId);
        Brand brand = brandService.getById(prod.getBrandId());
        if (Objects.nonNull(brand)){
            prod.setBrand(brand);
        }
        prod.setSkuList(skuList);
        return R.SUCCESS(prod);
    }

    /**
     * 平台删除商品
     */
    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public R<Void> delete(@PathVariable("prodId") Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId);
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        // 删除商品
        productService.removeProductByProdId(prodId);

        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }

        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        // 删除商品时，改变分销设置,团购订单处理。。。
        applicationContext.publishEvent(new ProdChangeEvent(dbProduct));
        return R.SUCCESS();
    }

    /**
     * 下线活动
     */
    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public R<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Product dbProduct = productService.getProductByProdId(offlineHandleEvent.getHandleId());
        if (dbProduct == null) {
            throw new GlobalException("未找到刚商品的信息");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        productService.offline(offlineHandleEvent.getHandleId(), offlineHandleEvent.getOfflineReason(), sysUserId);

        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, dbProduct.getStatus()));
        List<String> userIds = basketService.listUserIdByProdId(dbProduct.getProdId());
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        // 移除缓存
        productService.removeProductCacheByProdId(dbProduct.getProdId());
        return R.SUCCESS();
    }

    /**
     * 通过prodId获取最新下线商品的事件
     */
    @GetMapping("/getOfflineHandleEventByProdId/{prodId}")
    public R<OfflineHandleEvent> getOfflineHandleEventByProdId(@PathVariable Long prodId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.PROD.getValue(), prodId);
        return R.SUCCESS(offlineHandleEvent);
    }

    /**
     * 审核商品
     */
    @PostMapping("/prodAudit")
    public R<Void> prodAudit(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long userId = SecurityUtils.getSysUser().getUserId();
        productService.prodAudit(offlineHandleEventAuditParam, userId);

        // 移除缓存
        productService.removeProductCacheByProdId(offlineHandleEventAuditParam.getHandleId());
        return R.SUCCESS();
    }

    /**
     * 根据分类ID查询关联商品
     * */
    @PostMapping("/listRelatedProducts")
    @ApiOperation("根据分类ID查询关联商品")
    public R<IPage<Product>> listRelatedProducts(@RequestBody ListRelatedProductsDto listRelatedProductsDto){
        return R.SUCCESS(productService.listRelatedProducts(listRelatedProductsDto));
    }

}
