package com.ruoyi.bar;

import com.ruoyi.bar.domain.*;
import com.ruoyi.bar.service.*;
import com.ruoyi.bar.service.impl.WyBeerQrcodeScanLogServiceImpl;
import com.ruoyi.brewery.domain.*;
import com.ruoyi.brewery.service.*;
import com.ruoyi.common.constant.RewardStatusConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.BarLoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.WyFeedback;
import com.ruoyi.system.domain.WyPlatformActivity;
import com.ruoyi.system.service.IWyFeedbackService;
import com.ruoyi.system.service.IWyPlatformActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Api(tags = "酒吧方个人相关接口")
@RestController
@RequestMapping("/bar/user")
public class BarUserController extends BarBaseController {

    @Resource
    private IWyBeerReviewService wyBeerReviewService;
    @Resource
    private IWyFavoriteService wyFavoriteService;
    @Resource
    private IWyBarIconLogService wyBarIconLogService;
    @Resource
    private IWyBarIconService wyBarIconService;
    @Resource
    private IWyBeerQrcodeScanLogService wyBeerQrcodeScanLogService;
    @Resource
    private IWyRedeemOrderService wyRedeemOrderService;
    @Resource
    private IWyFeedbackService wyFeedbackService;
    @Resource
    private IWyActivityJoinBatchService wyActivityJoinBatchService;
    @Resource
    private IWyPlatformActivityService wyPlatformActivityService;
    @Resource
    private IWyActivityService wyActivityService;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private IWyActivityRewardService wyActivityRewardService;


