package com.ruoyi.bar;

import com.ruoyi.bar.domain.SharePlanJoinVO;
import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyBeerQrcodeScanLog;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.bar.service.IWyBeerQrcodeScanLogService;
import com.ruoyi.brewery.domain.*;
import com.ruoyi.brewery.service.IWyBeerQrcodeService;
import com.ruoyi.brewery.service.IWyBeerService;
import com.ruoyi.brewery.service.IWyBreweryShareLogService;
import com.ruoyi.brewery.service.IWyBrewerySharePlanService;
import com.ruoyi.common.annotation.Log;
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.domain.model.QrCodeConsumeVO;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DistanceCalculatorUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.WyPlatformActivity;
import com.ruoyi.system.domain.vo.WyActivityVO;
import com.ruoyi.system.domain.vo.WyPlatformActivityVO;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
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.HashMap;
import java.util.List;

@Api(tags = "酒吧方二维码相关接口")
@RestController
@RequestMapping("/bar/qrcode")
public class BarQrcodeController extends BarBaseController {
    @Resource
    private IWyBeerQrcodeService wyBeerQrcodeService;
    @Resource
    private IWyBeerQrcodeScanLogService wyBeerQrcodeScanLogService;
    @Resource
    private IWyBarService wyBarService;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private SysConfigServiceImpl sysConfigService;
    @Resource
    private IWyBrewerySharePlanService wyBrewerySharePlanService;
    @Resource
    private IWyBreweryShareLogService wyBreweryShareLogService;
    /**
     * 核销二维码
     */
    @ApiOperation("核销二维码")
    @PostMapping("/consume")
    public AjaxResult consume(@Validated @RequestBody QrCodeConsumeVO qrcode) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyBar wyBar = wyBarService.selectWyBarById(loginUser.getBarId());
        if (wyBar == null) {
            return AjaxResult.error("酒吧不存在");
        }
        if (!wyBar.getAuthState().equals(1)) {
            return AjaxResult.error("酒吧未认证");
        }
        final String code = qrcode.getCode();
        final WyBeerQrcode wyBeerQrcode = wyBeerQrcodeService.selectWyBeerQrcodeByCode(code);
        if (wyBeerQrcode == null) {
            return AjaxResult.error("二维码不存在");
        }
        if (wyBeerQrcode.getQrcodeStatus() == 1) {
            AjaxResult.error("二维码已被使用,不能核销");
        }
        if (wyBeerQrcode.getQrcodeStatus() == 2) {
            AjaxResult.error("二维码已失效,不能核销");
        }
        //检查距离
        if (wyBar.getLatitude() == null || wyBar.getLongitude() == null) {
            return AjaxResult.error("酒吧经纬度未设置");
        }
        String distanceLimit = sysConfigService.selectConfigByKey("bar.scan.distance");
        if (distanceLimit == null) {
            distanceLimit = "100"; //单位为米
        }
        final double distance = DistanceCalculatorUtil.calculateDistance(wyBar.getLatitude(), wyBar.getLongitude(), qrcode.getLatitude(), qrcode.getLongitude());//单位为千米
        System.out.println("distance:" + distance * 1000);
        System.out.println("wyBar:" + wyBar);
        System.out.println("qrcode:" + qrcode);
        if (distance * 1000 > Double.parseDouble(distanceLimit)) {
            return AjaxResult.error("请在酒吧附近" + distanceLimit + "米范围内扫码");
        }
        final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setUserId(loginUser.getUser().getUserId());
        wyBeerQrcodeScanLog.setBeerId(wyBeerQrcode.getBeerId());
        wyBeerQrcodeScanLog.setCodeId(wyBeerQrcode.getId());
        wyBeerQrcodeScanLog.setScanTime(DateUtils.getNowDate());
        wyBeerQrcodeScanLog.setScanStatus(1); // 核销
        wyBeerQrcodeScanLog.setSkuSn(code);
        wyBeerQrcodeScanLog.setBarId(loginUser.getBarId());
        wyBeerQrcodeScanLog.setScanCity(wyBar.getCity());
        wyBeerQrcodeScanLog.setBreweryId(wyBeerQrcode.getBreweryId());
        if (qrcode.getActivityId() == null && qrcode.getPlatformActivityId() == null) {
            //单纯核销
            wyBeerQrcodeScanLogService.insertWyBeerQrcodeScanLog(wyBeerQrcodeScanLog);
        } else {
            //可叠加参与
            if (qrcode.getActivityId() != null) {
                //记录品牌方活动参与记录
                wyBeerQrcodeScanLog.setActivityId(qrcode.getActivityId());
                wyBeerQrcodeScanLog.setActivitySupplier(1);
                wyBeerQrcodeScanLogService.insertWyBeerQrcodeScanLog(wyBeerQrcodeScanLog);
            }
            if (qrcode.getPlatformActivityId() != null) {
                //记录平台活动参与记录
                wyBeerQrcodeScanLog.setActivityId(qrcode.getPlatformActivityId());
                wyBeerQrcodeScanLog.setActivitySupplier(0);
                wyBeerQrcodeScanLogService.insertWyBeerQrcodeScanLog(wyBeerQrcodeScanLog);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询二维码信息
     */
    @ApiOperation("查询二维码信息")
    @PostMapping("/checkout")
    public AjaxResult checkout(@Validated @RequestBody QrCodeConsumeVO qrcode) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyBar wyBar = wyBarService.selectWyBarById(loginUser.getBarId());
        if (wyBar == null) {
            return AjaxResult.error("酒吧不存在");
        }
        if (!wyBar.getAuthState().equals(1)) {
            return AjaxResult.error("酒吧未认证");
        }
        //检查距离
        if (wyBar.getLatitude() == null || wyBar.getLongitude() == null) {
            return AjaxResult.error("酒吧经纬度未设置");
        }
        String distanceLimit = sysConfigService.selectConfigByKey("bar.scan.distance");
        if (distanceLimit == null) {
            distanceLimit = "100"; //单位为米
        }
        final double distance = DistanceCalculatorUtil.calculateDistance(wyBar.getLatitude(), wyBar.getLongitude(), qrcode.getLatitude(), qrcode.getLongitude());//单位为千米
        System.out.println("distance:" + distance * 1000);
        System.out.println("wyBar:" + wyBar);
        System.out.println("qrcode:" + qrcode);
        if (distance * 1000 > Double.parseDouble(distanceLimit)) {
            return AjaxResult.error("请在酒吧附近" + distanceLimit + "米范围内扫码");
        }
        //检查扫码用户身份
        final String code = qrcode.getCode();
        final WyBeerQrcode wyBeerQrcode = wyBeerQrcodeService.selectWyBeerQrcodeByCode(code);
        if (wyBeerQrcode == null) {
            return AjaxResult.error("二维码不存在");
        }
        final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setUserId(loginUser.getUser().getUserId());
        wyBeerQrcodeScanLog.setBeerId(wyBeerQrcode.getBeerId());
        wyBeerQrcodeScanLog.setCodeId(wyBeerQrcode.getId());
        wyBeerQrcodeScanLog.setScanTime(DateUtils.getNowDate());
        wyBeerQrcodeScanLog.setScanStatus(0); // 扫码
        wyBeerQrcodeScanLog.setSkuSn(code);
        wyBeerQrcodeScanLog.setBarId(loginUser.getBarId());
        wyBeerQrcodeScanLog.setScanCity(wyBar.getCity());
        wyBeerQrcodeScanLog.setBreweryId(wyBeerQrcode.getBreweryId());
        if (wyBeerQrcode.getQrcodeStatus() == 0) {
            wyBeerQrcodeScanLog.setRemark("二维码未被使用,可以核销");
        } else {
            wyBeerQrcodeScanLog.setRemark("二维码已被使用,不能核销");
        }
        wyBeerQrcodeScanLogService.insertWyBeerQrcodeScanLog(wyBeerQrcodeScanLog);
        final List<WyPlatformActivityVO> platformActivityByBeerId = wyBeerQrcodeScanLogService.getPlatformActivityByBeerId(wyBeerQrcode.getBeerId(), loginUser.getBarId());
        final List<WyActivityVO> activityByBeerId = wyBeerQrcodeScanLogService.getBreweryActivityByBeerId(wyBeerQrcode.getBeerId(), loginUser.getBarId());
        final WyBeer beer = wyBeerService.selectWyBeerById(wyBeerQrcode.getBeerId());
        HashMap<String, Object> result = new HashMap<>();
        result.put("qrcode", wyBeerQrcode);
        result.put("platformActivity", platformActivityByBeerId);
        result.put("activity", activityByBeerId);
        result.put("beer", beer);
        return AjaxResult.success(result);
    }

    @ApiOperation("分享方案详情")
    @GetMapping("/sharePlan")
    public AjaxResult sharePlan(@RequestParam("planId") Long planId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyBrewerySharePlan sharePlan = wyBrewerySharePlanService.selectWyBrewerySharePlanById(planId);
        if (sharePlan == null) {
            return AjaxResult.error("分享方案不存在");
        }
        if (sharePlan.getPlanStatus() != 1) {
            return AjaxResult.error("分享方案未生效");
        }
        return AjaxResult.success(sharePlan);
    }

    @ApiOperation("参与分享方案奖励")
    @PostMapping("/sharePlan/reward")
    public AjaxResult sharePlanReward(@Validated @RequestBody SharePlanJoinVO sharePlanJoinVO) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyBrewerySharePlan sharePlan = wyBrewerySharePlanService.selectWyBrewerySharePlanById(sharePlanJoinVO.getPlanId());
        if (sharePlan == null) {
            return AjaxResult.error("分享方案不存在");
        }
        if (sharePlan.getPlanStatus() != 1) {
            return AjaxResult.error("分享方案未生效");
        }
        final WyBreweryShareLog wyBreweryShareLog = new WyBreweryShareLog();
        wyBreweryShareLog.setBarId(loginUser.getBarId());
        wyBreweryShareLog.setPlanId(sharePlan.getId());
        wyBreweryShareLog.setUserId(loginUser.getUser().getUserId());
        wyBreweryShareLog.setClaimCount(sharePlan.getQuantityAvailable());
        wyBreweryShareLog.setBreweryId(sharePlan.getBreweryId());
        wyBreweryShareLogService.insertWyBreweryShareLog(wyBreweryShareLog);
        return AjaxResult.success("领取成功");
    }
}
