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

package com.yami.shop.discount.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
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.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
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.discount.comment.model.Discount;
import com.yami.shop.discount.comment.model.DiscountProd;
import com.yami.shop.discount.comment.service.DiscountService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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


/**
 * @author lgh on 2018/11/21.
 */
@RestController
@RequestMapping("/admin/discount")
@AllArgsConstructor
public class DiscountController {

    private DiscountService discountService;
    private ProductService productService;
    private OfflineHandleEventService offlineHandleEventService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Discount>> page(Discount discount, PageParam<Discount> page) {
        IPage<Discount> discounts = discountService.page(page,
                new LambdaQueryWrapper<Discount>()
                        .eq(Objects.nonNull(discount.getStatus()), Discount::getStatus, discount.getStatus())
                        .like(StringUtils.isNotBlank(discount.getDiscountName()), Discount::getDiscountName, discount.getDiscountName())
                        .eq(Discount::getShopId, SecurityUtils.getShopUser().getShopId())
//                        .orderByDesc(Discount::getStatus)
                        .orderByDesc(Discount::getStartTime)
        );
        return ResponseEntity.ok(discounts);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{discountId}")
    public ResponseEntity<Discount> info(@PathVariable("discountId") Long discountId) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Discount discount = discountService.getDiscountAndItemAndProdById(discountId);
        if (!Objects.equals(shopId, discount.getShopId())) {
            throw new GlobalException("您无权获取此活动信息");
        }
        return ResponseEntity.ok(discount);
    }

    /**
     * 保存
     */
    @PostMapping
    public ResponseEntity<String> save(@RequestBody @Valid Discount discount) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        discount.setShopId(shopId);
        List<DiscountProd> discountProds = discount.getDiscountProds();
        StringBuilder missProdNames = new StringBuilder();
        if (CollectionUtil.isNotEmpty(discountProds)) {
            for (DiscountProd discountProd : discountProds) {
                Product product = productService.getProductByProdId(discountProd.getProdId());
                if (product == null) {
                    missProdNames.append(discountProd.getProdName()).append(" ");
                }
            }
        }
        if (missProdNames.length() > 0) {
            return ResponseEntity.badRequest().body("活动中包含已下线商品：[ " + missProdNames.toString() + "]");
        }

        discountService.insertDiscountAndItemAndProd(discount);


        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseEntity<Void> update(@RequestBody @Valid Discount discount) {
        discountService.updateDiscountAndItemAndProd(discount);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{discountId}")
    public ResponseEntity<Void> delete(@PathVariable Long discountId) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        discountService.deleteDiscountsAndItemsAndProds(discountId, shopId);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventByDiscountId/{discountId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("discountId") Long discountId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISCOUNT.getValue(), discountId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Discount discount = discountService.getDiscountAndItemAndProdById(offlineHandleEventAuditParam.getHandleId());
        if (discount == null) {
            throw new GlobalException("未找到此活动信息");
        }
        // 提交审核
        discountService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        // 移除缓存
        discountService.removeDiscountsAndItemsCacheByShopId(discount.getShopId());
        discountService.removeDiscountAndItemAndProdCacheById(discount.getDiscountId());
        return ResponseEntity.ok().build();
    }
    /**
     * 查询商品是否在参与满减满折扣活动
     * 并且返回提示
     */
    @PostMapping("/prodIsDiscount")
    public ResponseEntity<String> prodIsDiscount(@RequestBody List<Long> prodIds) {
        // 查询是满减满折是所有商品都产于的
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Integer count = 0;
        String msg = "选择的商品也在限制特惠【满减满折】参与活动，请慎重选择";
        List<Long> seckillProdIds = discountService.getProdIsSeckillExcept(shopId);

        for (Long prodId : prodIds) {
            count = discountService.countProdIsSeckillAll(shopId,prodId);
            if (count > 0) {
                return ResponseEntity.ok(msg);
            }
            count = discountService.countProdIsSeckillSome(shopId,prodId);
            if (count > 0) {
                return ResponseEntity.ok(msg);
            }
            // 不能说明该商品在限时特惠活动中
//            count = discountService.countProdIsSeckillExcept(shopId,prodId);
//            if (count > 0) {
//                // 此时说明不在限时特惠中
//                continue;
//            }
            if (CollectionUtils.isNotEmpty(seckillProdIds)) {
                if (!seckillProdIds.contains(prodId)) {
                    return ResponseEntity.ok(msg);
                }
            }
        }
        return ResponseEntity.ok("");
    }
}
