package com.fs.company.controller.course;

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.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.course.domain.FsCourseLink;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.param.FsCourseLinkRoomNewParam;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.QwUserVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 短链Controller
 *
 * @author fs
 * @date 2024-09-11
 */
@RestController
@RequestMapping("/course/courseLink")
public class FsCourseLinkController extends BaseController
{
    @Autowired
    private IFsCourseLinkService fsCourseLinkService;

    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;

    @Autowired
    private IQwUserService qwUserService;

    @Autowired
    private CompanyUserMapper companyUserMapper;



    /**
     * 查询短链列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsCourseLink fsCourseLink)
    {
        startPage();
        List<FsCourseLink> list = fsCourseLinkService.selectFsCourseLinkList(fsCourseLink);
        return getDataTable(list);
    }

    /**
     * 导出短链列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:export')")
    @Log(title = "短链", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsCourseLink fsCourseLink)
    {
        List<FsCourseLink> list = fsCourseLinkService.selectFsCourseLinkList(fsCourseLink);
        ExcelUtil<FsCourseLink> util = new ExcelUtil<FsCourseLink>(FsCourseLink.class);
        return util.exportExcel(list, "短链数据");
    }

    /**
     * 获取短链详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:query')")
    @GetMapping(value = "/{linkId}")
    public AjaxResult getInfo(@PathVariable("linkId") Long linkId)
    {
        return AjaxResult.success(fsCourseLinkService.selectFsCourseLinkByLinkId(linkId));
    }

    /**
     * 新增短链
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:add')")
    @Log(title = "短链", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCourseLink fsCourseLink)
    {
        return toAjax(fsCourseLinkService.insertFsCourseLink(fsCourseLink));
    }

    /**
     * 修改短链
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:edit')")
    @Log(title = "短链", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCourseLink fsCourseLink)
    {
        return toAjax(fsCourseLinkService.updateFsCourseLink(fsCourseLink));
    }

    /**
     * 删除短链
     */
    @PreAuthorize("@ss.hasPermi('course:courseLink:remove')")
    @Log(title = "短链", businessType = BusinessType.DELETE)
	@DeleteMapping("/{linkIds}")
    public AjaxResult remove(@PathVariable Long[] linkIds)
    {
        return toAjax(fsCourseLinkService.deleteFsCourseLinkByLinkIds(linkIds));
    }

    @PreAuthorize("@ss.hasPermi('course:courseLink:create')")
    @Log(title = "创建短链", businessType = BusinessType.INSERT)
    @PutMapping("createLinkUrl")
    public R createLinkUrl(@RequestBody FsCourseLinkCreateParam param)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        return fsCourseLinkService.createLinkUrl(param);
    }

    /**
     * 根据销售id去查询已经绑定的企微
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('course:courseLink:queryQwIds')")
    @GetMapping("/queryQwIds")
    public R selectQwUserIdByCompanyUserId()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(loginUser.getUser().getUserId());
        String qwUserId = companyUser.getQwUserId();
        if(qwUserId == null || qwUserId.isEmpty()){
            return R.error("请先绑定企微");
        }
        Long[] array = Arrays.stream(qwUserId.split(","))
                .map(String::trim) // 去除空白
                .filter(str -> !str.isEmpty()) // 过滤空字符串
                .map(str -> {
                    try {
                        return Long.parseLong(str);
                    } catch (NumberFormatException e) {
                        return null; // 非数字设为null
                    }
                })
                .filter(num -> num != null) // 过滤null（非数字值）
                .toArray(Long[]::new);
        List<QwUserVO> qwUserVOS = qwUserService.selectQwUserVOByIds(array);
        return R.ok().put("list",qwUserVOS);
    }

    /**
     * 创建课程看课链接
     * @param param
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('course:courseLink:createRoomLink')")
    @PostMapping("/createRoomLink")
    @ApiOperation("创建群发链接")
    public R createRoomLink(@RequestBody FsCourseLinkRoomNewParam param) {

        if (param.getCourseId()==null){
            return R.error("课程id不能为空");
        }
        if (param.getVideoId()==null){
            return R.error("视频id不能为空");
        }
        if (param.getQwUserId()==null){
            return R.error("销售企微不能为空");
        }

        return fsUserCourseVideoService.createRoomMiniLinkByCourse(param);
    }

    /**
     * 提取飞书免授权看课链接
     */
    @PostMapping("/createFeishuLink")
    @ApiOperation("提取飞书免授权看课链接")
    public R createFeishuLink(@RequestBody FsCourseLinkRoomNewParam param) {
        if (param.getCourseId() == null) {
            return R.error("课程id不能为空");
        }
        if (param.getVideoId() == null) {
            return R.error("视频id不能为空");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setCompanyUserId(loginUser.getUser().getUserId());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        return fsUserCourseVideoService.createFeishuLinkByCourse(param);
    }

}
