package com.fs.company.controller.qw;

import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.his.dto.SendResultDetailDTO;
import com.fs.qw.dto.SmsLinkRemindCourseDTO;
import com.fs.qw.service.ISmsLinkRemindCourseService;
import com.fs.voice.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 企业微信客户-短信催课Controller
 *
 * @author fs
 * @date 2026-03-24
 */
@Slf4j
@RestController
@RequestMapping("/qw/smsLinkRemindCourse")
public class SmsLinkRemindCourseController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISmsLinkRemindCourseService smsLinkRemindCourseService;

    @PostMapping("/sendCourseLinkMsg")
    public AjaxResult sendCourseLinkMsg(@Valid @RequestBody SmsLinkRemindCourseDTO smsLinkRemindCourseDto) {
        // ========== 1. 参数预处理 ==========
        log.info("发送课程链接短信请求开始, 请求参数: {}", smsLinkRemindCourseDto);

        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (loginUser == null || loginUser.getCompany() == null) {
                log.error("获取登录用户信息失败，用户未登录或公司信息为空");
                return AjaxResult.error("用户未登录或会话已过期");
            }
            //校验企业编号
            if (StringUtil.strIsNullOrEmpty(smsLinkRemindCourseDto.getCorpId())) {
                throw new CustomException("企业corpId为空，不能发送课程链接短信");
            }
            SendResultDetailDTO sendResultDetailDTO = smsLinkRemindCourseService.sendMessageLinkRemindCourse(smsLinkRemindCourseDto);

            if (sendResultDetailDTO.isSuccess()) {
                log.info("发送课程链接短信成功, fsUserId:{}", smsLinkRemindCourseDto.getFsUserId());
                return AjaxResult.success("发送成功");
            } else {
                log.warn("发送短信课程链失败, fsUserId:{}, 失败原因: {}",
                        smsLinkRemindCourseDto.getFsUserId(), sendResultDetailDTO.getFailReason());
                return AjaxResult.error(sendResultDetailDTO.getFailReason());
            }

        } catch (CustomException e) {
            log.warn("业务异常: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());

        } catch (Exception e) {
            log.error("发送课程链接短信异常, fsUserId:{}", smsLinkRemindCourseDto.getFsUserId(), e);
            return AjaxResult.error("系统繁忙，请稍后再试");
        }
    }
}