package com.kexue.skills.controller;

import com.github.pagehelper.PageInfo;
import com.kexue.skills.annotation.RequireAuth;
import com.kexue.skills.common.Assert;
import com.kexue.skills.common.CommonResult;
import com.kexue.skills.entity.CmsContent;
import com.kexue.skills.entity.base.IdDto;
import com.kexue.skills.entity.dto.CmsContentDto;
import com.kexue.skills.entity.dto.QueryContentDto;
import com.kexue.skills.entity.request.ImportPathDto;
import com.kexue.skills.service.CmsContentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * (CmsContent)表控制层
 *
 * @author 王志维
 * @since 2025-02-21 23:01:48
 */
@RestController
@RequestMapping("api/cmsContent")
@Tag(name = "skill（skills）管理 Api")
@CrossOrigin(origins = "*")
public class CmsContentController {
    /**
     * 服务对象
     */
    @Resource
    private CmsContentService cmsContentService;
    /**
     * 分页查询
     *
     * @param queryDto 筛选条件
     * @return 查询结果
     */
    @PostMapping("/getPageList")
    @Operation(summary = "查询分页列表", description = "查询分页列表")
    public CommonResult<PageInfo<CmsContent>> getPageList(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(cmsContentService.getPageList(queryDto));
    }

    /**
     * 查询列表
     *
     * @param queryDto 筛选条件
     * @return 查询结果
     */
    @PostMapping("/getList")
    @Operation(summary = "查询列表", description = "查询列表")
    public CommonResult<PageInfo<CmsContent>> getList(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(new PageInfo<>(cmsContentService.getList(queryDto)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param contentId 主键
     * @return 单条数据
     */
    @PostMapping("queryById/{contentId}")
    @Operation(summary = "通过ID查询skill", description = "通过ID查询skill")
    public CommonResult<CmsContent> queryById(@PathVariable("contentId") Long contentId) {
        // 增加阅读量
        cmsContentService.increaseViewCount(contentId);
        return CommonResult.success(cmsContentService.queryById(contentId));
    }

    /**
     * 新增数据
     *
     * @param cmsContent 实体
     * @return 新增结果
     */
    @PostMapping("/insert")
    @Operation(summary = "新增skill", description = "新增skill")
    @RequireAuth
    public CommonResult<CmsContent> insert(@RequestBody CmsContent cmsContent) {
        return CommonResult.success(cmsContentService.insert(cmsContent));
    }

    /**
     * 编辑数据
     *
     * @param cmsContent 实体
     * @return 编辑结果
     */
    @PostMapping("/update")
    @Operation(summary = "更新skill", description = "更新skill")
    @RequireAuth
    public CommonResult<CmsContent> update(@RequestBody CmsContent cmsContent) {
        return CommonResult.success(cmsContentService.update(cmsContent));
    }

    /**
     * 更新审核状态
     *
     * @param contentId skillID
     * @param auditStatus 审核状态
     * @param reviewerId 审核人ID
     * @param reviewerName 审核人名称
     * @param auditComment 审核意见
     * @return 审核结果
     */
    @PostMapping("/updateAuditStatus")
    @Operation(summary = "更新审核状态", description = "更新审核状态")
    @RequireAuth
    public CommonResult<Boolean> updateAuditStatus(@RequestParam("contentId") Long contentId, 
                                                  @RequestParam("auditStatus") Integer auditStatus, 
                                                  @RequestParam("reviewerId") Long reviewerId, 
                                                  @RequestParam("reviewerName") String reviewerName, 
                                                  @RequestParam(value = "auditComment", required = false) String auditComment) {
        return CommonResult.success(cmsContentService.updateAuditStatus(contentId, auditStatus, reviewerId, reviewerName, auditComment, reviewerName) > 0);
    }

    /**
     * 更新发布状态
     *
     * @param contentId skillID
     * @param publishStatus 发布状态
     * @param publishTime 发布时间
     * @param updateBy 更新人
     * @return 发布结果
     */
    @PostMapping("/updatePublishStatus")
    @Operation(summary = "更新发布状态", description = "更新发布状态")
    @RequireAuth
    public CommonResult<Boolean> updatePublishStatus(@RequestParam("contentId") Long contentId, 
                                                   @RequestParam("publishStatus") Integer publishStatus, 
                                                   @RequestParam(value = "publishTime", required = false) String publishTime, 
                                                   @RequestParam("updateBy") String updateBy) {
        return CommonResult.success(cmsContentService.updatePublishStatus(contentId, publishStatus, publishTime, updateBy) > 0);
    }

    /**
     * 增加阅读量
     *
     * @param contentId skillID
     * @return 增加结果
     */
    @PostMapping("/increaseViewCount/{contentId}")
    @Operation(summary = "增加阅读量", description = "增加阅读量")
    public CommonResult<Boolean> increaseViewCount(@PathVariable("contentId") Long contentId) {
        return CommonResult.success(cmsContentService.increaseViewCount(contentId) > 0);
    }

    /**
     * 通过主键逻辑删除
     *
     * @param idDto 主键
     * @return 删除数据
     */
    @PostMapping("/logicDeleteById")
    @Operation(summary = "逻辑删除skill", description = "逻辑删除skill")
    @RequireAuth
    public CommonResult<Boolean> logicDeleteById(@RequestBody IdDto idDto) {
        return CommonResult.success(cmsContentService.logicDeleteById(idDto.getId(), "admin") > 0);
    }

    /**
     * 删除数据
     *
     * @param contentId 主键
     * @return 删除数据
     */
    @PostMapping("deleteById/{contentId}")
    @Operation(summary = "物理删除skill", description = "物理删除skill")
    @RequireAuth
    public CommonResult<Boolean> deleteById(@PathVariable("contentId") Long contentId) {
        return CommonResult.success(cmsContentService.deleteById(contentId) > 0);
    }

    /**
     * 添加收藏
     *
     * @param contentId skillID
     * @return 操作结果
     */
    @PostMapping("/addFavorite")
    @Operation(summary = "添加收藏", description = "添加skill收藏")
    @RequireAuth
    public CommonResult<Boolean> addFavorite(@RequestParam("contentId") Long contentId) {
        return CommonResult.success(cmsContentService.addFavorite(contentId) > 0);
    }

    /**
     * 取消收藏
     *
     * @param contentId skillID
     * @return 操作结果
     */
    @PostMapping("/removeFavorite")
    @Operation(summary = "取消收藏", description = "取消skill收藏")
    @RequireAuth
    public CommonResult<Boolean> removeFavorite(@RequestParam("contentId") Long contentId) {
        return CommonResult.success(cmsContentService.removeFavorite(contentId) > 0);
    }

    /**
     * 添加查看记录
     *
     * @param contentId skillID
     * @return 操作结果
     */
    @PostMapping("/addView")
    @Operation(summary = "添加查看记录", description = "添加skill查看记录")
    @RequireAuth
    public CommonResult<Boolean> addView(@RequestParam("contentId") Long contentId) {
        return CommonResult.success(cmsContentService.addView(contentId) > 0);
    }

    /**
     * 获取用户历史查看的内容列表
     *
     * @param queryDto 筛选条件，包含分页信息
     * @return 查询结果
     */
    @PostMapping("/getUserHistory")
    @Operation(summary = "获取用户历史查看", description = "获取当前用户历史查看的内容列表，带分页")
    @RequireAuth
    public CommonResult<PageInfo<CmsContent>> getUserHistory(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(cmsContentService.getPageListByUserHistory(queryDto));
    }

    /**
     * 获取用户收藏的内容列表
     *
     * @param queryDto 筛选条件，包含分页信息
     * @return 查询结果
     */
    @PostMapping("/getUserFavorites")
    @Operation(summary = "获取用户收藏", description = "获取当前用户收藏的内容列表，带分页")
    @RequireAuth
    public CommonResult<PageInfo<CmsContent>> getUserFavorites(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(cmsContentService.getPageListByUserFavorites(queryDto));
    }

    /**
     * 获取用户购买的内容列表
     *
     * @param queryDto 筛选条件，包含分页信息
     * @return 查询结果
     */
    @PostMapping("/getUserPurchases")
    @Operation(summary = "获取用户拥有", description = "获取当前用户购买的内容列表，带分页")
    @RequireAuth
    public CommonResult<PageInfo<CmsContent>> getUserPurchases(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(cmsContentService.getPageListByUserPurchases(queryDto));
    }

    /**
     * 获取用户创建的内容列表
     *
     * @param queryDto 筛选条件，包含分页信息和发布状态
     * @return 查询结果
     */
    @PostMapping("/getUserCreated")
    @Operation(summary = "获取用户创建", description = "获取当前用户创建的内容列表，带分页，可查询已发布、未发布")
    @RequireAuth
    public CommonResult<PageInfo<CmsContent>> getUserCreated(@RequestBody CmsContentDto queryDto) {
        return CommonResult.success(cmsContentService.getPageListByUserCreated(queryDto));
    }

    /**
     * 导入Excel数据到CmsContent
     *
     * @param file Excel文件
     * @param createBy 创建人
     * @return 导入结果
     */
    @PostMapping("/importFromExcel")
    @Operation(summary = "导入Excel数据", description = "从Excel文件导入数据到CmsContent")
    @RequireAuth
    public CommonResult<Integer> importFromExcel(@RequestParam("file") MultipartFile file, @RequestParam("createBy") String createBy) {
        try {
            byte[] fileBytes = file.getBytes();
            int successCount = cmsContentService.importFromExcel(fileBytes, createBy);
            return CommonResult.success(successCount);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取CmsContent的content字段内容
     *
     * @param queryContentDto 包含contentId和languageType的DTO对象
     * @return content或contentEn字段的内容
     */
    @PostMapping("/getContent")
    @Operation(summary = "获取内容详情", description = "根据languageType获取content或contentEn字段的内容")
    public CommonResult<String> getContent(@RequestBody QueryContentDto queryContentDto) {
        String content = cmsContentService.getContent(queryContentDto.getContentId(), queryContentDto.getLanguageType());
        return CommonResult.success(content);
    }
    
    /**
     * 获取CmsContent的title字段内容
     *
     * @param contentId 内容ID
     * @return title字段的内容
     */
    @PostMapping("/getTitle/{contentId}")
    @Operation(summary = "获取标题", description = "根据contentId获取title字段的内容")
    public CommonResult<String> getTitle(@PathVariable("contentId") Long contentId) {
        String title = cmsContentService.getTitle(contentId);
        return CommonResult.success(title);
    }
    
    /**
     * 从指定目录导入Excel数据到CmsContent
     *
     * @param importPathDto 导入路径请求参数
     * @param createBy 创建人
     * @return 导入结果
     */
    @PostMapping("/importFromPath")
    @Operation(summary = "从目录导入Excel数据", description = "从指定目录导入Excel数据到CmsContent")
    @RequireAuth
    public CommonResult<Integer> importFromPath(@RequestBody ImportPathDto importPathDto, @RequestParam("createBy") String createBy) {
        try {
            int successCount = cmsContentService.importFromPath(importPathDto, createBy);
            return CommonResult.success(successCount);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("导入失败：" + e.getMessage());
        }
    }
}