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

package com.yami.shop.groupbuy.multishop.controller;


import cn.hutool.core.collection.CollectionUtil;
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.ProdType;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.annotation.SysLog;
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.groupbuy.comment.api.dto.ApiGroupActivityDto;
import com.yami.shop.groupbuy.comment.dto.GroupProdAndSkuListDto;
import com.yami.shop.groupbuy.comment.dto.GroupProdDto;
import com.yami.shop.groupbuy.comment.enums.ActivityStatusEnum;
import com.yami.shop.groupbuy.comment.enums.GroupProdStatusEnum;
import com.yami.shop.groupbuy.comment.model.GroupActivity;
import com.yami.shop.groupbuy.comment.model.GroupProd;
import com.yami.shop.groupbuy.comment.param.GroupProdParam;
import com.yami.shop.groupbuy.comment.service.GroupActivityService;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 拼团活动商品表
 *
 * @author LGH
 * @date 2019-08-27 17:55:57
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/group/prod")
public class GroupProdController {

    private final GroupProdService groupProdService;
    private final ProductService productService;
    private final GroupActivityService groupActivityService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param groupProd 拼团活动商品表
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<GroupProdDto>> getGroupProdPage(PageParam<GroupProd> page, GroupProd groupProd) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        groupProd.setShopId(shopId);
        IPage<GroupProdDto> groupProdIPage = groupProdService.getGroupProdPage(page, groupProd);
        return ResponseEntity.ok(groupProdIPage);
    }


    /**
     * 通过id查询拼团活动商品表
     *
     * @param groupProdId id
     * @return 单个数据
     */
    @GetMapping("/info/{groupProdId}")
    public ResponseEntity<GroupProd> getById(@PathVariable("groupProdId") Long groupProdId) {
        return ResponseEntity.ok(groupProdService.getById(groupProdId));
    }

    /**
     * 新增拼团活动商品表
     *
     * @param groupProd 拼团活动商品表
     * @return 是否新增成功
     */
    @SysLog("新增拼团活动商品表")
    @PostMapping
    public ResponseEntity<Boolean> save(@RequestBody @Valid GroupProd groupProd) {
        return ResponseEntity.ok(groupProdService.save(groupProd));
    }

    /**
     * 修改拼团活动商品表
     *
     * @param groupProd 拼团活动商品表
     * @return 是否修改成功
     */
    @SysLog("修改拼团活动商品表")
    @PutMapping
    public ResponseEntity<Void> updateById(@RequestBody @Valid GroupProd groupProd) {
        groupProdService.updateById(groupProd);
        // 移除缓存
        if(groupProd != null){
            groupProdService.removeGroupProdCache(groupProd.getGroupProdId());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 通过id删除拼团活动商品表
     *
     * @param groupProdId id
     * @return 是否删除成功
     */
    @SysLog("删除拼团活动商品表")
    @DeleteMapping("/{groupProdId}")
    public ResponseEntity<Boolean> removeById(@PathVariable Long groupProdId) {
        // 校验店铺
        GroupProd groupProd = groupProdService.getById(groupProdId);
        if (Objects.isNull(groupProd)) {
            throw new GlobalException("活动商品不存在，请稍后重试");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!Objects.equals(shopId, groupProd.getShopId())) {
            throw new GlobalException("您无权对此活动商品进行操作");
        }
        // 校验活动是否开始
        GroupActivity groupActivity = groupActivityService.getById(groupProd.getGroupActivityId());
        if (Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.UNDER_WAY.value())
                && Objects.equals(groupProd.getStatus(), GroupProdStatusEnum.NORMAL.value())) {
            throw new GlobalException("活动进行中，不能删除活动商品，您可以等待活动结束后或失效该拼团活动后进行操作");
        }

        // 如果活动未开始，则删除无用记录
        if (Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.NOT_STARTED.value())) {
            groupProdService.delGroupProd(groupProd);
        } else {
            groupProdService.updateGroupProdToDelByGroupProd(groupProd);
        }

        // 删除缓存
        productService.removeProductCacheByProdId(groupProd.getProdId());
        groupProdService.removeGroupProdCache(groupProdId);
        return ResponseEntity.ok(true);
    }

    /**
     * 获取没有参与活动的活动本店铺商品
     */
    @GetMapping("/getNotGroupProdPage")
    public ResponseEntity<IPage<Product>> getNotGroupProdPage(PageParam<Product> page, Product product) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        IPage<Product> productIPage = productService.page(page, new LambdaQueryWrapper<Product>()
                .eq(Product::getShopId, shopId)
                .eq(Product::getStatus, 1)
                .eq(Product::getShopId, shopId)
                .eq(Objects.nonNull(product.getShopCategoryId()),Product::getShopCategoryId, product.getShopCategoryId())
                .like(StrUtil.isNotBlank(product.getProdName()),Product::getProdName, product.getProdName())
                .and(wrapper -> wrapper.isNull(Product::getProdType).or().eq(Product::getProdType, ProdType.PROD_TYPE_NORMAL.value()))
                //.and(wrapper -> wrapper.isNull(Product::getGroupActivityId).or().eq(Product::getGroupActivityId, 0))
                //.and(wrapper -> wrapper.isNull(Product::getSeckillActivityId).or().eq(Product::getSeckillActivityId, 0))
                .orderByAsc(Product::getCreateTime));
        return ResponseEntity.ok(productIPage);
    }

    @SysLog("添加拼团活动商品")
    @PostMapping("/saveByProdIds")
    public ResponseEntity<String> saveByProdIds(@RequestBody GroupProdParam groupProdParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<Long> prodIds = groupProdParam.getProdIds();
        if (CollectionUtil.isEmpty(prodIds)) {
            throw new GlobalException("添加拼团商品不能为空");
        }
        for (Long prodId : prodIds) {
            Product product = productService.getProductByProdId(prodId);
            if (!Objects.equals(product.getShopId(), shopId)) {
                throw new GlobalException("您无权操作此商品【" + product.getProdName() + "】");
            }
        }

        List<Long> resultIds = groupProdService.saveByProdIds(shopId, groupProdParam.getGroupActivityId(), groupProdParam.getProdIds());

        // 清理缓存
        if (CollectionUtil.isNotEmpty(resultIds)) {
            for (Long prodId : resultIds) {
                productService.removeProductCacheByProdId(prodId);
            }
        }
        return ResponseEntity.ok("添加成功");
    }

    /**
     * 通过id查询拼团活动商品表
     *
     * @param groupProdId id
     * @return 单个数据
     */
    @GetMapping("/getGroupProdAndSkuList/{groupProdId}")
    public ResponseEntity<GroupProdAndSkuListDto> getGroupProdAndSkuListById(@PathVariable("groupProdId") Long groupProdId) {
        GroupProdAndSkuListDto groupProdAndSkuListDto = groupProdService.getGroupProdAndSkuListById(groupProdId);
        return ResponseEntity.ok(groupProdAndSkuListDto);
    }

    /**
     * 失效正在拼团中的活动商品
     */
    @SysLog("失效拼团中活动商品")
    @PutMapping("/invalid/{groupProdId}")
    public ResponseEntity<Void> invalidGroupProd(@PathVariable Long groupProdId) {
        GroupProd groupProd = groupProdService.getById(groupProdId);
        if (Objects.isNull(groupProd) || !Objects.equals(groupProd.getStatus(), GroupProdStatusEnum.NORMAL.value())) {
            throw new GlobalException("活动商品不存在或已经失效");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!Objects.equals(groupProd.getShopId(), shopId)) {
            throw new GlobalException("您无权操作此活动");
        }
        // 查看活动
        ApiGroupActivityDto apiGroupActivityInfo = groupActivityService.getApiGroupActivityInfo(groupProd.getGroupActivityId(), groupProd.getProdId());
        if (Objects.isNull(apiGroupActivityInfo) || !Objects.equals(apiGroupActivityInfo.getActivityStatus(), ActivityStatusEnum.UNDER_WAY.value())) {
            throw new GlobalException("操作失败，活动不存在或已结束");

        }
        groupProdService.invalidGroupProd(groupProd);

        productService.removeProductCacheByProdId(groupProd.getProdId());
        groupProdService.removeGroupProdCache(groupProdId);
        return ResponseEntity.ok().build();
    }

}
