package com.yonge.cooleshow.teacher.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.AppMusicSheetVo;
import com.yonge.cooleshow.biz.dal.dto.MusicSheetRenderDto;
import com.yonge.cooleshow.biz.dal.dto.search.MusicSheetRelatedQueryInfo;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicSheetSearch;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MusicSortType;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.album.PurchaseRecordTypeEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetShareVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.wrapper.MusicSheetWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.EStatus;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.page.QueryInfo;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.Optional;

/**
 * 曲谱表 web 控制层
 * @author yzp
 * @date 2022-03-26 00:21:46
 * @version v1.0
 **/
@RestController
@RequestMapping("${app-config.url.teacher:}/music/sheet")
@Api(tags = "曲谱表 API接口")
public class MusicSheetController extends BaseController {
    @Resource
    private SysUserService sysUserService;
	@Resource
	private MusicSheetService musicSheetService;
    @Resource
    private AppVersionInfoService appVersionInfoService;
    @Resource
    private MusicSheetAuthRecordService musicSheetAuthRecordService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入musicTag")
    public HttpResponseResult<MusicSheetDetailVo> detail(@ApiParam(value = "曲谱编号", required = true) @PathVariable("id") String id,
                                                         @RequestParam(required = false) String tenantAlbumId) {
        SysUser sysUser = sysUserService.getUser();
        MusicSheetDetailVo detail = musicSheetService.detail(id, sysUser, ClientEnum.TEACHER,tenantAlbumId);

        // 设置返回默认值
        if (StringUtil.isEmpty(detail.getAudioFileUrl())) {
            detail.setAudioFileUrl("");
        }
        if (StringUtils.isEmpty(detail.getMusicImg())) {
            detail.setMusicImg("");
        }
        return succeed(detail);
    }


    @GetMapping("/detailUse/{id}")
    @ApiOperation(value = "是否可使用")
    public HttpResponseResult<MusicSheetWrapper.MusicUse> detailUse(@ApiParam(value = "曲谱编号", required = true) @PathVariable("id") String id,
                                                                    @RequestParam(required = false) String tenantAlbumId) {
        SysUser sysUser = sysUserService.getUser();
        if (sysUser == null  || sysUser.getId() == null) {
            sysUser = null;
        }
        MusicSheetDetailVo detail = musicSheetService.detail(id, sysUser, ClientEnum.TEACHER, tenantAlbumId);
        if (detail == null) {
            return failed("曲目不存在");
        }

        MusicSheetWrapper.MusicUse musicUse = new MusicSheetWrapper.MusicUse();
        musicUse.setBuyed(detail.getBuyed());
        musicUse.setPlay(detail.getPlay());
        return succeed(musicUse);
    }

