package com.ruoyi.bar;

import com.ruoyi.bar.domain.NewMonthBeer;
import com.ruoyi.bar.domain.WyFavoriteBrewery;
import com.ruoyi.bar.service.IWyFavoriteService;
import com.ruoyi.brewery.domain.*;
import com.ruoyi.brewery.service.IWyActivityService;
import com.ruoyi.brewery.service.IWyBeerService;
import com.ruoyi.brewery.service.IWyBreweryService;
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.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.WyPlatformActivity;
import com.ruoyi.system.domain.WyPlatformBanner;
import com.ruoyi.system.domain.WyPlatformFeaturePage;
import com.ruoyi.system.domain.vo.WyActivityVO;
import com.ruoyi.system.service.IWyPlatformActivityService;
import com.ruoyi.system.service.IWyPlatformBannerService;
import com.ruoyi.system.service.IWyPlatformFeaturePageService;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

@Api(tags = "平台信息")
@RestController
@RequestMapping("/bar/platform")
public class BarPlatFormController extends BaseController {

    @Autowired
    private IWyPlatformBannerService wyPlatformBannerService;

    @Autowired
    private IWyPlatformFeaturePageService wyPlatformFeaturePageService;
    @Autowired
    private IWyPlatformActivityService wyPlatformActivityService;
    @Resource
    private SysConfigServiceImpl sysConfigService;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private IWyBreweryService wyBreweryService;
    @Resource
    private IWyActivityService wyActivityService;
    @Resource
    private IWyFavoriteService wyFavoriteService;
    /**
     * 查询platFormBanner列表
     */
    @ApiOperation(value = "查询Banner列表", notes = "查询Banner列表")
    @GetMapping("/banner/list")
    public AjaxResult list(String bannerType) {
        WyPlatformBanner wyPlatformBanner = new WyPlatformBanner();
        wyPlatformBanner.setPublishState(1);
        wyPlatformBanner.setBannerType(bannerType);
        List<WyPlatformBanner> list = wyPlatformBannerService.selectWyPlatformBannerList(wyPlatformBanner);
        return AjaxResult.success(list);
    }

    /**
     * 获取营销活动详细信息
     */
    @ApiOperation(value = "获取营销活动详细信息", notes = "获取营销活动详细信息")
    @GetMapping(value = "/activity/{id}")
    public AjaxResult getActivityInfo(@PathVariable("id") Long id) {
        return success(wyPlatformActivityService.selectWyPlatformActivityById(id));
    }

    /**
     * 查询营销活动列表
     */
    @ApiOperation(value = "查询营销活动列表", notes = "查询营销活动列表")
    @GetMapping("/activity/list")
    public AjaxResult activityList() {
        WyPlatformActivity wyPlatformActivity = new WyPlatformActivity();
        wyPlatformActivity.setActivityStatus(1);
        List<WyPlatformActivity> list = wyPlatformActivityService.selectWyPlatformActivityList(wyPlatformActivity);

//        WyActivity wyActivity = new WyActivity();
//        wyActivity.setActivityStatus(1);
//        final List<WyActivity> wyActivities = wyActivityService.selectWyActivityList(wyActivity);

        List<WyActivityVO> wyActivityVOS = new ArrayList<>();
        list.forEach(item -> {
            final WyActivityVO wyActivityVO = new WyActivityVO();
            BeanUtils.copyProperties(item, wyActivityVO);
            wyActivityVO.setBreweryId(0L);
            wyActivityVOS.add(wyActivityVO);
        });
//        wyActivities.forEach(item -> {
//            final WyActivityVO wyActivityVO = new WyActivityVO();
//            BeanUtils.copyProperties(item, wyActivityVO);
//            wyActivityVOS.add(wyActivityVO);
//        });
        wyActivityVOS.sort(Comparator.comparing(WyActivityVO::getStartDate).reversed());
        return AjaxResult.success(wyActivityVOS);
    }

    /**
     * 获取专题页详细信息
     */
    @ApiOperation(value = "获取专题页详细信息", notes = "获取专题页详细信息")
    @GetMapping(value = "/feature/{id}")
    public AjaxResult getFeatureInfo(@PathVariable("id") Long id) {
        return success(wyPlatformFeaturePageService.selectWyPlatformFeaturePageById(id));
    }

    /**
     * 查询专题页列表
     */
    @ApiOperation(value = "查询专题页列表", notes = "查询专题页列表")
    @GetMapping("/feature/list")
    public AjaxResult featureList() {
        WyPlatformFeaturePage wyPlatformFeaturePage = new WyPlatformFeaturePage();
        wyPlatformFeaturePage.setPublishState(1);
        List<WyPlatformFeaturePage> list = wyPlatformFeaturePageService.selectWyPlatformFeaturePageList(wyPlatformFeaturePage);
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "获取客服二维码", notes = "获取客服二维码")
    @GetMapping("/customerServiceQRCode")
    public AjaxResult customerServiceQRCode() {
        final String url = sysConfigService.selectConfigByKey("CustomerService.QRCode");
        HashMap<String, Object> map = new HashMap<>();
        map.put("url", url);
        return success(map);
    }

