package com.fs.app.controller.course;



import com.fasterxml.jackson.core.JsonProcessingException;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.app.annotation.UserOperationLog;
import com.fs.app.controller.AppBaseController;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.app.annotation.Login;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.course.dto.BatchSendCourseDTO;
import com.fs.course.param.*;
import com.fs.course.param.newfs.FsUserCourseAddCompanyUserParam;
import com.fs.course.param.newfs.FsUserCourseVideoLinkParam;
import com.fs.course.param.newfs.FsUserCourseVideoUParam;
import com.fs.course.service.*;
import com.fs.course.vo.FsUserCourseVideoH5VO;
import com.fs.course.vo.newfs.FsUserCourseVideoLinkDetailsVO;
import com.fs.feishu.model.FeishuLinkParam;
import com.fs.feishu.service.FeiShuService;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsUserOperationEnum;
import com.fs.his.service.IFsUserService;
import com.fs.im.dto.OpenImResponseDTO;
import com.fs.im.service.OpenIMService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api("会员-看课接口")
@RestController
@RequestMapping(value = "/app/course/wx/h5")
public class CourseFsUserController extends AppBaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IFsUserCourseService courseService;

    @Autowired
    private IFsUserCourseVideoService courseVideoService;

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private IFsCourseLinkService courseLinkService;


    @Autowired
    private IFsCourseQuestionBankService questionBankService;

    @Autowired
    private FeiShuService feiShuService;

    @Autowired
    private RedisTemplate redisTemplate;



    @Login
    @ApiOperation("判断是否添加客服（是否关联销售）")
    @PostMapping("/isAddKf")
    public ResponseResult<FsUser> isAddCompanyUser(@Valid @RequestBody FsUserCourseAddCompanyUserParam param) {
        if (ObjectUtil.isEmpty(param.getUserId())){
            Long userId = Long.parseLong(getUserId());
            param.setUserId(userId);
        }

        // 记录appId到fs_user表
        if (StringUtils.isNotEmpty(param.getAppId())) {
            FsUser user = fsUserService.selectFsUserById(param.getUserId());
            if (user != null) {
                String updatedAppId = addAppIdIfNotExists(user.getAppId(), param.getAppId());
                if (!updatedAppId.equals(user.getAppId())) {
                    FsUser userUpdate = new FsUser();
                    userUpdate.setUserId(param.getUserId());
                    userUpdate.setAppId(updatedAppId);
                    fsUserService.updateFsUser(userUpdate);
                }
            }
        }

        return courseVideoService.isAddCompanyUser(param);
    }

    /**
     * 绑定关系
     *
     * @param param
     * @return
     */
    @PostMapping("/isSaveKf")
    public R isSaveKf(@RequestBody FsUserCourseVideoAddKfUParam param){
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        return courseVideoService.isSaveKf(param);
    }


    @ApiOperation("h5课程简介")
    @GetMapping("/getH5CourseByVideoId")
    public R getCourseByVideoId(@RequestParam("videoId") Long videoId)
    {
        FsUserCourseVideoH5VO course = courseService.selectFsUserCourseVideoH5VOByVideoId(videoId);
        if (CloudHostUtils.hasCloudHostName("金牛明医","康年堂")){
            course.setCourseName("");
        }
        return R.ok().put("data",course);
    }

    @Login
    @ApiOperation("H5课程详情")
    @GetMapping("/videoDetails")
    @UserOperationLog(operationType = FsUserOperationEnum.STUDY)
    public ResponseResult<FsUserCourseVideoLinkDetailsVO> getCourseVideoDetails(FsUserCourseVideoLinkParam param) {
        param.setFsUserId(Long.parseLong(getUserId()));
        return courseVideoService.getLinkCourseVideoDetails(param);
    }

    @ApiOperation("获取真实链接")
    @GetMapping("/getRealLink")
    public R getRealLink(@RequestParam("sortLink")String link)
    {
        return courseLinkService.getRealLinkH5(link);
    }

    @ApiOperation("更新看课时长")
    @PostMapping("/updateWatchDuration")
    @Login
    public R updateWatchDuration(@RequestBody FsUserCourseVideoUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return courseVideoService.updateWatchDurationWx(param);
    }


    @ApiOperation("获取缓冲流量")
    @PostMapping("/getInternetTraffic")
    @Login
    public R getInternetTraffic(@RequestBody FsUserCourseVideoFinishUParam param) {
        String uidStr = getUserId();
        try {
            param.setUserId(Long.parseLong(uidStr));
        } catch (Exception ex) {
            logger.error("getInternetTraffic - 无法解析用户ID: {}", uidStr, ex);
            return R.error("未授权或Token不合法：APPToken的subject不是数字");
        }
        if (Integer.valueOf(1).equals(param.getIsOpen())) {
            return courseVideoService.getInternetTrafficIsOpen(param);
        }
        return courseVideoService.getInternetTraffic(param);
    }


    @ApiOperation("答题")
    @PostMapping("/courseAnswer")
    @UserOperationLog(operationType = FsUserOperationEnum.ANSWER)
    @RepeatSubmit
    public R courseAnswer(@RequestBody FsCourseQuestionAnswerUParam param){
        if (ObjectUtil.isEmpty(param.getUserId())){
            Long userId = Long.parseLong(getUserId());
            param.setUserId(userId);
        }
        logger.info("zyp \n【答题】：{}",param.getQuestions());
        if (param.getDuration()==null){
            logger.info("zyp \n【未识别到时长】：{}",param.getUserId());
        }
        return questionBankService.courseAnswerByFsUser(param);
    }

    @ApiOperation("手动发放奖励")
    @PostMapping("/sendReward")
    @UserOperationLog(operationType = FsUserOperationEnum.SENDREWARD)
    @RepeatSubmit
    public R sendReward(@RequestBody FsCourseSendRewardUParam param, HttpServletRequest request)
    {
        if (ObjectUtil.isEmpty(param.getUserId())){
            Long userId = Long.parseLong(getUserId());
            param.setUserId(userId);
        }
        String sourceType = request.getHeader("Sourcetype");
        if(StringUtils.isNotBlank(sourceType)){
            if ("APP".equals(sourceType)) {
                param.setSource(3);
            }
        }
        logger.info("zyp \n【发放奖励】2：{}",param);
        return courseVideoService.sendRewardByFsUser(param);
    }


    @PostMapping("/getErrMsg")
    public void getErrMsg(@RequestParam("msg") String msg) {
        logger.error("zyp \n【h5看课中途报错】：{}",msg);
    }

    @ApiOperation("获取飞书课程链接")
    @PostMapping("/getFeiShuCourseNewLink")
    public R getFeiShuCourseNewLink(@RequestBody FeishuLinkParam param) {
        if (StringUtils.isBlank(param.getLink())){
            return R.error("飞书课程短链不能为空");
        }
        String feishuCourseNewLink = feiShuService.getFeishuCourseNewLink(param);
        return R.ok().put("data", feishuCourseNewLink);
    }

    @Login
    @ApiOperation("发送红包（以积分提现的形式）")
    @PostMapping("/withdrawal")
    @RepeatSubmit
    public R withdrawal(@RequestBody FsCourseSendRewardUParam param){
        String userId = getUserId();
        if(userId == null){
            return R.error("请先登录!");
        }
        param.setUserId(Long.parseLong(userId));
        return R.ok(courseVideoService.withdrawal(param));
    }

    /**
     * 添加appId到用户的appId列表中（如果不存在）
     * @param currentAppIds 当前用户已有的appId列表（逗号分隔）
     * @param newAppId 新的appId
     * @return 更新后的appId列表
     */
    private String addAppIdIfNotExists(String currentAppIds, String newAppId) {
        // 如果新appId为空，返回原值
        if (StringUtils.isEmpty(newAppId)) {
            return currentAppIds == null ? "" : currentAppIds;
        }

        // 如果当前appId为空，直接返回新appId
        if (StringUtils.isEmpty(currentAppIds)) {
            return newAppId;
        }

        // 检查是否已存在
        String[] appIdArray = currentAppIds.split(",");
        for (String appId : appIdArray) {
            if (appId.trim().equals(newAppId.trim())) {
                // 已存在，不需要添加
                return currentAppIds;
            }
        }

        // 不存在，追加到末尾
        return currentAppIds + "," + newAppId;
    }

}