    /**
     * 查询我评价的酒评列表
     */
    @ApiOperation("查询我评价的酒评列表")
    @GetMapping("/reviewList")
    public TableDataInfo reviewList() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        WyBeerReview wyBeerReview = new WyBeerReview();
        wyBeerReview.setUserId(loginUser.getUser().getUserId());
        startPage();
        List<WyBeerReview> list = wyBeerReviewService.selectWyBeerReviewList(wyBeerReview);
        return getDataTable(list);
    }

    /**
     * 查询我收藏的酒款列表
     */
    @ApiOperation("查询我收藏的酒款列表")
    @GetMapping("/favoriteBeerList")
    public TableDataInfo favoriteBeerList() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        WyFavoriteBeer favoriteBeer = new WyFavoriteBeer();
        favoriteBeer.setUserId(loginUser.getUser().getUserId());
        startPage();
        List<WyFavoriteBeer> list = wyFavoriteService.selectWyFavoriteBeerList(favoriteBeer);
        return getDataTable(list);
    }

    /**
     * 查询我收藏的品牌列表
     */
    @ApiOperation("查询我收藏的品牌列表")
    @GetMapping("/favoriteBreweryList")
    public TableDataInfo favoriteBreweryList() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        WyFavoriteBrewery favoriteBrewery = new WyFavoriteBrewery();
        favoriteBrewery.setUserId(loginUser.getUser().getUserId());
        startPage();
        List<WyFavoriteBrewery> list = wyFavoriteService.selectWyFavoriteBreweryList(favoriteBrewery);
        return getDataTable(list);
    }

    /**
     * 查询我啤酒币变动记录
     */
    @ApiOperation("查询我啤酒币变动记录")
    @GetMapping("/coinRecordList")
    public TableDataInfo coinRecordList(@RequestParam(value = "breweryId", required = false) Long breweryId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        startPage();
        final WyBarIconLog wyBarIconLog = new WyBarIconLog();
        wyBarIconLog.setBarId(loginUser.getUser().getBarId());
        if (breweryId != null) {
            wyBarIconLog.setBreweryId(breweryId);
        }
        final List<WyBarIconLog> wyBarIconLogs = wyBarIconLogService.selectWyBarIconLogList(wyBarIconLog);
        return getDataTable(wyBarIconLogs);
    }

    /**
     * 门店啤酒币余额
     */
    @ApiOperation("门店啤酒币余额")
    @GetMapping("/coinList")
    public AjaxResult coinList() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyBarIcon wyBarIcon = new WyBarIcon();
        wyBarIcon.setBarId(loginUser.getUser().getBarId());
        final List<WyBarIcon> wyBarIcons = wyBarIconService.selectWyBarIconListWithGoodsNum(wyBarIcon);
        return AjaxResult.success(wyBarIcons);
    }

    /**
     * 特定品牌啤酒币余额
     */
    @ApiOperation("特定品牌啤酒币余额")
    @GetMapping("/coinDetail")
    public AjaxResult coinDetail(@RequestParam(value = "breweryId", required = false, defaultValue = "0") Long breweryId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyBarIcon wyBarIcon = new WyBarIcon();
        wyBarIcon.setBarId(loginUser.getUser().getBarId());
        wyBarIcon.setBreweryId(breweryId);
        final List<WyBarIcon> wyBarIcons = wyBarIconService.selectWyBarIconList(wyBarIcon);
        if (wyBarIcons.isEmpty()) {
            if (breweryId == 0) {
                final WyBarIcon wyBarIconNew = new WyBarIcon();
                wyBarIconNew.setBarId(loginUser.getUser().getBarId());
                wyBarIconNew.setBreweryId(breweryId);
                wyBarIconNew.setBalance(0L);
                wyBarIconService.insertWyBarIcon(wyBarIconNew);
                return AjaxResult.success(wyBarIconNew);
            } else {
                return AjaxResult.error("尚无该品牌的啤酒币，请先扫码开酒");
            }
        }
        return AjaxResult.success(wyBarIcons.get(0));
    }

    /**
     * 门店参与的活动列表
     */
    @ApiOperation("门店参与的活动列表")
    @GetMapping("/myActivityList")
    public AjaxResult myActivityList(@RequestParam(value = "status", required = false) Integer status,
                                     @RequestParam(value = "breweryId", required = false) Long breweryId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final HashMap<String, Object> activityMap = wyBeerQrcodeScanLogService.getActivityByBarId(loginUser.getUser().getBarId(), status, breweryId);
        return AjaxResult.success(activityMap);
    }

    /**
     * 门店参与的活动详情
     */
    @ApiOperation("门店参与的活动详情")
    @GetMapping("/myActivityDetail")
    public AjaxResult myActivityDetail(@RequestParam(value = "batchId") Long batchId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyActivityJoinBatch batch = wyActivityJoinBatchService.selectWyActivityJoinBatchByBatchId(batchId);
        if (batch == null || !Objects.equals(batch.getBarId(), loginUser.getUser().getBarId())) {
            return AjaxResult.error("活动参与信息不存在，或不属于当前门店");
        }
        final HashMap<String, Object> activityMap = new HashMap<>();
        activityMap.put("batch", batch);
        Integer target = 0;
        final BatchJoined batchJoined = wyBeerQrcodeScanLogService.selectActivityByBatchId(batchId);
        if (batch.getActivitySupplier() == 0) {
            final WyPlatformActivity platformActivity = wyPlatformActivityService.selectWyPlatformActivityById(batch.getActivityId());
            platformActivity.setRemainingBeerCount((int) (platformActivity.getActivityTarget() - batchJoined.getScanNum()));
            activityMap.put("activity", platformActivity);
            target = Math.toIntExact(platformActivity.getActivityTarget());
        } else {
            final WyActivity activity = wyActivityService.selectWyActivityById(batch.getActivityId());
            activity.setRemainingBeerCount(activity.getActivityTarget() - batchJoined.getScanNum());
            activityMap.put("activity", activity);
            target = activity.getActivityTarget();
        }
        final int cent = 100 / target;
        final WyBeerQrcodeScanLog query = new WyBeerQrcodeScanLog();
        query.setJoinBatchId(batchId);
        query.setBarId(loginUser.getUser().getBarId());
        query.setScanStatus(1);
        HashMap<String, Object> orderByMap = new HashMap<>();
        orderByMap.put("orderByColumn", "create_time");
        orderByMap.put("isAsc", "asc");
        query.setParams(orderByMap);
        final List<WyBeerQrcodeScanLog> logs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(query);
        List<ScanLogVO> scanLogVOs = new ArrayList<>();
        final ScanLogVO scanLogVO = new ScanLogVO();
        scanLogVO.setDate(DateUtils.parseDateToStr("yyyy-MM-dd", logs.get(0).getCreateTime()));
        scanLogVO.setPercent(0);
        scanLogVO.setOperation("开始累计");
        scanLogVOs.add(scanLogVO);
        for (int i = 0; i < logs.size(); i++) {
            final WyBeerQrcodeScanLog log = logs.get(i);
            final WyBeer beer = wyBeerService.selectWyBeerById(log.getBeerId());
            int last = cent * (i+1); // 当前进度
            if(last>97){
                last = 100;
            }
            final ScanLogVO scanLogVO1 = new ScanLogVO();
            scanLogVO1.setDate(DateUtils.parseDateToStr("yyyy-MM-dd", log.getCreateTime()));
            scanLogVO1.setPercent(last);
            scanLogVO1.setOperation("上枪产品:" + beer.getBeerName());
            scanLogVOs.add(scanLogVO1);
        }
//        logs.forEach(log -> {
//            final WyBeer beer = wyBeerService.selectWyBeerById(log.getBeerId());
//            final ScanLogVO logVO = new ScanLogVO();
//            logVO.setDate(DateUtils.parseDateToStr("yyyy-MM-dd", log.getCreateTime()));
//            logVO.setPercent(cent * index.getAndIncrement());
//            logVO.setOperation("上枪产品:" + beer.getBeerName());
//            scanLogVOs.add(logVO);
//        });
        if (logs.size() >= target) {
            final ScanLogVO scanLogVOEnd = new ScanLogVO();
            scanLogVOEnd.setDate(DateUtils.parseDateToStr("yyyy-MM-dd", logs.get(logs.size() - 1).getCreateTime()));
            scanLogVOEnd.setPercent(100);
            scanLogVOEnd.setOperation("达成活动目标值");
            scanLogVOs.add(scanLogVOEnd);
        }
        final WyActivityReward wyActivityReward = new WyActivityReward();
        wyActivityReward.setJoinBatchId(batchId);
        final List<WyActivityReward> wyActivityRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);
        if (!wyActivityRewards.isEmpty()) {
            final ScanLogVO scanLogVOEnd = new ScanLogVO();
            scanLogVOEnd.setDate(DateUtils.parseDateToStr("yyyy-MM-dd", wyActivityRewards.get(0).getCreateTime()));
            scanLogVOEnd.setPercent(null);
            scanLogVOEnd.setOperation("品牌方已发起兑付");
            scanLogVOs.add(scanLogVOEnd);
            activityMap.put("reward", wyActivityRewards.get(0));
        }
        //TODO 增加兑付记录
        activityMap.put("logs", scanLogVOs);
        return AjaxResult.success(activityMap);
    }

    /**
     * 我的扫码数据
     */
    @ApiOperation("我的扫码数据")
    @GetMapping("/myScanData")
    public AjaxResult myScanData() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final int days = 30;
        final Integer scanCount = wyBeerQrcodeScanLogService.scanCountByBarId(loginUser.getUser().getBarId(), days);
        final Integer percent = wyBeerQrcodeScanLogService.scanCountPercentByBarId(loginUser.getUser().getBarId(), days);
        final HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("scanCount", scanCount);
        stringObjectHashMap.put("percent", percent);
        return AjaxResult.success(stringObjectHashMap);
    }

    /**
     * 我的兑换订单
     */
    @ApiOperation("我的兑换订单")
    @GetMapping("/myExchangeOrder")
    public TableDataInfo myExchangeOrder(@RequestParam(value = "status", required = false) Integer status) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyRedeemOrder wyRedeemOrder = new WyRedeemOrder();
        wyRedeemOrder.setBarId(loginUser.getUser().getBarId());
        if (status != null) {
            //1 待发货 2 待收货 3 已完成
            if (status != 1 && status != 2 && status != 3) {
                throw new IllegalArgumentException("状态参数错误,只能为1,2,3");
            }
            wyRedeemOrder.setOrderStatus(status);
        }
        startPage();
        final List<WyRedeemOrder> wyRedeemOrders = wyRedeemOrderService.selectWyRedeemOrderList(wyRedeemOrder);
        return getDataTable(wyRedeemOrders);
    }

    @ApiOperation("发布意见反馈")
    @PostMapping("/addFeedback")
    public AjaxResult add(@Validated @RequestBody WyFeedback wyFeedback) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        wyFeedback.setUserId(loginUser.getUserId());
        wyFeedback.setBarId(loginUser.getUser().getBarId());
        return toAjax(wyFeedbackService.insertWyFeedback(wyFeedback));
    }

    /**
     * 查询某酒款我的收藏情况
     */
    @ApiOperation("查询某酒款我的收藏情况")
    @GetMapping("/favoriteBeerByBeerId")
    public AjaxResult favoriteBeerList(@RequestParam(value = "beerId") Long beerId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyFavoriteBeer wyFavoriteBeer = wyFavoriteService.selectWyFavoriteBeerByBeerIdAndUserId(beerId, loginUser.getUser().getUserId());
        return AjaxResult.success(wyFavoriteBeer);
    }

    /**
     * 查询某酒款我的收藏情况
     */
    @ApiOperation("查询某酒款我的收藏情况")
    @GetMapping("/favoriteBreweryByBreweryId")
    public AjaxResult favoriteBreweryList(@RequestParam(value = "breweryId") Long breweryId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyFavoriteBrewery wyFavoriteBrewery = wyFavoriteService.selectWyFavoriteBreweryByBreweryIdAndUserId(breweryId, loginUser.getUser().getUserId());
        return AjaxResult.success(wyFavoriteBrewery);
    }

    @ApiOperation("确认商品已经兑付")
    @PostMapping("/confirmExchange")
    public AjaxResult confirmExchange(@RequestParam(value = "rewardId") Long rewardId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyActivityReward wyActivityReward = wyActivityRewardService.selectWyActivityRewardById(rewardId);
        if (wyActivityReward == null || !Objects.equals(wyActivityReward.getBarId(), loginUser.getUser().getBarId())) { // 兑付信息不存在或不属于当前门店
            return AjaxResult.error("兑付信息不存在，或不属于当前门店");
        }
        if (wyActivityReward.getRewardStatus() == 1) { // 已经确认过
            return AjaxResult.error("已经确认过了,请勿重复操作");
        }
        wyActivityReward.setRewardStatus(RewardStatusConstants.Redeemed); //确认兑付
        wyActivityReward.setClaimTime(DateUtils.getNowDate());
        wyActivityRewardService.updateWyActivityReward(wyActivityReward);
        return AjaxResult.success();
    }

}