    @ApiOperation(value = "热门啤酒风格", notes = "热门啤酒风格")
    @GetMapping("/popularStyles")
    public AjaxResult popularStyles() {
        final List<PopularStyleVO> popularStyleVOS = wyBeerService.selectPopularStyles();
        return success(popularStyleVOS);
    }

    @ApiOperation(value = "通用搜索", notes = "通用搜索")
    @GetMapping("/commonSearch")
    public AjaxResult commonSearch(@RequestParam("search") String searchText) {
        if (searchText == null || searchText.trim().length() == 0) {
            throw new IllegalArgumentException("搜索内容不能为空");
        }
        if (searchText.trim().length() < 2) {
            throw new IllegalArgumentException("搜索内容长度不能少于2个字符");
        }
        searchText = searchText.trim();
        HashMap<String, Object> map = new HashMap<>();
        final WyBeer beerQuery = new WyBeer();
        beerQuery.setBeerName(searchText);
        final List<WyBeer> wyBeers = wyBeerService.selectWyBeerList(beerQuery);
        map.put("beers", wyBeers);

        final WyBrewery breweryQuery = new WyBrewery();
        breweryQuery.setBrandName(searchText);
        final List<WyBrewery> wyBreweries = wyBreweryService.selectWyBreweryList(breweryQuery);
        map.put("breweries", wyBreweries);
        return success(map);
    }

    @ApiOperation("风格酒款列表")
    @GetMapping("/getBeerListByStyle")
    public TableDataInfo getBeerListByStyle(@RequestParam(name = "style") String style,
                                            @RequestParam(name = "brewery_id", required = false) Long brewery_id,
                                            @RequestParam(name = "orderByColumn", required = false, defaultValue = "beer_reviews_count") String orderByColumn) {
        final WyBeer beer = new WyBeer();
        if (style == null) {
            throw new IllegalArgumentException("风格不能为空");
        }
        if (orderByColumn != null && !orderByColumn.equals("beer_reviews_count") && !orderByColumn.equals("beer_overall_rating") && !orderByColumn.equals("create_time")) {
             throw new IllegalArgumentException("排序字段错误,只能是beer_reviews_count,beer_overall_rating,create_time");
        }
        beer.setBeerStyles(style);
        beer.setOnSale(1);
        if (brewery_id != null) {
            beer.setBreweryId(brewery_id);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderByColumn", orderByColumn);
        map.put("isAsc", "desc");
        beer.setParams(map);
        startPage();
        final List<WyBeer> wyBeers = wyBeerService.selectWyBeerList(beer);
        return getDataTable(wyBeers);
    }

    @ApiOperation("最近的6个月")
    @GetMapping("/lastSixMonth")
    public AjaxResult lastSixMonth(@RequestParam(name = "style", required = false) String style) {
        Month currentMonth = LocalDate.now().getMonth();
        List<NewMonthBeer> months = new ArrayList<>();
        months.add(getNewMonthBeer(currentMonth, 0,style));
        months.add(getNewMonthBeer(currentMonth, 1,style));
        months.add(getNewMonthBeer(currentMonth, 2,style));
        months.add(getNewMonthBeer(currentMonth, 3,style));
        months.add(getNewMonthBeer(currentMonth, 4,style));
        months.add(getNewMonthBeer(currentMonth, 5,style));

        return AjaxResult.success(months);
    }

    @ApiOperation("获取新酒品列表")
    @GetMapping("/newBeerListByMonth")
    public AjaxResult newBeerListByMonth(@RequestParam(name = "num", required = false, defaultValue = "0") Integer num,
                                         @RequestParam(name = "style", required = false) String style) {
        if (num < 0 || num > 5) {
            throw new IllegalArgumentException("参数错误");
        }
        final List<WyBeer> wyBeers = getNewBeersByMonth(num,style);
        return AjaxResult.success(wyBeers);
    }

    private NewMonthBeer getNewMonthBeer(Month currentMonth, Integer num,String style) {
        NewMonthBeer monthBeer = new NewMonthBeer();
        monthBeer.setMonth(currentMonth.minus(num).getValue());
        final List<WyBeer> newBeersByMonth = getNewBeersByMonth(num,style);
        monthBeer.setBeers(newBeersByMonth);
        monthBeer.setBeerCount(newBeersByMonth.size());
        return monthBeer;
    }

    private List<WyBeer> getNewBeersByMonth(Integer num,String style) {
        YearMonth yearMonth = YearMonth.now();
        YearMonth yyyymm = yearMonth.minusMonths(num);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD);
        LocalDate startOfMonth = yyyymm.atDay(1);
        LocalDate endOfMonth = yyyymm.atEndOfMonth();
        final String beginTime = startOfMonth.format(formatter);
        final String endTime = endOfMonth.format(formatter);
        final WyBeer beer = new WyBeer();
        beer.setOnSale(1);
        HashMap<String, Object> map = new HashMap<>();
        map.put("beginLaunchTime", beginTime);
        map.put("endLaunchTime", endTime);
        beer.setParams(map);
        if (style != null) {
            beer.setBeerStyles(style);
        }
        return wyBeerService.selectWyBeerList(beer);
    }

}
