package com.yinlihupo.enlish.service.controller;

import com.yinlihupo.enlish.service.constant.LessonPlanConstant;
import com.yinlihupo.enlish.service.domain.dataobject.LessonPlansDO;
import com.yinlihupo.enlish.service.domain.dataobject.VocabularyBankDO;
import com.yinlihupo.enlish.service.model.vo.plan.*;
import com.yinlihupo.enlish.service.service.LessonPlansService;
import com.yinlihupo.enlish.service.utils.TTSUtil;
import com.yinlihupo.enlish.service.utils.WordExportUtil;
import com.yinlihupo.framework.biz.operationlog.aspect.ApiOperationLog;
import com.yinlihupo.framework.common.response.PageResponse;
import com.yinlihupo.framework.common.response.Response;
import com.yinlihupo.framework.common.util.JsonUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
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 java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

@RequestMapping("/plan/")
@RestController
@Slf4j
public class LessonPlanController {

    @Resource
    private LessonPlansService lessonPlanService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "taskExecutor")
    private Executor taskExecutor;
    @Resource
    private TTSUtil ttsUtil;

    @Value("${templates.plan.weekday}")
    private String planWeekday;
    @Value("${templates.plan.weekend}")
    private String planWeekend;

    @PostMapping("generate")
    @ApiOperationLog(description = "生成学案")
    public Response<String> generateLessonPlan(@RequestBody AddLessonPlanReqVO addLessonPlanReqVO) {
        Integer studentId = addLessonPlanReqVO.getStudentId();
        Integer unitId = addLessonPlanReqVO.getUnitId();
        Integer wordSize = addLessonPlanReqVO.getWordSize();
        try {
            if (redisTemplate.opsForValue().get(LessonPlanConstant.buildGeneratePlanContent(studentId)) != null) {
                throw new RuntimeException("学案正在生成，请耐心等待");
            }
            taskExecutor.execute(() -> lessonPlanService.generateLessonPlans(studentId, unitId, wordSize));
            return Response.success("生成学案成功，请等待 10 分钟");
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail("生成学案失败" + e.getMessage());
        }

    }

    @PostMapping("download")
    public void downloadLessonPlan(@RequestBody DownLoadLessonPlanReqVO downLoadLessonPlanReqVO, HttpServletResponse response) {
        Integer id = downLoadLessonPlanReqVO.getId();
        LessonPlansDO lessonPlanById = lessonPlanService.findLessonPlanById(id);

        try {
            Map<String, Object> map = JsonUtils.parseMap(lessonPlanById.getContentDetails(), String.class, Object.class);
            if (!lessonPlanById.getTitle().contains("复习")) {
                WordExportUtil.generateLessonPlanDocx(map, lessonPlanById, response, planWeekday, true);
            } else {
                WordExportUtil.generateLessonPlanDocx(map, lessonPlanById, response, planWeekend, false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @PostMapping("word/voice")
    @ApiOperationLog(description = "获取单词")
    public Response<FindWordVoiceRspVO> findPlanWordVoice(@RequestBody FindWordVoiceReqVO findWordVoiceReqVO) {
        Integer id = findWordVoiceReqVO.getPlanId();
        LessonPlansDO lessonPlanById = lessonPlanService.findLessonPlanById(id);
        try {
            Map<String, Object> map = JsonUtils.parseMap(lessonPlanById.getContentDetails(), String.class, Object.class);
            Object syncVocabList = map.get("syncVocabList");
            List<VocabularyBankDO> list = JsonUtils.parseList(JsonUtils.toJsonString(syncVocabList), VocabularyBankDO.class);
            List<String> words = list.stream().map(VocabularyBankDO::getWord).toList();

            return Response.success(FindWordVoiceRspVO.builder().words(words).build());
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail("获取单词失败");
        }
    }

    @PostMapping("word/voice/tts")
    public void findPlanWordVoiceTTS(@RequestBody FindWordTTSVoiceReqVO findWordVoiceReqVO, HttpServletResponse response) {
        ttsUtil.generateWordVoice(findWordVoiceReqVO.getText(), response);
    }

    @PostMapping("check")
    @ApiOperationLog(description = "检测学案是否在生成")
    public Response<String> checkLessonPlan(@RequestBody FindIsGeneratePlanReqVO findIsGeneratePlanReqVO) {
        Integer studentId = findIsGeneratePlanReqVO.getStudentId();
        String key = LessonPlanConstant.buildGeneratePlanContent(studentId);
        if (redisTemplate.opsForValue().get(key) != null) {
            return Response.fail();
        }
        return Response.success("学案生成完成");
    }

    @PostMapping("student/list")
    @ApiOperationLog(description = "查询学生学案")
    public Response<FindPlanStudentListRspVO> findStudentPlans(@RequestBody FindPlanStudentReqVO findPlanStudentReqVO) {
        List<LessonPlansDO> lessonPlansDOS = lessonPlanService.findLessonPlansByStudentId(findPlanStudentReqVO.getStudentId());
        List<LessonPlanItem> list = lessonPlansDOS.stream().map(lessonPlansDO -> LessonPlanItem
                .builder()
                .id(lessonPlansDO.getId())
                .isFinished(0)
                .title(lessonPlansDO.getTitle())
                .build())
                .toList();

        return Response.success(FindPlanStudentListRspVO.builder().lessonPlanItems(list).build());
    }

}
