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

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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
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.IndexImg;
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.distribution.comment.model.DistributionProd;
import com.yami.shop.distribution.comment.model.DistributionProdLog;
import com.yami.shop.distribution.comment.service.DistributionProdService;
import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.security.multishop.model.YamiShopUser;
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.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/distribution/distributionProd")
@AllArgsConstructor
public class DistributionProdController {

    private final DistributionProdService distributionProdService;

    private final OfflineHandleEventService offlineHandleEventService;

    private final ProductService productService;

    @GetMapping("/count")
    public ResponseEntity<Integer> count(Long prodId) {
        return ResponseEntity.ok(distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, prodId)
        ));
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<DistributionProd>> page(DistributionProd distributionProd, PageParam<DistributionProd> page, String prodName, Integer state) {
        distributionProd.setShopId(SecurityUtils.getShopUser().getShopId());
        distributionProd.setState(state);
        IPage<DistributionProd> list = distributionProdService.distributionProdsPage(page, distributionProd, prodName);
        return ResponseEntity.ok(list);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
    public ResponseEntity<DistributionProd> info(@PathVariable("id") Long id) {
        DistributionProd distributionProd = distributionProdService.getById(id);
        return ResponseEntity.ok(distributionProd);
    }

    /**
     * 保存
     */
    @PostMapping
    public ResponseEntity<Void> save(@RequestBody @Valid DistributionProd distributionProd) {
        distributionProd.setShopId(SecurityUtils.getShopUser().getShopId());
        // 防止重复提交
        int count = distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, distributionProd.getProdId())
                .eq(DistributionProd::getShopId, distributionProd.getShopId()));
        if (count>0){
            throw new GlobalException("分销商品已经存在");
        }
        // 校验数据
        validateDistributionProd(distributionProd);
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.save(distributionProd);
        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseEntity<Void> update(@RequestBody @Valid DistributionProd distributionProd) {
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        // 校验数据
        validateDistributionProd(distributionProd);

        if (!Objects.equals(distributionProd.getShopId(), shopUser.getShopId())) {
            throw new UnauthorizedException("未授权");
        }
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.updateById(distributionProd);
        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping
    public ResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionProdService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }


    private void setDefaultAwardNumbers(@Valid @RequestBody DistributionProd distributionProd) {
        if (StrUtil.isBlank(distributionProd.getParentAwardNumbers())) {
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setParentAwardNumbers("0");
            } else {
                distributionProd.setParentAwardNumbers(null);
            }
        }
        if (StrUtil.isBlank(distributionProd.getAwardNumbers())) {
            distributionProd.setAwardNumbers("0");
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setAwardNumbers("0");
            } else {
                distributionProd.setAwardNumbers(null);
            }
        }
        distributionProd.setUpdateTime(new Date());
    }

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

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEventAuditParam.getHandleId());
        if (distributionProd == null) {
            throw new GlobalException("未找到分销商品信息信息");
        }
        distributionProdService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ResponseEntity.ok().build();
    }

    /**
     * 获取分销商品销售记录信息
     */
    @GetMapping("/getDistributionProdLogPage")
    public ResponseEntity<IPage<DistributionProdLog>> getDistributionProdLogPage(DistributionProdLog distributionProdLog, PageParam<DistributionProdLog> page) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        distributionProdLog.setShopId(shopId);
        IPage<DistributionProdLog> distributionProdLogL = distributionProdService.getDistributionProdLogPage(page,distributionProdLog);
        return ResponseEntity.ok(distributionProdLogL);
    }

    /**
     * 校验数据
     */
    private void validateDistributionProd(DistributionProd distributionProd) {
        Product product = productService.getProductByProdId(distributionProd.getProdId());
        if (product == null) {
            throw new GlobalException("未找到此商品");
        }
        // 如果不使用需要校验
        if (distributionProd.getDefaultReward() == 1) {
            return;
        }

        // 按比例
        if (distributionProd.getAwardProportion() == 0) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getAwardNumbers()) >= 100) {
                    throw new GlobalException("固定奖励比例设置不能超过100%");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > 100)) {
                    throw new GlobalException("等级奖励比例设置不能超过100%");
                }
            }

        }
        // 按金额
        if (distributionProd.getAwardProportion() == 1) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getAwardNumbers()) > product.getPrice()) {
                    throw new GlobalException("固定奖励设置不能超商品的原价格");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > product.getPrice())) {
                    throw new GlobalException("等级奖励设置不能超商品的原价格");
                }
            }
        }
        // 查看是否有开启邀请人奖励
        if (distributionProd.getParentAwardSet() == 0) {
            return;
        }

        // 按比例
        if (distributionProd.getAwardProportion() == 0) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getParentAwardNumbers()) >= 100) {
                    throw new GlobalException("邀请人固定奖励比例设置不能超过100%");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getParentAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > 100)) {
                    throw new GlobalException("邀请人等级奖励比例设置不能超过100%");
                }
            }

        }
        // 按金额
        if (distributionProd.getAwardProportion() == 1) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getParentAwardNumbers()) > product.getPrice()) {
                    throw new GlobalException("邀请人固定奖励设置不能超商品的原价格");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getParentAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > product.getPrice())) {
                    throw new GlobalException("邀请人等级奖励设置不能超商品的原价格");
                }
            }
        }
    }
}
