package com.yonge.cooleshow.teacher.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.CourseCourseware;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.TenantGroupAlbumMapper;
import com.yonge.cooleshow.biz.dal.service.*;
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.TenantGroupAlbumWrapper;
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.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 曲谱表 web 控制层
 * @author yzp
 * @date 2022-03-26 00:21:46
 * @version v1.0
 **/
@RestController
@RequestMapping("${app-config.url.teacher:}/musicSheet")
@Api(tags = "曲谱表 API接口")
public class MusicSheetCbsController extends BaseController {
    @Resource
    private SysUserService sysUserService;
	@Resource
	private MusicSheetService musicSheetService;
    @Resource
    private MusicFavoriteService musicFavoriteService;
    @Resource
    private CourseCoursewareService courseCoursewareService;
    @Resource
    private AppVersionInfoService appVersionInfoService;
    @Resource
    private InstrumentService instrumentService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private TenantGroupAlbumMapper tenantGroupAlbumMapper;

    /**
     * 查询单条
     *
     * @param id 详情ID
     * @return R<MusicSheetVo.MusicSheet>
     */
    @ApiOperation(value = "查询内容平台数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @GetMapping("/cbsDetail/{id}")
    public R<MusicSheetVo.MusicSheetDetail> cbsDetail(@PathVariable("id") Long id,
                                                      @RequestParam(required = false) String tenantAlbumId) {

        SysUser sysUser = sysUserService.getUser();
        // 曲目信息
        MusicSheet musicSheet = musicSheetService.getDao().get(id);
        if (Objects.isNull(musicSheet)) {
            throw new BizException("曲目信息不存在");
        }
        if (musicSheet.getCbsMusicSheetId() ==null) {
            throw new BizException("曲目信息异常");
        }
        CbsMusicSheetWrapper.MusicSheet cbsMusicSheet = musicSheetService.cbsDetail(musicSheet.getCbsMusicSheetId());
        cbsMusicSheet.setBizId(id);

        MusicSheetVo.MusicSheetDetail musicSheetDetail = JSON.parseObject(JSON.toJSONString(cbsMusicSheet), MusicSheetVo.MusicSheetDetail.class);
        MusicSheetDetailVo detail = musicSheetService.detail(id.toString(), sysUser, ClientEnum.TEACHER, tenantAlbumId);
        if (detail != null) {
            // 设置曲目付费类型
            musicSheetDetail.setPaymentType(detail.getPaymentType());
            // 设置业务端曲目分类
//            musicSheetDetail.setBizMusicCategoryId(detail.getCategoriesId() == null ? null : detail.getCategoriesId().longValue());
            musicSheetDetail.setScoreType(detail.getScoreType());
            musicSheetDetail.setIsConvertibleScore(detail.getNotation() ==YesOrNoEnum.YES);
            musicSheetDetail.setPlay(detail.getPlay());
            musicSheetDetail.setBuyed(detail.getBuyed());
            musicSheetDetail.setMusicPrice(detail.getMusicPrice());
        }
        //获取曲目专辑数量
        musicSheetDetail.setAlbumNums(musicSheetService.getDao().selectMusicAlbumNum(id));
        musicSheetDetail.setExquisiteFlag(musicSheet.getExquisiteFlag());
        musicSheetDetail.setMusicSubject(musicSheet.getMusicSubject());
        musicSheetDetail.setUserId(musicSheet.getCreateBy());
        musicSheetDetail.setFavorite(musicFavoriteService.checkFavorite(id,sysUser.getId(),ClientEnum.STUDENT,null));
        CourseCourseware one = courseCoursewareService.lambdaQuery()
                .eq(CourseCourseware::getMusicSheetId, id)
                .eq(CourseCourseware::getClientType, ClientEnum.TEACHER)
                .eq(CourseCourseware::getUserId, sysUser.getId())
                .eq(CourseCourseware::getDelFlag, false).last("limit 1").one();
        if (one != null) {
            musicSheetDetail.setCoursewareStatus(YesOrNoEnum.YES);
            musicSheetDetail.setCoursewareId(one.getId());
        }

        // 如果是合奏 并且乐器ID = 2268
        musicSheetDetail.setSpecialPercussionFlag(false);
        if ("2268".equals(musicSheetDetail.getMusicalInstrumentIds()) && musicSheetDetail.getMusicSheetType() == EMusicSheetType.CONCERT) {
            musicSheetDetail.setSpecialPercussionFlag(true);
        }

        // 设置乐器信息
        if (StringUtils.isNotBlank(musicSheetDetail.getMusicalInstrumentIds())) {
            List<Long> instrumentIds = Arrays.stream(musicSheetDetail.getMusicalInstrumentIds().split(","))
                .map(Long::parseLong).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(instrumentIds) && CollectionUtils.isNotEmpty(musicSheetDetail.getMusicalInstruments())) {
                Map<Long, InstrumentWrapper.Instrument> instrumentMap = instrumentService.getMapByIds(instrumentIds);
                for (CbsMusicSheetWrapper.MusicalInstrument musicalInstrument : musicSheetDetail.getMusicalInstruments()) {
                    InstrumentWrapper.Instrument instrument = instrumentMap.get(musicalInstrument.getId().longValue());
                    if (instrument != null) {
                        musicalInstrument.setOrientation(instrument.getOrientation());
                    }

                }
            }
        }
        return R.from(musicSheetDetail);
    }

