package com.yonge.cooleshow.student.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.validation.Valid;

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 com.baomidou.mybatisplus.core.metadata.IPage;
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.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.Student;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.service.AppVersionInfoService;
import com.yonge.cooleshow.biz.dal.service.MusicAlbumService;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
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.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
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 com.yonge.toolset.utils.idcard.IdcardInfoExtractor;

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

	@Autowired
	private MusicSheetService musicSheetService;

    @Autowired
    private MusicAlbumService musicAlbumService;

    @Autowired
    private AppVersionInfoService appVersionInfoService;

    @Autowired
    private StudentService studentService;


    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入musicTag")
    public HttpResponseResult<MusicSheetDetailVo> detail(@ApiParam(value = "曲谱编号", required = true) @PathVariable("id") Long id) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        return succeed(musicSheetService.detail(id, sysUser, ClientEnum.STUDENT));
    }

    @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);
            }
            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(AuthStatusEnum.PASS);
            query.setStudentId(sysUser.getId());
            query.setMyself(false);
        }

        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(AuthStatusEnum.PASS);
        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("无效的客户端类型");
        }

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



    /**
     * 我的单曲，收藏单曲
     */
    @GetMapping("/my")
    @ApiOperation(value = "我的单曲")
    public HttpResponseResult<PageInfo<MusicSheetVo>> myMusic(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(AuthStatusEnum.PASS);
        search.setUserType(ClientEnum.STUDENT);
        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());
        search.setState(YesOrNoEnum.YES);
        search.setAuditStatus(AuthStatusEnum.PASS);
        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(AuthStatusEnum.PASS);
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.practiceMusic(PageUtil.getPage(query),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) {
    	
    	IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.queryRelatedList(PageUtil.getPage(queryInfo),queryInfo.getAlbumId(), queryInfo.getMusicSheetId());
        return succeed(PageUtil.pageInfo(musicSheetVoIPage));
    }

}
