package com.yonge.cooleshow.teacher.controller;

import com.alibaba.fastjson.JSON;
import com.dayaedu.cbs.common.enums.music.EEvaluationStandard;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.google.common.collect.Lists;
import com.microsvc.toolkit.common.response.template.R;
import com.microsvc.toolkit.common.webportal.exception.BizException;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.UserMusic;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.MusicPracticeRecordService;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.service.UserMusicService;
import com.yonge.cooleshow.biz.dal.wrapper.MusicPracticeRecordWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.teacher:}/musicPracticeRecord")
@Api(tags = "曲目练习记录")
public class MusicPracticeRecordController {

    @Autowired
    private MusicPracticeRecordService musicPracticeRecordService;

    @Autowired
    private UserMusicService userMusicService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询单条
     * @param id 详情ID
     * @return R<MusicPracticeRecordVo.MusicPracticeRecord>
     */
    @ApiOperation(value = "详情", notes = "曲目练习记录-根据详情ID查询单条, 传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @GetMapping("/detail/{id}")
    public R<MusicPracticeRecordWrapper.MusicPracticeRecord> detail(@PathVariable("id") Long id) {

        MusicPracticeRecordWrapper.Entity wrapper = musicPracticeRecordService.detail(id);

        if (wrapper == null) {
            throw new BizException("记录不存在");
        }

        // 上传过作品，用作品视频路径覆盖上传视频路径
        // ID集合
        Map<Long, UserMusic> userMusicMap = userMusicService.getMapByMusicPracticeRecordIds(Lists.newArrayList(Long.parseLong(wrapper.getId())));

        UserMusic userMusic = userMusicMap.get(Long.parseLong(wrapper.getId()));
        if (Objects.nonNull(userMusic)) {
            wrapper.setVideoFilePath(userMusic.getVideoUrl());
        }
        MusicPracticeRecordWrapper.MusicPracticeRecord from = MusicPracticeRecordWrapper.MusicPracticeRecord.from(JSON.toJSONString(wrapper));
        // 曲目信息
        MusicSheet musicSheet = musicSheetService.getDao().get(Long.parseLong(wrapper.getMusicSheetId()));
        if (Objects.isNull(musicSheet)) {
            throw new com.yonge.toolset.base.exception.BizException("曲目信息不存在");
        }
        if (musicSheet.getCbsMusicSheetId() ==null) {
            throw new com.yonge.toolset.base.exception.BizException("曲目信息异常");
        }
        CbsMusicSheetWrapper.MusicSheet cbsMusicSheet = musicSheetService.cbsDetail(musicSheet.getCbsMusicSheetId());
        if (cbsMusicSheet != null) {
            from.setRhythmFlag(cbsMusicSheet.getEvaluationStandard() != EEvaluationStandard.FREQUENCY);
        }

        return R.from(from);
    }


    /**
     * 新增
     * @param record MusicPracticeRecordVo.MusicPracticeRecord
     * @return R<Boolean>
     */
    @ApiOperation(value = "新增", notes = "曲目练习记录- 传入 MusicPracticeRecordVo.MusicPracticeRecord")
    @PostMapping("/save")
    public R<String> add( @RequestBody MusicPracticeRecordWrapper.MusicPracticeRecord record) {

        Long userId = sysUserService.getUserId();
        record.userId(String.valueOf(userId)).clientType(ClientEnum.TEACHER.getCode());

        // 新增数据
        MusicPracticeRecordWrapper.MusicPracticeRecord from = MusicPracticeRecordWrapper.MusicPracticeRecord.from(record.jsonString());
        if (record.getDelFlag() !=null && record.getDelFlag()) {
            from.setDelFlag(false);
            from.setHiddenFlag(true);
        }

        return R.from(musicPracticeRecordService.add(from));
    }

    @ApiOperation(value = "用户最后一次评测数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "recordId", value = "曲目练习记录Id", dataType = "long")
    })
    @GetMapping("/getLastEvaluationMusicalNotesPlayStats")
    public Object getLastEvaluationMusicalNotesPlayStats(Long recordId){
        return R.from(musicPracticeRecordService.getLastEvaluationMusicalNotesPlayStats(recordId));
    }

    @ApiOperation(value = "上传音频文件")
    @PostMapping("videoUpload")
    public R<Boolean> videoUpload( @RequestBody MusicPracticeRecordWrapper.MusicPracticeRecord record){

        if (Objects.isNull(record.getId())) {
            throw BizException.from("recordId不能为空");
        }
        if (Objects.isNull(record.getVideoFilePath())) {
            throw BizException.from("videoUrl不能为空");
        }

        MusicPracticeRecordWrapper.Entity practiceRecord = musicPracticeRecordService.getById(record.getId());
        if (Objects.isNull(practiceRecord)) {
            throw BizException.from("记录不存在");
        }

        practiceRecord.setVideoFilePath(record.getVideoFilePath());
        musicPracticeRecordService.update(practiceRecord);

        return R.from(true);
    }

}
