package com.fs.course.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.config.cloud.CloudHostProper;
import com.fs.course.business.FsVideoResourceBusinessService;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.domain.FsVideoResource;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.service.IFsUserVideoService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.service.IFsUserVideoService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.service.IFsVideoResourceService;
import com.fs.course.vo.FsVideoResourceVO;
import com.fs.framework.web.service.TokenService;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源库管理
 */
@Slf4j
@RestController
@RequestMapping("/course/videoResource")
@AllArgsConstructor
public class FsVideoResourceController extends BaseController {

    private final IFsVideoResourceService fsVideoResourceService;

    private final TokenService tokenService;

    private final ISysConfigService configService;

    private final CloudHostProper cloudHostProper;

    private final FsVideoResourceBusinessService videoResourceBusinessService;
    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;
    @Autowired
    private IFsUserVideoService fsUserVideoService;

    /**
     * 查询视频素材库列表
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String resourceName,
                              @RequestParam(required = false) String fileName,
                              @RequestParam(required = false) Integer typeId,
                              @RequestParam(required = false) Integer typeSubId,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("resourceName", resourceName);
        params.put("fileName", fileName);
        params.put("typeId", typeId);
        params.put("typeSubId", typeSubId);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound()) && config.getIsBound()) {
            params.put("userId", loginUser.getUser().getUserId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<FsVideoResourceVO> list = fsVideoResourceService.selectVideoResourceListByMap(params);
        return getDataTable(list);
    }


    /**
     * 获取视频素材库详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(fsVideoResourceService.getById(id));
    }

    /**
     * 新增视频素材库
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:add')")
    @Log(title = "视频素材库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsVideoResource fsVideoResource) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound()) && config.getIsBound()) {
            fsVideoResource.setUserId(userId);
        }

        fsVideoResource.setCreateTime(LocalDateTime.now());
        boolean save = fsVideoResourceService.save(fsVideoResource);
        if (save&&StringUtils.isNotEmpty(fsVideoResource.getHsyVid())){
            try {
                fsUserCourseVideoService.updateMediaPublishStatus(fsVideoResource.getHsyVid());
                log.info("更新视频发布状态成功，hsyVid: {}", fsVideoResource.getHsyVid());
            } catch (Exception e) {
                log.error("更新视频发布状态失败，hsyVid: {}, 错误: {}", fsVideoResource.getHsyVid(), e.getMessage());
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改视频素材库
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:edit')")
    @Log(title = "视频素材库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsVideoResource fsVideoResource)
    {
        FsVideoResource fsVideoResourceResult = fsVideoResourceService.getById(fsVideoResource.getId());
        fsVideoResourceResult.setOldVideoUrl(fsVideoResourceResult.getVideoUrl());
        fsVideoResource.setUpdateTime(LocalDateTime.now());
        //12.10要求素材名称跟着视频名称走
        fsVideoResourceService.updateById(fsVideoResource);
        fsUserCourseVideoService.updateVideoByVideoUrl(fsVideoResource.getVideoUrl(), fsVideoResourceResult.getOldVideoUrl(), fsVideoResource.getThumbnail(), fsVideoResource.getFileName(), fsVideoResource.getDuration(), fsVideoResource.getLine1(), fsVideoResource.getLine2());
        return AjaxResult.success();
    }

    /**
     * 删除视频素材库
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:remove')")
    @Log(title = "视频素材库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        Wrapper<FsVideoResource> updateWrapper = Wrappers.<FsVideoResource>lambdaUpdate()
                .set(FsVideoResource::getIsDel, 1)
                .in(FsVideoResource::getId, Arrays.asList(ids));
        fsVideoResourceService.update(updateWrapper);
        return AjaxResult.success();
    }

    /**
     * 批量修改视频分类
     *
     * @param typeId
     * @param typeSubId
     * @param ids
     * @return
     */
    @PreAuthorize("@ss.hasPermi('course:videoResource:batchUpdateClass')")
    @Log(title = "视频素材库", businessType = BusinessType.UPDATE)
    @PostMapping("/batchUpdateClass")
    public AjaxResult batchUpdateClass(@RequestParam("typeId") Long typeId,
                                       @RequestParam("typeSubId") Long typeSubId,
                                       @RequestParam("ids") String ids) {
        if (typeId == null || typeId <= 0) {
            return AjaxResult.error("请选择分类");
        }
        if (typeSubId == null || typeSubId <= 0) {
            return AjaxResult.error("请选择子分类");
        }
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("请选择要修改的分类");
        }

        // 将ids字符串分割为ID列表
        List<String> idList = Arrays.asList(ids.split(","));

        // 创建更新条件
        Wrapper<FsVideoResource> updateWrapper = Wrappers.<FsVideoResource>lambdaUpdate()
                .set(FsVideoResource::getTypeId, typeId)
                .set(FsVideoResource::getTypeSubId, typeSubId)
                .in(FsVideoResource::getId, idList.stream().map(Long::valueOf).collect(Collectors.toList()));

        // 执行批量更新
        fsVideoResourceService.update(updateWrapper);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('course:videoResource:batchAdd')")
    @Log(title = "视频素材库", businessType = BusinessType.INSERT)
    @PostMapping("/batchAddVideoResource")
    public AjaxResult batchAddVideoResource(@RequestBody List<FsVideoResource> list) {
        if (Objects.isNull(list) || list.isEmpty()) {
            return AjaxResult.error("数据不能为空");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        list.forEach(v -> {
            v.setCreateTime(LocalDateTime.now());
            if (ObjectUtil.isNotEmpty(config.getIsBound()) && config.getIsBound()) {
                v.setUserId(userId);
            }
        });
        boolean saveStatus = fsVideoResourceService.saveBatch(list);
        if (saveStatus) {
            list.forEach(fsVideoResource -> {
                // 检查hsyVid是否存在且不为空
                if (ObjectUtil.isNotEmpty(fsVideoResource.getHsyVid())) {
                    try {
                        fsUserCourseVideoService.updateMediaPublishStatus(fsVideoResource.getHsyVid());
                        log.info("更新视频发布状态成功，hsyVid: {}", fsVideoResource.getHsyVid());
                    } catch (Exception e) {
                        log.error("更新视频发布状态失败，hsyVid: {}, 错误: {}", fsVideoResource.getHsyVid(), e.getMessage());
                    }
                }
            });
        }
        return AjaxResult.success();
    }
}
