package com.yonge.cooleshow.website.controller;

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

import java.io.File;
import java.util.Date;

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.MusicSheetDto;
import com.yonge.cooleshow.biz.dal.dto.search.MusicSheetRelatedQueryInfo;
import com.yonge.cooleshow.biz.dal.dto.search.MusicSheetSearch;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicSheetSearch;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ChargeTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherAuditMusicSheetVo;
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;

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

	@Autowired
	private MusicSheetService musicSheetService;

    @Autowired
    private TeacherService teacherService;

    /**
     * 曲目收藏
     */
    @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(@ApiParam(value = "客户端类型") @RequestParam(value = "clientType", required = false, defaultValue = "STUDENT") String clientType,
                                                              QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

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

        StudentMusicSheetSearch search = new StudentMusicSheetSearch();
        search.setStudentId(sysUser.getId());
        search.setAuditStatus(AuthStatusEnum.PASS);
        search.setUserType(ClientEnum.valueOf(clientType));
        IPage<MusicSheetVo> sheetVoIPage = musicSheetService.myMusic(PageUtil.getPage(query),search);
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }


    /**
     * 我的单曲，收藏单曲
     */
    @GetMapping("/favorite")
    @ApiOperation(value = "学生-收藏单曲")
    public HttpResponseResult<PageInfo<MusicSheetVo>> favoriteMusic(@ApiParam(value = "客户端类型") @RequestParam(value = "clientType", required = false, defaultValue = "STUDENT") String clientType,
                                                                    QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        if (ClientEnum.invalid(clientType)) {
            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.valueOf(clientType));
        return succeed(PageUtil.pageInfo(sheetVoIPage));
    }

    @ApiOperation(value = "老师-个人中心-曲目分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/teacher/list", consumes="application/json", produces="application/json")
    public HttpResponseResult<TeacherAuditMusicSheetVo> list(@RequestBody MusicSheetSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        // 设置只查老师用户 状态为启用
        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);
        }
        query.setSourceType(SourceTypeEnum.TEACHER);
        query.setMyself(true);

        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectPage(PageUtil.getPage(query), query);

        TeacherAuditMusicSheetVo teacherAuditMusicSheetVo = musicSheetService.selectTeacherCount(sysUser.getId());
        if (teacherAuditMusicSheetVo == null) {
            teacherAuditMusicSheetVo = new TeacherAuditMusicSheetVo();
        }
        teacherAuditMusicSheetVo.setList(PageUtil.pageInfo(musicSheetVoIPage));
        return succeed(teacherAuditMusicSheetVo);
    }

    @ApiOperation(value = "老师新增曲目", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/create", consumes="application/json", produces="application/json")
    public HttpResponseResult<Object> create(@Valid @RequestBody MusicSheetDto musicSheetDto) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        if (ChargeTypeEnum.CHARGE.getCode().equals(musicSheetDto.getChargeType().getCode())
                && musicSheetDto.getMusicPrice()==null){
            return failed("此曲谱为收费曲谱，需要提供价格");
        }

        musicSheetDto.setUserId(sysUser.getId());
        musicSheetDto.setAuditStatus(AuthStatusEnum.DOING);
        musicSheetDto.setSubmitAuditTime(new Date());
        musicSheetDto.setSourceType(SourceTypeEnum.TEACHER);

        musicSheetDto.setCreateBy(sysUser.getId());
        musicSheetDto.setCreateTime(new Date());
        musicSheetService.saveMusicSheet(musicSheetDto,sysUser.getId());
        return succeed("新增曲谱成功");
    }

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

        if (musicSheet.getState().equals(YesOrNoEnum.NO)) {
            return failed("曲目已被下架");
        }
        return status(musicSheetService.state(id,"", ClientEnum.TEACHER));
    }


    @ApiOperation(value = "修改", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/update", consumes="application/json", produces="application/json")
    public HttpResponseResult<Object> update(@Valid @RequestBody MusicSheetDto musicSheet) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        if (musicSheet.getId()==null){
            return failed("缺少ID");
        }

        musicSheet.setUserId(sysUser.getId());
        musicSheet.setSubmitAuditTime(new Date());
        musicSheet.setCreateTime(new Date());
        musicSheet.setCreateBy(sysUser.getId());
        musicSheet.setUpdateBy(sysUser.getId());
        musicSheet.setUpdateTime(new Date());
        musicSheet.setSubmitAuditTime(new Date());
        musicSheet.setAuditStatus(AuthStatusEnum.DOING);
        if ( musicSheetService.saveMusicSheet(musicSheet,sysUser.getId())){
            return succeed("修改成功");
        } else {
            return failed("修改失败");
        }
    }

    @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));
    }
}
