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

package com.yami.shop.distribution.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.model.OfflineHandleEvent;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
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.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.platform.model.YamiSysUser;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.service.OfflineHandleEventService;
import lombok.AllArgsConstructor;
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.Date;
import java.util.List;
import java.util.Objects;

/**
 * 分销商品信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2019-04-01
 */
@RestController
@RequestMapping("/platform/distributionProd")
@AllArgsConstructor
public class DistributionProdController {

    private final DistributionProdService distributionProdService;

    private final OfflineHandleEventService offlineHandleEventService;

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

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:page')")
    public ResponseEntity<IPage<DistributionProd>> page(DistributionProd distributionProd, PageParam<DistributionProd> page, String prodName, Integer state) {
        distributionProd.setState(state);
        IPage<DistributionProd> list = distributionProdService.distributionProdsPage(page, distributionProd, prodName);
        return ResponseEntity.ok(list);
    }

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

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:save')")
    public ResponseEntity<Void> save(@RequestBody @Valid DistributionProd distributionProd) {
        distributionProd.setShopId(Constant.PLATFORM_SHOP_ID);
        distributionProd.setModifier(SecurityUtils.getSysUser().getUserId());
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.save(distributionProd);

        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }


    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> update(@RequestBody @Valid DistributionProd distributionProd) {
        YamiSysUser sysUser = SecurityUtils.getSysUser();

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

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:delete')")
    public ResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionProdService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }


    private void setDefaultAwardNumbers(@Valid @RequestBody DistributionProd distributionProd) {
        distributionProd.setUpdateTime(new Date());

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

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

    /**
     * 下线活动
     */
    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEvent.getHandleId());
        if (distributionProd == null) {
            throw new GlobalException("未找到分销商品信息");
        }
        distributionProdService.offline(distributionProd, offlineHandleEvent.getOfflineReason(), sysUserId);
        return ResponseEntity.ok().build();
    }

    /**
     * 审核活动
     */
    @PostMapping("/auditDistributionProd")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> auditDistributionProd(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEventAuditParam.getHandleId());
        if (distributionProd == null) {
            throw new GlobalException("未找到该分销商品信息");
        }
        distributionProdService.auditDistributionProd(offlineHandleEventAuditParam, sysUserId);

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

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