package com.yonge.cooleshow.student.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dayaedu.cbs.common.enums.school.EMusicSheetType;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.dto.RealnameAuthReq;
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.MusicAlbumSearch;
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.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.AlbumAndSheetVo;
import com.yonge.cooleshow.biz.dal.vo.CheckVo;
import com.yonge.cooleshow.biz.dal.vo.MusicAlbumVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.wrapper.InstrumentWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.MusicSheetWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.music.MusicCompareWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
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 com.yonge.toolset.utils.idcard.IdcardInfoExtractor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 曲谱表 web 控制层
 * @author yzp
 * @date 2022-03-26 00:21:46
 * @version v1.0
 **/
@RestController
@RequestMapping("${app-config.url.student:}/music/sheet")
@Api(tags = "曲谱表 API接口")
public class MusicSheetController extends BaseController {
    @Resource
    private SysUserFeignService sysUserFeignService;

	@Resource
	private MusicSheetService musicSheetService;

    @Resource
    private MusicAlbumService musicAlbumService;

    @Resource
    private AppVersionInfoService appVersionInfoService;

    @Resource
    private StudentService studentService;

    @Autowired
    private InstrumentService instrumentService;

    /**
     * 查询单条
     */
    @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 = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            sysUser = null;
        }
        return succeed(musicSheetService.detail(id, sysUser, ClientEnum.STUDENT,tenantAlbumId));
    }



    @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 = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            sysUser = null;
        }
        MusicSheetDetailVo detail = musicSheetService.detail(id, sysUser, ClientEnum.STUDENT, 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="/list", consumes="application/json", produces="application/json")
    public HttpResponseResult<PageInfo<MusicSheetVo>> list(@RequestBody StudentMusicSheetSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        // 老师课查看所有曲目
        if (query.getMyself() == null || query.getMyself()) {
            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 {

            Student student = studentService.getById(sysUser.getId());
            if (student == null) {
                return failed("用户信息获取失败");
            }
            if(StringUtils.isBlank(query.getSubjectIds())){
            	query.setSubjectIds(student.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.STUDENT);
        return succeed(PageUtil.pageInfo(musicSheetVoIPage));
    }

    @ApiOperation(value = "乐谱（专辑和曲目同时查询）分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/albumAndSheetList", consumes="application/json", produces="application/json")
    public HttpResponseResult<AlbumAndSheetVo> albumAndSheetList(@RequestBody StudentMusicSheetSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        Student student = studentService.getById(sysUser.getId());
        if (student == null) {
            return failed("用户信息获取失败");
        }

        // 检查app版本
        YesOrNoEnum appAuditVersion = appVersionInfoService.getAppAuditVersion(query.getPlatform(), query.getVersion());
        // 学生 只能看通过审核 并且 启用的 曲目
        query.setState(YesOrNoEnum.YES);
        query.setAuditVersion(appAuditVersion);
        query.setAuditStatus(null);
        query.setStudentId(sysUser.getId());

        // query.setSubjectIds(student.getSubjectId());
        query.setRows(query.getSheetRow());
        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectStudentPage(PageUtil.getPage(query), query, ClientEnum.STUDENT);

        MusicAlbumSearch musicAlbumSearch = new MusicAlbumSearch();
        musicAlbumSearch.setAlbumStatus(YesOrNoEnum.YES);
        musicAlbumSearch.setSortBy(1);
        musicAlbumSearch.setIdAndName(query.getIdAndName());
        musicAlbumSearch.setAuditVersion(appAuditVersion);
        musicAlbumSearch.setAlbumTagIds(query.getMusicTagIds());
        musicAlbumSearch.setPage(query.getPage());
        // musicAlbumSearch.setSubjectIds(student.getSubjectId());
        musicAlbumSearch.setRows(query.getAlbumRow());
        IPage<MusicAlbumVo> musicAlbumVoIPage = musicAlbumService.selectPage(PageUtil.getPage(musicAlbumSearch), musicAlbumSearch);

        AlbumAndSheetVo albumAndSheetVo = new AlbumAndSheetVo();
        albumAndSheetVo.setMusicSheetList(PageUtil.pageInfo(musicSheetVoIPage));
        albumAndSheetVo.setMusicAlbumList(PageUtil.pageInfo(musicAlbumVoIPage));
        return succeed(albumAndSheetVo);
    }

    /**
     * 曲目收藏
     */
    @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 = "STUDENT") String clientType) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        if (ClientEnum.invalid(clientType)) {
            return failed("无效的客户端类型");
        }
        Student student = studentService.getById(sysUser.getId());
        if (student == null) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("学生不存在");
        }


        return succeed(musicSheetService
                .setFavorite(sysUser.getId(),id, ClientEnum.valueOf(clientType),student.getTenantId() !=null && student.getTenantId()>0?"TENANT":"PLATFORM"));
    }



    /**
     * 我的单曲，收藏单曲
     */
    @ApiOperation(value = "我的单曲")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gift", value = "课程赠品 0:购买 1:赠品, 默认值: 0"),
            @ApiImplicitParam(name = "page", value = "分页查询， 默认值: 1"),
            @ApiImplicitParam(name = "row", value = "当前页行数, 默认值: 10"),
    })
    @GetMapping("/my")
    public HttpResponseResult<PageInfo<MusicSheetVo>> myMusic(@RequestParam(value = "gift", required = false, defaultValue = "0") Integer gift,
                                                              QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        search.setStudentId(sysUser.getId());
        // search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setUserType(ClientEnum.STUDENT);
        search.setPurchaseType(Optional.ofNullable(search.getPurchaseType()).orElse(PurchaseRecordTypeEnum.MUSIC));
        search.setCourseGift(gift);

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


    /**
     * 我的单曲，收藏单曲
     */
    @GetMapping("/favorite")
    @ApiOperation(value = "收藏单曲")
    public HttpResponseResult<PageInfo<MusicSheetVo>> favoriteMusic(QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        search.setStudentId(sysUser.getId());
        // 查询学生时机构还是平台
        Student student = studentService.getById(search.getStudentId());
        if (student != null && student.getTenantId() != null && student.getTenantId()>0) {
            search.setProviderType(SourceTypeEnum.TENANT);
        }
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.favoriteMusic(PageUtil.getPage(query),search, ClientEnum.STUDENT);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }


    /**
     * 最近练习
     */
    @GetMapping("/practice")
    @ApiOperation(value = "最近练习")
    public HttpResponseResult<PageInfo<MusicSheetVo>> practiceMusic(QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        search.setStudentId(sysUser.getId());
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setClientType(ClientEnum.STUDENT);
        // 查询学生时机构还是平台
        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(query),search);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }

    /**
     * 最近练习
     */
    @GetMapping("/practice/del/{id}")
    @ApiOperation(value = "删除最近练习记录")
    public HttpResponseResult<Boolean> delPracticeMusic(@PathVariable Long id) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        musicSheetService.delPractice(id,sysUser.getId(),ClientEnum.STUDENT);
        return succeed();
    }



    /**
     * 最近练习
     */
    @GetMapping("/user/practice")
    @ApiOperation(value = "查看指定最近练习记录")
    public HttpResponseResult<PageInfo<MusicSheetVo>> practiceMusic(@RequestParam Long userId) {

        if (userId == null) {
            return failed("用户信息不存在");
        }
        Student student = studentService.getById(userId);
        if (student == null) {
            return failed("用户信息不存在");
        }
        StudentMusicSheetSearch search = new StudentMusicSheetSearch();

        if (student.getTenantId() !=null && student.getTenantId()>0) {
            search.setProviderType(SourceTypeEnum.TENANT);
        }
        search.setStudentId(userId);
        search.setClientType(ClientEnum.STUDENT);
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(null);
        search.setRows(3);
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.practiceMusic(PageUtil.getPage(search),search);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }

    /**
     * 检查实名认证
     */
    @GetMapping("/realNameAuth/check")
    @ApiOperation(value = "检查实名认证")
    public HttpResponseResult<CheckVo> realNameAuthCheck() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        CheckVo checkVo = new CheckVo();
        if (StringUtil.isEmpty(sysUser.getIdCardNo())) {
            checkVo.setCheck(YesOrNoEnum.NO);
        }  else {
            checkVo.setCheck(YesOrNoEnum.YES);
        }
        return succeed(checkVo);
    }


    /**
     * 实名认证
     */
    @PostMapping(value = "/realNameAuth" ,consumes="application/json", produces="application/json")
    @ApiOperation(value = "实名认证", httpMethod="POST",consumes="application/json", produces="application/json")
    public HttpResponseResult<IdcardInfoExtractor> realNameAuth(@Valid @RequestBody RealnameAuthReq realNameAuthDto) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        return sysUserFeignService.realNameAuth(realNameAuthDto);
    }

    @ApiOperation(value = "关联的曲目列表")
    @GetMapping(value="/queryRelatedList")
    public HttpResponseResult<PageInfo<MusicSheetVo>> queryRelatedList(MusicSheetRelatedQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        Student student = studentService.getById(sysUser.getId());
        if (student == null) {
            return failed("用户信息获取失败");
        }
        // 如果是机构学生
        IPage<MusicSheetVo> musicSheetVoIPage;
        if (student.getTenantId() !=null && student.getTenantId()>0) {
            queryInfo.setSubjectId(Long.parseLong(student.getSubjectId()));
            musicSheetVoIPage =musicSheetService.queryTenantRelatedList(PageUtil.getPage(queryInfo),queryInfo);
        } else {

            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 = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        Student student = studentService.getById(sysUser.getId());
        if (student == null) {
            return failed("用户信息获取失败");
        }
        if(StringUtils.isBlank(query.getSubjectIds())){
            query.setSubjectIds(student.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.STUDENT).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);
    }


    @ApiOperation(value = "搜索")
    @PostMapping(value="/search")
    public HttpResponseResult<MusicCompareWrapper.SearchData> search(@RequestBody MusicCompareWrapper.MusicSearch queryInfo) {

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        queryInfo.setUserId(sysUser.getId());
        queryInfo.setProviderType(SourceTypeEnum.PLATFORM);
        return succeed(musicSheetService.search(queryInfo));
    }


    @ApiOperation(value = "搜索机构")
    @PostMapping(value="/searchTenant")
    public HttpResponseResult<MusicCompareWrapper.SearchData> searchTenant(@RequestBody MusicCompareWrapper.MusicSearch queryInfo) {

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        queryInfo.setUserId(sysUser.getId());
        Student student = studentService.getById(sysUser.getId());
        if (student == null) {
            throw new BizException("用户信息获取失败");
        }
        queryInfo.setSubjectId(Integer.parseInt(student.getSubjectId()));
        queryInfo.setProviderType(SourceTypeEnum.TENANT);
        return succeed(musicSheetService.searchTenant(queryInfo));
    }

}