    @ApiOperation(value = "修改", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/updateRenderFile", consumes="application/json", produces="application/json")
    public HttpResponseResult<Object> updateRenderFile(@Valid @RequestBody MusicSheetRenderDto musicSheetRenderDto) {
        SysUser sysUser = sysUserService.getUser();
        if (musicSheetRenderDto.getMusicSheetId()==null){
            return failed("缺少ID");
        }
        MusicSheet musicSheet = musicSheetService.getById(musicSheetRenderDto.getMusicSheetId());
        
        if(musicSheet == null){
        	return failed("参数异常");
        }
        musicSheet.setMusicFirstSvg(musicSheetRenderDto.getMusicFirstSvg());
        musicSheet.setMusicJianSvg(musicSheetRenderDto.getMusicJianSvg());
        musicSheet.setMusicJSON(musicSheetRenderDto.getMusicJSON());
        musicSheet.setMusicSvg(musicSheetRenderDto.getMusicSvg());

        musicSheet.setUpdateBy(sysUser.getId());
        musicSheet.setUpdateTime(new Date());
        if ( musicSheetService.updateById(musicSheet)){
            return succeed("修改成功");
        } else {
            return failed("修改失败");
        }
    }

    @ApiOperation(value = "曲目分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/list", consumes="application/json", produces="application/json")
    public HttpResponseResult<PageInfo<MusicSheetVo>> list(@RequestBody StudentMusicSheetSearch query) {
        SysUser sysUser = sysUserService.getUser();
        // 老师课查看所有曲目
        AuthStatusEnum auditStatus = query.getAuditStatus();
        if (query.getMyself() == null || query.getMyself()) {
            // 设置只查老师用户 状态为启用
            query.setCreateBy(sysUser.getId());
            if (query.getAuditStatus() != null && AuthStatusEnum.PASS.getCode().equals(query.getAuditStatus().getCode())) {
                query.setState(YesOrNoEnum.YES);
            } else if (query.getAuditStatus() != null && AuthStatusEnum.OUT_SALE.getCode().equals(query.getAuditStatus().getCode())) {
                query.setState(YesOrNoEnum.NO);
                query.setAuditStatus(AuthStatusEnum.PASS);
            }else if(query.getAuditStatus() != null && (AuthStatusEnum.UNPASS.getCode().equals(query.getAuditStatus().getCode()) ||
                    AuthStatusEnum.DOING.getCode().equals(query.getAuditStatus().getCode()))){
                query.setState(YesOrNoEnum.NO);
                query.setDelFlag(true);
            }
            query.setSourceType(SourceTypeEnum.TEACHER);
            query.setMyself(true);
        } else {
            Teacher teacher = teacherService.getById(sysUser.getId());
            if (teacher == null) {
                return failed("用户信息获取失败");
            }
            if(StringUtils.isBlank(query.getSubjectIds())){
            	query.setSubjectIds(teacher.getSubjectId());
            }

            // 检查app版本
            query.setAuditVersion(appVersionInfoService.getAppAuditVersion(query.getPlatform(),query.getVersion()));
            //  只能看通过审核 并且 启用的 曲目
            query.setState(YesOrNoEnum.YES);
            query.setAuditStatus(null);
            query.setStudentId(sysUser.getId());
            query.setMyself(false);
            query.setProviderType(SourceTypeEnum.PLATFORM);
        }

        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectStudentPage(PageUtil.getPage(query), query, ClientEnum.TEACHER);
        if(auditStatus != null && !auditStatus.equals(AuthStatusEnum.PASS)){
            return succeed(PageUtil.pageInfo(musicSheetAuthRecordService.convertMusicDetail(musicSheetVoIPage,query.getAuditStatus())));
        }
        return succeed(PageUtil.pageInfo(musicSheetVoIPage));
    }

    @PostMapping("/state/{id}")
    @ApiOperation(value = "启用/停用", notes = "传入id")
    public HttpResponseResult<Boolean> state(@ApiParam(value = "曲目编号", required = true)  @PathVariable Long id) {
        if (StringUtil.isEmpty(id)) {
            return failed("参数不能为空");
        }
        return status(musicSheetService.state(id,"",ClientEnum.TEACHER));
    }

    /**
     * 曲目收藏
     */
    @PostMapping("/favorite/{id}")
    @ApiOperation(value = "曲目收藏/取消收藏")
    public HttpResponseResult<Boolean> favorite(@ApiParam(value = "曲目编号", required = true) @PathVariable("id") Long id,
                                                @ApiParam(value = "客户端类型") @RequestParam(value = "clientType", required = false, defaultValue = "TEACHER") String clientType,
                                                @RequestParam(value = "providerType", required = false, defaultValue = "PLATFORM") String providerType) {
        SysUser sysUser = sysUserService.getUser();
        if (ClientEnum.invalid(clientType)) {
            return failed("无效的客户端类型");
        }

        return succeed(musicSheetService.setFavorite(sysUser.getId(),id, ClientEnum.valueOf(clientType),providerType));
    }

    /**
     * 我的单曲
     */
    @PostMapping("/my")
    @ApiOperation(value = "我的单曲")
    public HttpResponseResult<PageInfo<MusicSheetVo>> myMusic(@RequestBody  StudentMusicSheetSearch search) {
        SysUser sysUser = sysUserService.getUser();
        search.setStudentId(sysUser.getId());
//        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setUserType(ClientEnum.TEACHER);
        search.setPurchaseType(PurchaseRecordTypeEnum.MUSIC);
        search.setCourseGift(Optional.ofNullable(search.getCourseGift()).orElse(EStatus.DISABLE.getValue()));

        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.myMusic(PageUtil.getPage(search),search);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }

    /**
     * 收藏单曲
     */
    @GetMapping("/favorite")
    @ApiOperation(value = "收藏单曲")
    public HttpResponseResult<PageInfo<MusicSheetVo>> favoriteMusic(QueryInfo query) {
        SysUser sysUser = sysUserService.getUser();
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        Teacher teacher = teacherService.getById(sysUser.getId());
        if (teacher.getTenantId() !=null && teacher.getTenantId() >0) {
            search.setTenantId(teacher.getTenantId());
        }
        search.setStudentId(sysUser.getId());
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setProviderType(null);
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.favoriteMusic(PageUtil.getPage(query),search, ClientEnum.TEACHER);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }

    @ApiOperation(value = "乐谱分享")
    @GetMapping(value="/share")
    public HttpResponseResult<MusicSheetShareVo> shareMusicSheet() {
        SysUser sysUser = sysUserService.getUser();
        return succeed(musicSheetService.shareMusicSheet(sysUser));
    }


    @ApiOperation(value = "我的乐谱数量")
    @GetMapping(value="/count")
    public HttpResponseResult<Integer> countTeacherMusicSheet() {
        SysUser sysUser = sysUserService.getUser();
        return succeed(musicSheetService.countTeacherMusicSheet(sysUser));
    }

    @ApiOperation(value = "关联的曲目列表")
    @GetMapping(value="/queryRelatedList")
    public HttpResponseResult<PageInfo<MusicSheetVo>> queryRelatedList(MusicSheetRelatedQueryInfo queryInfo) {
    	
    	IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.queryRelatedList(PageUtil.getPage(queryInfo),queryInfo);
        return succeed(PageUtil.pageInfo(musicSheetVoIPage));
    }


    @ApiOperation(value = "app首页曲目数据", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/appMusicSheet", consumes="application/json", produces="application/json")
    public HttpResponseResult<AppMusicSheetVo> appMusicSheet(@RequestBody StudentMusicSheetSearch query) {
        SysUser sysUser = sysUserService.getUser();
        Teacher teacher = teacherService.getById(sysUser.getId());
        if (teacher == null) {
            return failed("用户信息获取失败");
        }
        if(StringUtils.isBlank(query.getSubjectIds())){
            query.setSubjectIds(teacher.getSubjectId());
        }

        // 检查app版本
        query.setAuditVersion(appVersionInfoService.getAppAuditVersion(query.getPlatform(),query.getVersion()));

        //  只能看通过审核 并且 启用的 曲目
        query.setState(YesOrNoEnum.YES);
        query.setAuditStatus(null);
        query.setStudentId(sysUser.getId());
        query.setMyself(false);
        query.setRows(20);
        query.setProviderType(SourceTypeEnum.PLATFORM);

        AppMusicSheetVo appMusicSheetVo = new AppMusicSheetVo();
        // 推荐曲目
        query.setMusicSortType(MusicSortType.TOP);
        appMusicSheetVo.setTopMusicSheet(musicSheetService.selectStudentPage(PageUtil.getPage(query), query, ClientEnum.TEACHER).getRecords());

        // 审核版本只返回一列
        if (query.getAuditVersion().equals(YesOrNoEnum.YES)) {
            appMusicSheetVo.setHotMusicSheet(new ArrayList<>());
            appMusicSheetVo.setNewMusicSheet(new ArrayList<>());
        } else {
            // 最热曲目
            query.setMusicSortType(MusicSortType.HOT);
            appMusicSheetVo.setHotMusicSheet(
                    musicSheetService.selectStudentPage(PageUtil.getPage(query), query, ClientEnum.STUDENT).getRecords());

            // 最新曲目
            query.setMusicSortType(MusicSortType.NEW);
            appMusicSheetVo.setNewMusicSheet(
                    musicSheetService.selectStudentPage(PageUtil.getPage(query), query, ClientEnum.STUDENT).getRecords());
        }
        return succeed(appMusicSheetVo);
    }


    /**
     * 最近练习
     */
    @GetMapping("/user/practice")
    @ApiOperation(value = "老师查看学生最近练习")
    public HttpResponseResult<PageInfo<MusicSheetVo>> practiceMusic(@RequestParam Long userId) {

        if (userId == null) {
            return failed("用户信息不存在");
        }
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        search.setStudentId(userId);
        search.setClientType(ClientEnum.STUDENT);
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setRows(3);
        // 查询学生时机构还是平台
        Student student = studentService.getById(search.getStudentId());
        if (student != null && student.getTenantId() != null && student.getTenantId()>0) {
            search.setProviderType(SourceTypeEnum.TENANT);
        }
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.practiceMusic(PageUtil.getPage(search),search);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }
}
