package com.bizzan.bitrade.controller.cms;

import com.bizzan.bitrade.annotation.AccessLog;
import com.bizzan.bitrade.constant.AdminModule;
import com.bizzan.bitrade.constant.PageModel;
import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.entity.AppBanner;
import com.bizzan.bitrade.entity.QAppBanner;
import com.bizzan.bitrade.service.AppBannerService;
import com.bizzan.bitrade.service.LocaleMessageSourceService;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.util.PredicateUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * APP首页Banner管理
 */
@Slf4j
@RestController
@RequestMapping("/cms/app-banner")
public class AppBannerController extends BaseAdminController {

    @Autowired
    private AppBannerService appBannerService;
    @Autowired
    private LocaleMessageSourceService msService;

    /**
     * 创建Banner
     */
    @RequiresPermissions("cms:app-banner:create")
    @PostMapping("/create")
    @AccessLog(module = AdminModule.CMS, operation = "创建App Banner")
    public MessageResult create(
            @RequestParam String title,
            @RequestParam String imageUrl,
            @RequestParam String linkType,
            @RequestParam String linkUrl,
            @RequestParam(defaultValue = "0") Integer sort,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        AppBanner banner = new AppBanner();
        banner.setTitle(title);
        banner.setImageUrl(imageUrl);
        banner.setLinkType(linkType);
        banner.setLinkUrl(linkUrl);
        banner.setSort(sort);
        banner.setStatus(status);
        banner.setStartTime(startTime);
        banner.setEndTime(endTime);
        return success(appBannerService.save(banner));
    }

    /**
     * 更新Banner
     */
    @RequiresPermissions("cms:app-banner:update")
    @PostMapping("/update")
    @AccessLog(module = AdminModule.CMS, operation = "更新App Banner")
    public MessageResult update(
            @RequestParam Long id,
            @RequestParam String title,
            @RequestParam String imageUrl,
            @RequestParam String linkType,
            @RequestParam String linkUrl,
            @RequestParam(defaultValue = "0") Integer sort,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        AppBanner banner = appBannerService.findById(id);
        Assert.notNull(banner, "validate id!");
        banner.setTitle(title);
        banner.setImageUrl(imageUrl);
        banner.setLinkType(linkType);
        banner.setLinkUrl(linkUrl);
        banner.setSort(sort);
        banner.setStatus(status);
        banner.setStartTime(startTime);
        banner.setEndTime(endTime);
        return success(appBannerService.save(banner));
    }

    /**
     * 分页查询
     */
    @RequiresPermissions("cms:app-banner:page-query")
    @PostMapping("/page-query")
    @AccessLog(module = AdminModule.CMS, operation = "分页查询App Banner")
    public MessageResult pageQuery(
            PageModel pageModel,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String title) {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
        if (status != null) {
            booleanExpressions.add(QAppBanner.appBanner.status.eq(status));
        }
        if (StringUtils.isNotBlank(title)) {
            booleanExpressions.add(QAppBanner.appBanner.title.like("%" + title + "%"));
        }
        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        if (pageModel.getProperty() == null) {
            List<String> list = new ArrayList<>();
            list.add("sort");
            List<Sort.Direction> directions = new ArrayList<>();
            directions.add(Sort.Direction.DESC);
            pageModel.setProperty(list);
            pageModel.setDirection(directions);
        }
        Page<AppBanner> all = appBannerService.findAll(predicate, pageModel.getPageable());
        return success(all);
    }

    /**
     * 查询详情
     */
    @RequiresPermissions("cms:app-banner:detail")
    @GetMapping("/detail")
    @AccessLog(module = AdminModule.CMS, operation = "查询App Banner详情")
    public MessageResult detail(@RequestParam Long id) {
        AppBanner banner = appBannerService.findById(id);
        Assert.notNull(banner, "validate id!");
        return success(banner);
    }

    /**
     * 批量删除
     */
    @RequiresPermissions("cms:app-banner:deletes")
    @PostMapping("/deletes")
    @AccessLog(module = AdminModule.CMS, operation = "删除App Banner")
    public MessageResult deletes(@RequestParam Long[] ids) {
        appBannerService.deleteBatch(ids);
        return success();
    }

    /**
     * 启用Banner
     */
    @RequiresPermissions("cms:app-banner:update")
    @PostMapping("/enable")
    @AccessLog(module = AdminModule.CMS, operation = "启用App Banner")
    public MessageResult enable(@RequestParam Long id) {
        AppBanner banner = appBannerService.findById(id);
        Assert.notNull(banner, "validate id!");
        banner.setStatus(1);
        appBannerService.save(banner);
        return success();
    }

    /**
     * 禁用Banner
     */
    @RequiresPermissions("cms:app-banner:update")
    @PostMapping("/disable")
    @AccessLog(module = AdminModule.CMS, operation = "禁用App Banner")
    public MessageResult disable(@RequestParam Long id) {
        AppBanner banner = appBannerService.findById(id);
        Assert.notNull(banner, "validate id!");
        banner.setStatus(0);
        appBannerService.save(banner);
        return success();
    }

    /**
     * 查询App端生效的Banner列表（供前端/App调用）
     */
    @GetMapping("/active-list")
    public MessageResult activeList() {
        return success(appBannerService.findActiveBanners());
    }
}
