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.AppHeader;
import com.bizzan.bitrade.entity.QAppHeader;
import com.bizzan.bitrade.service.AppHeaderService;
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首页Header管理
 */
@Slf4j
@RestController
@RequestMapping("/cms/app-header")
public class AppHeaderController extends BaseAdminController {

    @Autowired
    private AppHeaderService appHeaderService;
    @Autowired
    private LocaleMessageSourceService msService;

    /**
     * 创建Header
     */
    @RequiresPermissions("cms:app-header:create")
    @PostMapping("/create")
    @AccessLog(module = AdminModule.CMS, operation = "创建App Header")
    public MessageResult create(
            @RequestParam String title,
            @RequestParam(defaultValue = "image") String mediaType,
            @RequestParam(defaultValue = "0") Integer displayType,
            @RequestParam(defaultValue = "") String mediaUrl,
            @RequestParam(defaultValue = "") String dayMediaUrl,
            @RequestParam(defaultValue = "") String nightMediaUrl,
            @RequestParam(defaultValue = "internal") String linkType,
            @RequestParam(defaultValue = "") 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) {
        AppHeader header = new AppHeader();
        header.setTitle(title);
        header.setMediaType(mediaType);
        header.setDisplayType(displayType);
        header.setMediaUrl(mediaUrl);
        header.setDayMediaUrl(dayMediaUrl);
        header.setNightMediaUrl(nightMediaUrl);
        header.setLinkType(linkType);
        header.setLinkUrl(linkUrl);
        header.setSort(sort);
        header.setStatus(status);
        header.setStartTime(startTime);
        header.setEndTime(endTime);
        return success(appHeaderService.save(header));
    }

    /**
     * 更新Header
     */
    @RequiresPermissions("cms:app-header:update")
    @PostMapping("/update")
    @AccessLog(module = AdminModule.CMS, operation = "更新App Header")
    public MessageResult update(
            @RequestParam Long id,
            @RequestParam String title,
            @RequestParam(defaultValue = "image") String mediaType,
            @RequestParam(defaultValue = "0") Integer displayType,
            @RequestParam(defaultValue = "") String mediaUrl,
            @RequestParam(defaultValue = "") String dayMediaUrl,
            @RequestParam(defaultValue = "") String nightMediaUrl,
            @RequestParam(defaultValue = "internal") String linkType,
            @RequestParam(defaultValue = "") 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) {
        AppHeader header = appHeaderService.findById(id);
        Assert.notNull(header, "validate id!");
        header.setTitle(title);
        header.setMediaType(mediaType);
        header.setDisplayType(displayType);
        header.setMediaUrl(mediaUrl);
        header.setDayMediaUrl(dayMediaUrl);
        header.setNightMediaUrl(nightMediaUrl);
        header.setLinkType(linkType);
        header.setLinkUrl(linkUrl);
        header.setSort(sort);
        header.setStatus(status);
        header.setStartTime(startTime);
        header.setEndTime(endTime);
        return success(appHeaderService.save(header));
    }

    /**
     * 分页查询
     */
    @RequiresPermissions("cms:app-header:page-query")
    @PostMapping("/page-query")
    @AccessLog(module = AdminModule.CMS, operation = "分页查询App Header")
    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(QAppHeader.appHeader.status.eq(status));
        }
        if (StringUtils.isNotBlank(title)) {
            booleanExpressions.add(QAppHeader.appHeader.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<AppHeader> all = appHeaderService.findAll(predicate, pageModel.getPageable());
        return success(all);
    }

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

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

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

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

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