/*
 * 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.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.ProdStatusEnums;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.model.*;
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.common.util.R;
import com.yami.shop.service.*;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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


/**
 * 积分商品管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-11-26
 */
@Controller
@RequestMapping("/platform/scoreProduct")
@AllArgsConstructor
public class ScoreProductController {

    private final ProductService productService;
    private final SkuService skuService;
    private final BasketService basketService;
    private final OfflineHandleEventService offlineHandleEventService;
    private final MapperFacade mapperFacade;


    /**
     * 分页获取积分商品信息
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('score: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)
                        .eq(Product::getProdType, ProdType.PROD_TYPE_SCORE.value())
                        .ne(Product::getStatus,-1));
//        System.out.println("---------"+ProdType.PROD_TYPE_SCORE);
        return R.SUCCESS(products);
    }


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

    /**
     * 平台删除商品
     */
    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('score:prod:delete')")
    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);
        }

        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);
    }


    /**
     * 更新商品状态
     */
    @PutMapping("/prodStatus")
    public R<Void> shopStatus(@RequestBody ProductParam productParam) {
        Long prodId = productParam.getProdId();
        Integer prodStatus = productParam.getStatus();
        Product dbProduct = productService.getProductByProdId(prodId);
        if (!(Objects.equals(dbProduct.getStatus(), ProdStatusEnums.NORMAL.getValue())
                || Objects.equals(dbProduct.getStatus(), ProdStatusEnums.SHOP_OFFLINE.getValue()))) {
            throw new GlobalException("商品不在正常状态，修改失败");
        }
        Product product = new Product();
        product.setProdId(prodId);
        product.setStatus(prodStatus);
        if (prodStatus == 1) {
            product.setPutawayTime(new Date());
        }
        dbProduct.setStatus(prodStatus);
        // 商品状态改变时的发送事件，让活动下线
//        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, dbProduct.getStatus()));

        productService.updateById(product);
        List<String> userIds = basketService.listUserIdByProdId(prodId);
        productService.removeProductCacheByProdId(prodId);
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        return R.SUCCESS();
    }

    /**
     * 保存积分商品
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('score:prod:save')")
    public R<String> save(@Valid @RequestBody ProductScoreParam productScoreParam) {
        checkParam(productScoreParam);
        Product product = mapperFacade.map(productScoreParam, Product.class);
        product.setStatus(1);
        product.setShopId(Constant.PLATFORM_SHOP_ID);
        product.setPutawayTime(new Date());
        product.setUpdateTime(new Date());
        product.setProdType(3);
        product.setVersion(0);
        product.setCreateTime(new Date());
        // 商品销量设置为0
        product.setSoldNum(0);
        //积分商品类型
        product.setProdType(ProdType.PROD_TYPE_SCORE.value());
        productService.saveProduct(product);
        return R.SUCCESS();
    }

    /**
     * 修改积分商品
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('score:prod:update')")
    public R<String> update(@Valid @RequestBody ProductScoreParam productScoreParam) {
        checkParam(productScoreParam);
        Product product = mapperFacade.map(productScoreParam, Product.class);
        Product dbProduct = productService.getProductByProdId(productScoreParam.getProdId());
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        product.setUpdateTime(new Date());
        //积分商品类型
        product.setProdType(ProdType.PROD_TYPE_SCORE.value());
        dbProduct.setSkuList(dbSkus);
        productService.updateProduct(product, dbProduct);
        List<String> userIds = basketService.listUserIdByProdId(product.getProdId());
        //清除缓存
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        return R.SUCCESS();
    }


    private void checkParam(ProductScoreParam productScoreParam) {
        boolean isAllUnUse = true;
        List<Sku> skuList = productScoreParam.getSkuList();
        for (Sku sku : skuList) {
            if (sku.getStatus() == Constant.SUPER_ADMIN_ID) {
                isAllUnUse = false;
            }
        }
        if (isAllUnUse) {
            throw new GlobalException("至少要启用一种商品规格");
        }
    }

}
