/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.disk.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.annotation.CommonLog;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.pojo.CommonValidList;
import vip.xiaonuo.common.util.PinyinUtils;
import vip.xiaonuo.disk.domain.CourseAuditRecord;
import vip.xiaonuo.disk.domain.CourseInfo;
import vip.xiaonuo.disk.domain.ResourceUserFile;
import vip.xiaonuo.disk.dto.courseauditrecord.CourseAuditRecordAddParam;
import vip.xiaonuo.disk.dto.courseauditrecord.CourseAuditRecordEditParam;
import vip.xiaonuo.disk.dto.courseauditrecord.CourseAuditRecordIdParam;
import vip.xiaonuo.disk.dto.courseauditrecord.CourseAuditRecordPageParam;
import vip.xiaonuo.disk.service.CourseAuditRecordService;
import vip.xiaonuo.disk.service.CourseInfoService;
import vip.xiaonuo.disk.service.ResourceUserfileService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.*;

/**
 * 资源管理控制器
 *
 * @author honorfire
 * @date  2025/06/20 14:58
 */
@Api(tags = "资源管理控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@Validated
public class CourseAuditRecordController {


    @Resource
    private CourseAuditRecordService courseAuditRecordService;

    @Resource
    private CourseInfoService courseInfoService;

    @Resource
    private ResourceUserfileService resourceUserfileService;

    @Resource
    private PinyinUtils pinyinUtils;


    /**
     * 资源管理-分页列表
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("资源管理-分页列表")
    @SaCheckPermission("/disk/courseauditrecord/page")
    @GetMapping("/disk/courseauditrecord/page")
    public CommonResult<Page<Map<String,Object>>> page(CourseAuditRecordPageParam courseAuditRecordPageParam, HttpServletRequest req) {
        Map param =new HashMap();
        //默认不传情况，列表查询的是未审核的
        String verifyStatus="0";
        if(StringUtils.isNotEmpty(req.getParameter("verifyStatus")))verifyStatus=req.getParameter("verifyStatus");
        param.put("verifyStatus", verifyStatus);
        //文件名称
        param.put("fileName", req.getParameter("fileName"));
        param.put("collegeId", req.getParameter("collegeId"));
        param.put("collegeTwoId", req.getParameter("collegeTwoId"));
        param.put("collegeThreeId", req.getParameter("collegeThreeId"));
        param.put("majorId", req.getParameter("majorId"));
        param.put("resourceType", req.getParameter("resourceType"));
        param.put("suffix", req.getParameter("suffix"));
        Page<Map<String,Object>> list=courseAuditRecordService.queryList(param);
        return CommonResult.data(list);
    }


    /**
     * 资源中心-分页列表
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("资源中心-分页列表")
    @SaCheckPermission("/disk/resourcecentre/page")
    @GetMapping("/disk/resourcecentre/page")
    public CommonResult<Page<Map<String,Object>>> resourcecentrePage(CourseAuditRecordPageParam courseAuditRecordPageParam, HttpServletRequest req) {
        Map param =new HashMap();
        //资源中心排序标识，0最新，1热门，默认为0
        String sortflag="0";
        if(StringUtils.isNotEmpty(req.getParameter("queryFlag")))sortflag=req.getParameter("sortflag");
        param.put("sortflag", sortflag);
        //资源中心功能标识，0默认，1资源推荐，2相关资源
        String funcType="0";
        if(StringUtils.isNotEmpty(req.getParameter("funcType")))funcType=req.getParameter("funcType");
        param.put("funcType", funcType);
        if("2".equals(funcType))
        {
            String userId=StpLoginUserUtil.getLoginUser().getId();
        }

        //资源中心必须全部是审核通过已发布的
        String verifyStatus="2";
        param.put("verifyStatus", verifyStatus);
        //检索信息
        if(StringUtils.isNotEmpty(req.getParameter("queryInfo")))
        {
            //信息检索会从多个方面触发，用or连接，分别检索资源名称，资源名称，资源拼音，关键词，关键词拼音，老师名称
            String queryInfo=req.getParameter("queryInfo");
            param.put("queryInfo", queryInfo);
            String queryInfoPinyin=StringUtils.deleteWhitespace(pinyinUtils.toPinyin(queryInfo));
            param.put("queryInfoPinyin", queryInfoPinyin);
        }

        param.put("collegeId", req.getParameter("collegeId"));
        param.put("collegeTwoId", req.getParameter("collegeTwoId"));
        param.put("collegeThreeId", req.getParameter("collegeThreeId"));
        param.put("majorId", req.getParameter("majorId"));
        param.put("resourceType", req.getParameter("resourceType"));
        param.put("suffix", req.getParameter("suffix"));
        Page<Map<String,Object>> list=courseAuditRecordService.queryResourceCentreList(param);
        return CommonResult.data(list);
    }

    /**
     * 资源管理-添加
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("资源管理-添加")
    @CommonLog("资源管理-添加")
    @SaCheckPermission("/disk/courseauditrecord/add")
    @PostMapping("/disk/courseauditrecord/add")
    public CommonResult<String> add(@RequestBody @Valid CourseAuditRecordAddParam courseAuditRecordAddParam) {

        //该次上传附件信息
        String userFileIdsStr=courseAuditRecordAddParam.getUserfileIds();
        String[] userFileIdList = userFileIdsStr.split(",");
        List<CourseAuditRecord> courseAuditRecordList = new ArrayList<>();
        for (String userFileId : userFileIdList) {
            CourseAuditRecord courseAuditRecord = BeanUtil.toBean(courseAuditRecordAddParam, CourseAuditRecord.class);
            //2025.6.27废弃，改用userfile表，直接有相关信息
//            ResourceUserFile resourceUserFile =resourceUserfileService.queryEntity(userFileId);
//            courseAuditRecord.setFileName(resourceUserFile.getFileName());
            courseAuditRecord.setUserfileId(userFileId);
            courseAuditRecord.setVerifyStatus("0");
            if(StringUtils.isNotEmpty(courseAuditRecordAddParam.getKeywordValue()))courseAuditRecord.setKeywordPinyin(StringUtils.deleteWhitespace(pinyinUtils.toPinyin(courseAuditRecordAddParam.getKeywordValue(),false)));
            courseAuditRecordList.add(courseAuditRecord);
        }
        courseAuditRecordService.addBatch(courseAuditRecordList);
        return CommonResult.ok();
    }

    /**
     * 资源管理-编辑
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("资源管理-编辑")
    @CommonLog("资源管理-编辑")
    @SaCheckPermission("/disk/courseauditrecord/edit")
    @PostMapping("/disk/courseauditrecord/edit")
    public CommonResult<String> edit(@RequestBody @Valid CourseAuditRecordEditParam courseAuditRecordEditParam) {
        if(StringUtils.isEmpty(courseAuditRecordEditParam.getId()))return CommonResult.error("id不能为空");
        CourseAuditRecord courseAuditRecord = BeanUtil.toBean(courseAuditRecordEditParam, CourseAuditRecord.class);
        if(StringUtils.isNotEmpty(courseAuditRecordEditParam.getKeywordValue()))courseAuditRecord.setKeywordPinyin(StringUtils.deleteWhitespace(pinyinUtils.toPinyin(courseAuditRecordEditParam.getKeywordValue(),false)));
        courseAuditRecordService.editOne(courseAuditRecord);
        return CommonResult.ok();
    }

    /**
     * 资源管理-修改状态
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("资源管理-修改状态")
    @CommonLog("资源管理-修改状态")
    @SaCheckPermission("/disk/courseauditrecord/updateStatus")
    @PostMapping("/disk/courseauditrecord/updateStatus")
    public CommonResult<String> updateStatus(@RequestBody @Valid CourseAuditRecordEditParam courseAuditRecordEditParam) {
        if(StringUtils.isEmpty(courseAuditRecordEditParam.getIds()))return CommonResult.error("id组不能为空");
        if(StringUtils.isEmpty(courseAuditRecordEditParam.getVerifyStatus()))return CommonResult.error("审核状态不能为空");
        //校验
        //0未发布，1待审核，2已发布，3未通过，4已删除
        List<String> VerifyStatusList = Arrays.asList("1","2","3","4");
        if(!VerifyStatusList.contains(courseAuditRecordEditParam.getVerifyStatus()))return CommonResult.error("审核状态错误");
        if("1".equals(courseAuditRecordEditParam.getVerifyStatus()))
        {
            if(StringUtils.isEmpty(courseAuditRecordEditParam.getResourceDesc()) )return CommonResult.error("发布未传资源信息");
            if(StringUtils.isEmpty(courseAuditRecordEditParam.getCoverImage()) )return CommonResult.error("发布未传封面");
        }

        //修改审核状态需要同步改变课程状态（2025.6.26废弃）
        //批量处理资源管理击状态
        String idsStr=courseAuditRecordEditParam.getIds();
        String[] idList = idsStr.split(",");
        List<CourseAuditRecord> courseAuditRecordList = new ArrayList<>();
        for (String id : idList) {
            //1.查回课程审核记录（资源管理）设置审核状态以及相关信息
            CourseAuditRecord courseAuditRecord=courseAuditRecordService.queryEntity(id);
            if("1".equals(courseAuditRecordEditParam.getVerifyStatus()))courseAuditRecord.setResourceDesc(courseAuditRecordEditParam.getResourceDesc());
            if("1".equals(courseAuditRecordEditParam.getVerifyStatus()))courseAuditRecord.setCoverImage(courseAuditRecordEditParam.getCoverImage());
            courseAuditRecord.setVerifyStatus(courseAuditRecordEditParam.getVerifyStatus());
            courseAuditRecordList.add(courseAuditRecord);
        }
        courseAuditRecordService.editBatch(courseAuditRecordList);

        //2.查回对应课程信息（2025.6.27废弃，课程和资源解耦，不在强绑定）
//        CourseInfo courseInfo=courseInfoService.queryEntity(courseAuditRecord.getCourseId());
        //设置审核状态（2025.6.26废弃）
//        courseInfo.setVerifyStatus(courseAuditRecord.getVerifyStatus());
//        if("2".equals(courseAuditRecordEditParam.getVerifyStatus()))courseInfo.setPublishTime(new Date());
        //查看是否课程有关联资源
//        Map queryRelateParam = new HashMap();
//        queryRelateParam.put("courseId", courseInfo.getCourseId());
//        queryRelateParam.put("verifyStatus", "2");
//        List<CourseAuditRecord> relateResourceList=courseAuditRecordService.queryCourseAuditRecordList(queryRelateParam);
//        if(relateResourceList != null && relateResourceList.size() > 0)
//        {
//            courseInfo.setHaveresource("1");
//        }
//        else
//        {
//            courseInfo.setHaveresource("0");
//        }
//        courseInfoService.editOne(courseInfo);

        return CommonResult.ok();
    }

    /**
     * 资源中心-添加浏览次数
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("资源中心-添加浏览次数")
    @CommonLog("资源中心-添加浏览次数")
    @SaCheckPermission("/disk/courseauditrecord/addViewCount")
    @PostMapping("/disk/courseauditrecord/addViewCount")
    public CommonResult<String> addViewCount(@RequestBody @Valid CourseAuditRecordEditParam courseAuditRecordEditParam) {
        CourseAuditRecord courseAuditRecord=courseAuditRecordService.queryEntity(courseAuditRecordEditParam.getId());
        courseAuditRecord.setViewCount(String.valueOf(Integer.valueOf(courseAuditRecord.getViewCount())+1));
        return CommonResult.ok();
    }

    /**
     * 资源管理-删除
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation("资源管理-删除")
    @CommonLog("资源管理-删除")
    @SaCheckPermission("/disk/courseauditrecord/delete")
    @PostMapping("/disk/courseauditrecord/delete")
    public CommonResult<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                               CommonValidList<CourseAuditRecordIdParam> courseAuditRecordIdParamList) {
        courseAuditRecordService.delete(courseAuditRecordIdParamList);
        return CommonResult.ok();
    }

    /**
     * 资源管理-详情
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("资源管理-详情")
    @SaCheckPermission("/disk/courseauditrecord/detail")
    @GetMapping("/disk/courseauditrecord/detail")
    public CommonResult<Map<String,Object>> detail(@Valid CourseAuditRecordIdParam courseAuditRecordIdParam, HttpServletRequest req) {
        Map param =new HashMap();
        param.put("id", req.getParameter("id"));
        Map<String,Object> result=courseAuditRecordService.queryInfo(param);
        return CommonResult.data(result);
    }

    /**
     * 资源中心-详情
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("资源中心-详情")
    @SaCheckPermission("/disk/resourcecentre/detail")
    @GetMapping("/disk/resourcecentre/detail")
    public CommonResult<Map<String,Object>> resourcecentreDetail(@Valid CourseAuditRecordIdParam courseAuditRecordIdParam, HttpServletRequest req) {
        Map param =new HashMap();
        param.put("id", req.getParameter("id"));
        Map<String,Object> result=courseAuditRecordService.queryInfo(param);
        return CommonResult.data(result);
    }

    /**
     * 资源管理-查询最近一次信息
     *
     * @author honorfire
     * @date  2025/06/20 14:58
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("资源管理-查询最近一次信息")
    @SaCheckPermission("/disk/courseauditrecord/recentlyRecord")
    @GetMapping("/disk/courseauditrecord/recentlyRecord")
    public CommonResult<Map<String,Object>> recentlyRecord(CourseAuditRecordIdParam courseAuditRecordIdParam, HttpServletRequest req) {
        Map param =new HashMap();
        String userId = StpLoginUserUtil.getLoginUser().getId();
        param.put("userId", userId);
        Map<String,Object> result=courseAuditRecordService.queryRecentlyRecord(param);
        return CommonResult.data(result);
    }

}
