package com.yonge.cooleshow.admin.controller;

import com.yonge.cooleshow.biz.dal.dto.AdjustModel;
import com.yonge.cooleshow.biz.dal.enums.OrderTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
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 org.springframework.web.multipart.MultipartFile;

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.MusicSheetExport;
import com.yonge.cooleshow.biz.dal.dto.ReasonDto;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherMusicSheetAuditReq;
import com.yonge.cooleshow.biz.dal.dto.search.MusicSheetSearch;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicSheetOrderSearch;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherMusicSheetAuditSearch;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherMusicSheetSearch;
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.MusicTagService;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetStudentByMessage;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.vo.StudentMusicSheetOrderVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherMusicSheetVo;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.BizHttpStatus;
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.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.utils.easyexcel.ErrMsg;
import com.yonge.toolset.utils.easyexcel.ExcelDataReader;
import com.yonge.toolset.utils.easyexcel.ExcelException;
import com.yonge.toolset.utils.easyexcel.ExcelUtils;

/**
 * 曲谱表 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 MusicTagService musicTagService;

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入id")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/detail')")
    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.SYSTEM));
    }

	@ApiOperation(value = "新增", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/create", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/create')")
    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("此曲谱为收费曲谱，需要提供价格");
        }
        if (StringUtil.isEmpty(musicSheetDto.getMusicSubject())) {
            return failed("曲目声部不能为空");
        }

        if (musicSheetDto.getNotation() == null) {
            musicSheetDto.setNotation(YesOrNoEnum.NO);
        }
        String musicTag = musicSheetDto.getMusicTag();
        List<Long> musicTagList = StringUtil.toLongList(musicTag);

        //  一级曲谱标签只能选一个二级
        if (!musicTagService.checkParentDifferent(musicTagList)) {
            return failed("每个一级标签只能选一个二级标签");
        }

        if (StringUtil.isEmpty(musicSheetDto.getMusicImg())) {
            throw new BizException("曲目渲染失败");
        }

        musicSheetDto.setUserId(sysUser.getId());
        musicSheetDto.setAuditStatus(AuthStatusEnum.PASS);
        musicSheetDto.setDelFlag(false);
        musicSheetDto.setSourceType(SourceTypeEnum.PLATFORM);

        musicSheetDto.setCreateBy(sysUser.getId());
        musicSheetDto.setCreateTime(new Date());
        musicSheetService.saveMusicSheet(musicSheetDto,sysUser.getId());

        return succeed("新增曲谱成功");

    }

    @ApiOperation(value = "删除", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping("/delete/{id}")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/delete')")
    public Object delete(@PathVariable Long id) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        boolean result = musicSheetService.del(id);
        if (result){
            return succeed("删除成功");
        } else {
            return failed("删除失败");
        }
    }

    @ApiOperation(value = "修改", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/update", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/update')")
    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 service = musicSheetService.getById(musicSheet.getId());
        if (YesOrNoEnum.YES.getCode().equals(service.getState().getCode())) {
            return failed("启用状态不许修改");
        }

        if (musicSheet.getNotation() == null) {
            musicSheet.setNotation(YesOrNoEnum.NO);
        }

        if (StringUtil.isEmpty(musicSheet.getMusicImg())) {
            throw new BizException("曲目渲染失败");
        }

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

    @ApiOperation(value = "分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
    @PostMapping(value="/list", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/list')")
    public HttpResponseResult<PageInfo<MusicSheetVo>> list(@RequestBody MusicSheetSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        query.setAuditStatus(AuthStatusEnum.PASS);
        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectPage(PageUtil.getPage(query), query);
        return succeed(PageUtil.pageInfo(musicSheetVoIPage));
    }


    /**
     * 启用/停用
     */
    @PostMapping("/state/{id}")
    @ApiOperation(value = "启用/停用", notes = "传入id")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/state')")
    public HttpResponseResult<Boolean> state(@ApiParam(value = "曲目编号", required = true)  @PathVariable Long id, @RequestBody ReasonDto reasonDto) {
        if (StringUtil.isEmpty(id)) {
            return failed("参数不能为空");
        }
        MusicSheet musicSheet = musicSheetService.getById(id);
        if (musicSheet == null) {
            return failed("未找到曲目");
        }
        if (YesOrNoEnum.YES.equals(musicSheet.getState()) &&
                musicSheet.getSourceType().equals(SourceTypeEnum.TEACHER) && StringUtil.isEmpty(reasonDto.getReason())) {
            return failed("请填写下架原因");
        }
        return status(musicSheetService.state(id,reasonDto.getReason(),ClientEnum.SYSTEM));
    }


    /**
     * 批量启用/停用
     */
    @PostMapping("/stateList")
    @ApiOperation(value = "批量启用/停用")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/stateList')")
    public HttpResponseResult<Boolean> stateList(@RequestBody ReasonDto reasonDto) {
        if (StringUtil.isEmpty(reasonDto.getMusicSheetIds())) {
            return failed("参数不能为空");
        }
        if (reasonDto.getState() == null) {
            return failed("启用/禁用状态不能为空");
        }
        if (reasonDto.getState().equals(YesOrNoEnum.NO) && StringUtil.isEmpty(reasonDto.getReason())) {
            return failed("停用原因不能为空");
        }

        return status(musicSheetService.stateList(reasonDto));
    }

    /**
     * 学生详情-乐谱
     */
    @PostMapping(value = "/student", consumes="application/json", produces="application/json")
    @ApiOperation(value = "学生详情-乐谱", httpMethod="POST", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/student')")
    public HttpResponseResult<PageInfo<StudentMusicSheetOrderVo>> student(@Valid @RequestBody StudentMusicSheetOrderSearch query) {
        return succeed(PageUtil.pageInfo(musicSheetService.selectStudentOrderPage(PageUtil.getPage(query),query)));
    }


    /**
     * 老师详情-乐谱
     */
    @PostMapping(value = "/teacher", consumes="application/json", produces="application/json")
    @ApiOperation(value = "老师详情-乐谱", httpMethod="POST", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/teacher')")
    public HttpResponseResult<PageInfo<TeacherMusicSheetVo>> teacher(@Valid @RequestBody TeacherMusicSheetSearch query) {
        return succeed(PageUtil.pageInfo(musicSheetService.selectTeacherPage(PageUtil.getPage(query),query)));
    }

    /**
     * 审核中心-乐谱审核列表
     */
    @PostMapping(value = "/audit/list", consumes="application/json", produces="application/json")
    @ApiOperation(value = "审核中心-乐谱审核列表", httpMethod="POST", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/audit/list')")
    public HttpResponseResult<PageInfo<TeacherMusicSheetVo>> audit(@RequestBody TeacherMusicSheetAuditSearch query) {
        return succeed(PageUtil.pageInfo(musicSheetService.selectAuditPage(PageUtil.getPage(query),query)));
    }

    /**
     * 审核中心-乐谱审核
     */
    @PostMapping(value = "/audit", consumes="application/json", produces="application/json")
    @ApiOperation(value = "审核中心-乐谱审核", httpMethod="POST", consumes="application/json", produces="application/json")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/audit')")
    public HttpResponseResult<Boolean> audit(@Valid @RequestBody TeacherMusicSheetAuditReq param) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        return status(musicSheetService.audit(param,sysUser.getId()));
    }


    /**
     * 审核中心-乐谱审核
     */
    @GetMapping(value = "/auditDetail/{authMusicSheetId}")
    @ApiOperation(value = "审核中心-乐谱审核详情",  notes = "传入曲目审核id")
    public HttpResponseResult<MusicSheetDetailVo> auditDetail(@PathVariable Long authMusicSheetId) {

        return succeed(musicSheetService.auditDetail(authMusicSheetId));
    }



    /**
     * 审核中心-乐谱审核记录列表
     */
    @GetMapping(value = "/auditDetailList/{authMusicSheetId}")
    @ApiOperation(value = "审核中心-乐谱审核详情历史记录",  notes = "传入曲目审核id")
    public HttpResponseResult<List<MusicSheetDetailVo>> auditDetailList(@PathVariable Long authMusicSheetId) {

        return succeed(musicSheetService.auditDetailList(authMusicSheetId));
    }





    @PostMapping(value = "/buySendMessage", consumes="application/json", produces="application/json")
    @ApiOperation(value = "发送学生购买老师曲目信息", httpMethod="POST", consumes="application/json", produces="application/json")
    public HttpResponseResult<Boolean> buySendMessage(@Valid @RequestBody MusicSheetStudentByMessage param) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        return status(musicSheetService.sendBuyMessage(param.getTeacherId(), param.getStudentId(), param.getMusicSheetId(),
                                                       ClientEnum.STUDENT, OrderTypeEnum.MUSIC));
    }
    /**
     * 导入
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入", notes = "传入file")
    public HttpResponseResult<List<ErrMsg>> importExcel(@RequestParam("file") MultipartFile file) {
        if (null == file) {
            return HttpResponseResult.failed("请上传文件");
        }
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        try {
            ExcelDataReader<MusicSheetExport> reader = ExcelUtils.getReader(MusicSheetExport.class, file);
            musicSheetService.importExcel(reader.getDataList(), user.getId());
            return HttpResponseResult.succeed();
        } catch (ExcelException e) {
            return HttpResponseResult.failed(BizHttpStatus.IMPORT.getCode(), e.getErrMsgList(), BizHttpStatus.IMPORT.getMsg());
        }
    }


    /**
     * 置顶
     */
    @PostMapping("/top/{id}")
    @ApiOperation(value = "置顶曲目", notes = "传入id")
    @PreAuthorize("@pcs.hasPermissions('music/sheet/top')")
    public HttpResponseResult<Boolean> top(@ApiParam(value = "曲目编号", required = true)  @PathVariable Long id) {
        if (StringUtil.isEmpty(id)) {
            return failed("参数不能为空");
        }
        return status(musicSheetService.top(id));
    }


    /**
     * 设置排序值 和加精
     */
    @PostMapping("/adjust")
    @ApiOperation(value = "曲目调整设置")
    public HttpResponseResult<Boolean> adjust(@RequestBody @Valid AdjustModel model) {

        MusicSheet musicSheet = new MusicSheet();
        musicSheet.setId(model.getId());
        musicSheet.setSortNumber(model.getSort());
        musicSheet.setExquisiteFlag(model.getExquisiteFlag());

        musicSheetService.updateById(musicSheet);

        return succeed();
    }




}
