package com.yonge.cooleshow.teacher.controller;

import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.OrderStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.album.PurchaseRecordTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.search.MusicAlbumDetailSearch;
import com.yonge.cooleshow.biz.dal.dto.search.MusicAlbumSearch;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicAlbumSearch;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.service.AppVersionInfoService;
import com.yonge.cooleshow.biz.dal.service.MusicAlbumService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.vo.AlbumDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicAlbumVo;
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.mybatis.support.PageUtil;

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

	@Autowired
	private MusicAlbumService musicAlbumService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private AppVersionInfoService appVersionInfoService;

    @ApiOperation(value = "分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/list", consumes="application/json", produces="application/json")
    public HttpResponseResult<PageInfo<MusicAlbumVo>> list(@RequestBody MusicAlbumSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        Teacher teacher = teacherService.getById(sysUser.getId());
        if (teacher == null) {
            return failed("用户信息获取失败");
        }
        
        if(query.getSubjectIdList() == null || query.getSubjectIdList().size() == 0){
        	List<Long> subjectIdList = new ArrayList<Long>();
        	if(StringUtils.isNotBlank(teacher.getSubjectId())){
        		String[] subjectIds = teacher.getSubjectId().split(",");
        		for(String s : subjectIds){
                	subjectIdList.add(Long.parseLong(s));
        		}
        		query.setSubjectIdList(subjectIdList);
        	}
        }

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

        query.setAlbumStatus(YesOrNoEnum.YES);
        query.setSortBy(1);
        IPage<MusicAlbumVo> iPage = musicAlbumService.selectStudentPage(PageUtil.getPage(query),query, ClientEnum.TEACHER);
        return succeed(PageUtil.pageInfo(iPage));
    }


    /**
     * 专辑详情
     */
    @PostMapping(value = "/detail",  consumes="application/json", produces="application/json")
    @ApiOperation(value = "专辑详情",httpMethod="POST", consumes="application/json", produces="application/json")
    public HttpResponseResult<AlbumDetailVo> detail(@Valid @RequestBody MusicAlbumDetailSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        query.setType(2);
        query.setState(YesOrNoEnum.YES);
        YesOrNoEnum yesOrNoEnum = musicAlbumService.checkFavorite(sysUser.getId(),query.getId(), ClientEnum.TEACHER);
        AlbumDetailVo albumDetailVo = musicAlbumService.detail(PageUtil.getPage(query), query, sysUser,  ClientEnum.TEACHER);
        albumDetailVo.setFavorite(yesOrNoEnum);

        // 相关专辑
        MusicAlbumSearch musicAlbumSearch = new MusicAlbumSearch();
        musicAlbumSearch.setAuditVersion(YesOrNoEnum.NO);
        musicAlbumSearch.setAlbumStatus(YesOrNoEnum.YES);
        musicAlbumSearch.setSortBy(1);
        musicAlbumSearch.setPage(1);
        musicAlbumSearch.setRows(query.getRelatedNum() +1);
        musicAlbumSearch.setAlbumTagIds(albumDetailVo.getAlbumTag());
        IPage<MusicAlbumVo> relatedMusicAlbum = musicAlbumService.selectStudentPage(PageUtil.getPage(musicAlbumSearch),musicAlbumSearch, ClientEnum.TEACHER);
        List<MusicAlbumVo> musicAlbumVos1 = relatedMusicAlbum.getRecords()
                                                      .stream()
                                                      .filter(musicAlbumVo -> !musicAlbumVo.getId()
                                                                                           .equals(albumDetailVo.getId()))
                                                      .collect(Collectors.toList());
        if (musicAlbumVos1.size() > query.getRelatedNum()) {
            musicAlbumVos1 = musicAlbumVos1.subList(0,query.getRelatedNum());
        }
        albumDetailVo.setRelatedMusicAlbum(musicAlbumVos1);
        return succeed(albumDetailVo);
    }

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

         if (ClientEnum.invalid(clientType)) {
             return failed("无效的客户端类型");
         }

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


    /**
     * 专辑收藏
     */
    @GetMapping("/favorite")
    @ApiOperation(value = "收藏专辑列表")
    public HttpResponseResult<PageInfo<MusicAlbumVo>> favoriteAlbum(QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        StudentMusicAlbumSearch search = new StudentMusicAlbumSearch();
        search.studentId(sysUser.getId())
                .albumFavorite(true)
                 .setAlbumStatus(YesOrNoEnum.YES);

        IPage<MusicAlbumVo> albumVoIPage = musicAlbumService.favoriteAlbum(PageUtil.getPage(query), search, ClientEnum.TEACHER);
        return succeed(PageUtil.pageInfo(albumVoIPage));
    }

    /**
     * 已购买专辑信息
     * @return HttpResponseResult<PageInfo<MusicAlbumVo>>
     */
    @ApiOperation(value = "已购买专辑信息")
    @GetMapping("/purchased")
    public HttpResponseResult<PageInfo<MusicAlbumVo>> purchasedAlbumInfo(QueryInfo query) {

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        StudentMusicAlbumSearch search = new StudentMusicAlbumSearch();
        search.studentId(sysUser.getId())
                .albumPurchased(true)
                .purchaseType(PurchaseRecordTypeEnum.ALBUM)
                .orderStatus(OrderStatusEnum.PAID)
                .clientType(ClientEnum.TEACHER);

        IPage<MusicAlbumVo> albumVoIPage = musicAlbumService.favoriteAlbum(PageUtil.getPage(query), search, ClientEnum.TEACHER);
        return succeed(PageUtil.pageInfo(albumVoIPage));
    }
}
