package com.gxwebsoft.app.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppEventService;
import com.gxwebsoft.app.entity.AppEvent;
import com.gxwebsoft.app.param.AppEventParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 应用操作动态控制器
 *
 * @author 科技小王子
 * @since 2026-03-28 21:29:44
 */
@Slf4j
@Tag(name = "应用操作动态管理")
@RestController
@RequestMapping("/api/app/app-event")
public class AppEventController extends BaseController {

    @Resource
    private AppEventService appEventService;

    @Operation(summary = "分页查询操作动态")
    @GetMapping("/page")
    public ApiResult<PageResult<AppEvent>> page(AppEventParam param) {
        return success(appEventService.pageRel(param));
    }

    @Operation(summary = "查询全部操作动态")
    @GetMapping()
    public ApiResult<List<AppEvent>> list(AppEventParam param) {
        return success(appEventService.listRel(param));
    }

    @Operation(summary = "根据id查询操作动态")
    @GetMapping("/{id}")
    public ApiResult<AppEvent> get(@PathVariable("id") Integer id) {
        return success(appEventService.getByIdRel(id));
    }

    @Operation(summary = "获取应用最新一条动态（用于卡片展示）")
    @GetMapping("/latest/{websiteId}")
    public ApiResult<AppEvent> getLatest(@PathVariable("websiteId") Long websiteId) {
        return success(appEventService.getLatestEvent(websiteId));
    }

    @PreAuthorize("hasAuthority('app:appEvent:save')")
    @OperationLog
    @Operation(summary = "手动记录操作动态")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AppEvent appEvent) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            appEvent.setUserId(loginUser.getUserId());
            appEvent.setTenantId(loginUser.getTenantId());
            if (appEvent.getOperatorId() == null) {
                appEvent.setOperatorId(loginUser.getUserId().longValue());
            }
            if (appEvent.getOperator() == null) {
                appEvent.setOperator(loginUser.getNickname());
            }
        }
        if (appEventService.save(appEvent)) {
            return success("记录成功");
        }
        return fail("记录失败");
    }

    @PreAuthorize("hasAuthority('app:appEvent:update')")
    @OperationLog
    @Operation(summary = "修改操作动态")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AppEvent appEvent) {
        if (appEventService.updateById(appEvent)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appEvent:remove')")
    @OperationLog
    @Operation(summary = "删除操作动态")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (appEventService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('app:appEvent:remove')")
    @OperationLog
    @Operation(summary = "清空应用所有动态记录")
    @DeleteMapping("/clear/{websiteId}")
    public ApiResult<?> clearByWebsiteId(@PathVariable("websiteId") Long websiteId) {
        // 只清空当前租户下的数据
        AppEventParam param = new AppEventParam();
        param.setWebsiteId(websiteId);
        List<AppEvent> list = appEventService.listRel(param);
        if (list.isEmpty()) {
            return success("暂无动态记录");
        }
        List<Long> ids = list.stream().map(AppEvent::getId).collect(java.util.stream.Collectors.toList());
        if (appEventService.removeByIds(ids)) {
            return success("已清空 " + ids.size() + " 条动态记录");
        }
        return fail("清空失败");
    }

    @PreAuthorize("hasAuthority('app:appEvent:remove')")
    @OperationLog
    @Operation(summary = "批量删除操作动态")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (appEventService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