    @ApiOperation(value = "查询分页", notes = "曲谱表- 传入 MusicSheetVo.MusicSheetQuery")
    @PostMapping("/page")
    public HttpResponseResult<PageInfo<MusicSheetWrapper.MusicSheetCloud>> cloudPage(@RequestBody MusicSheetWrapper.MusicSheetCloudQuery query) {

        SysUser sysUser = sysUserService.getUser();
        Teacher teacher = teacherService.getById(sysUser.getId());
        if (teacher == null) {
            return failed("用户信息获取失败");
        }

        // 检查app版本
        YesOrNoEnum appAuditVersion = appVersionInfoService.getAppAuditVersion(query.getPlatform(), query.getVersion());
        // 学生 只能看通过审核 并且 启用的 曲目
        query.setDelFlag(false);
        query.setVersionFlag(appAuditVersion == YesOrNoEnum.YES);
        query.setStatus(true);
        query.setUserId(teacher.getUserId());
        query.setClientType(ClientEnum.TEACHER.name());
        MusicSheet musicSheet =null;
        if (query.getExcludeMusicId() !=null) {
            musicSheet = musicSheetService.getById(query.getExcludeMusicId());
            if (musicSheet == null) {
                return failed("曲目不存在");
            }
            query.setMusicSheetType(musicSheet.getMusicSheetType());
        }
        // 如果是机构老师
        if (query.getProviderType() != null && query.getProviderType() == SourceTypeEnum.TENANT) {
            // 查询机构老师可用的专辑ID集合
            List<TenantGroupAlbumWrapper.BuyTenantAlbum> buyAlbumInfo = tenantGroupAlbumMapper.getBuyAlbumInfo(TenantGroupAlbumWrapper.BuyTenantAlbumQuery.builder().tenantId(teacher.getTenantId()).build());
            if (CollectionUtils.isEmpty(buyAlbumInfo)) {
                return HttpResponseResult.succeed(PageUtil.pageInfo(new Page<>()));
            }
            query.setTenantAlbumIds(buyAlbumInfo.stream().map(TenantGroupAlbumWrapper.BuyTenantAlbum::getId).collect(Collectors.toList()));

        } else {
            query.setProviderType(SourceTypeEnum.PLATFORM);
            if (musicSheet !=null) {
                query.setMusicTagIds(musicSheet.getMusicTag());
                if (StringUtils.isNotBlank(musicSheet.getMusicSubject())) {
                    List<Long> subjectIds = Arrays.stream(musicSheet.getMusicSubject().split(","))
                            .filter(StringUtils::isNotBlank).map(Long::parseLong).collect(Collectors.toList());
                    query.setMustMatchSubjectIds(subjectIds);
                }
            }
        }
        IPage<MusicSheetWrapper.MusicSheetCloud> musicSheetCloudIPage = musicSheetService.cloudPage(query);
        return HttpResponseResult.succeed(PageUtil.pageInfo(musicSheetCloudIPage));
    }
}
