package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayaedu.cbs.openfeign.client.MusicFeignClientService;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetApplicationExtendClientWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetAuthRecordDao;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherMusicSheetAuditReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherMusicSheetAuditSearch;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.MusicSheetAccompaniment;
import com.yonge.cooleshow.biz.dal.entity.MusicSheetAuthRecord;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherMusicSheetVo;
import com.yonge.cooleshow.common.service.IdGeneratorService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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


@Service
public class MusicSheetAuthRecordServiceImpl extends ServiceImpl<MusicSheetAuthRecordDao, MusicSheetAuthRecord> implements MusicSheetAuthRecordService {
    private static final Logger log = LoggerFactory.getLogger(MusicSheetAuthRecordServiceImpl.class);
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private MusicSheetService musicSheetService;
    @Resource
    private MusicFeignClientService musicFeignClientService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private MusicSheetAccompanimentService musicSheetAccompanimentService;

    @Value("${openfeign-client.app-id:1745637981387108354}")
    public Long applicationId;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(TeacherMusicSheetAuditReq param, Long userId) {
        // 查询到审核记录
        List<MusicSheetAuthRecord> list = this.lambdaQuery()
                                              .eq(MusicSheetAuthRecord::getMusicSheetId, param.getMusicSheetId())
                                              .eq(MusicSheetAuthRecord::getAuditState, AuthStatusEnum.DOING.getCode())
                                              .list();
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException("没有找到待审核记录");
        }
        MusicSheetAuthRecord musicSheetAuthRecord = list.get(0);
        musicSheetAuthRecord.setAuditState(param.getAuthStatus());
        musicSheetAuthRecord.setReason(param.getRemark());
        musicSheetAuthRecord.setVerifyUserId(userId);
        musicSheetAuthRecord.setAuditState(param.getAuthStatus());
        MusicSheet musicSheet = musicSheetService.getById(musicSheetAuthRecord.getMusicSheetId());
        if (musicSheet == null) {
            throw new BizException("曲目信息不存在");
        }
        musicSheet.setAuditStatus(param.getAuthStatus());
        musicSheet.setUpdateBy(userId);
        if (param.getAuthStatus().equals(AuthStatusEnum.PASS)) {
            musicSheetService.updateById(musicSheet);
            // 修改老师标签
            teacherService.setTeacherTag(musicSheet.getUserId(), TeacherTagEnum.MUSIC);
            //同步到内容平台
            String musicSheetJson = musicSheetAuthRecord.getMusicSheetJson();
            CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
            CbsMusicSheetWrapper.MusicSheetExtend musicSheetExtend = new CbsMusicSheetWrapper.MusicSheetExtend();
            musicSheetExtend.setApplicationId(applicationId);
            musicSheetExtend.setUserId(addMusicSheet.getCreateBy());
            addMusicSheet.setSendAppFlag(true);
            addMusicSheet.setMusicSheetExtend(musicSheetExtend);
            addMusicSheet.setMusicImg(param.getMusicImg());
            addMusicSheet.setMusicFirstImg(param.getMusicFirstImg());
            addMusicSheet.setMusicJianImg(param.getMusicJianImg());
            if(musicSheet.getCbsMusicSheetId() == null){
                musicSheet.setCbsMusicSheetId(IdWorker.getId());
            }
            addMusicSheet.setId(musicSheet.getCbsMusicSheetId());
            musicFeignClientService.musicSheetAdd(addMusicSheet);
        }else {
            musicSheetService.updateById(musicSheet);
        }
        this.updateById(musicSheetAuthRecord);
        // 发送审核通知
        Map<Long, String> receivers = new HashMap<>();
        SysUser teacher = sysUserService.getByUserId(musicSheet.getUserId());
        receivers.put(musicSheet.getUserId(), teacher.getPhone());
        try {
            sendMusicSheetAuditMessage(param, musicSheet, receivers);
        } catch (Exception e) {
            log.warn("曲目审核消息发送失败，{}", e.getMessage());
        }
    }

    // 发送曲目审核消息
    private void sendMusicSheetAuditMessage(TeacherMusicSheetAuditReq param, MusicSheet musicSheet, Map<Long, String> receivers) {
        if (AuthStatusEnum.PASS.getCode().equals(param.getAuthStatus().getCode())) {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSIC_SHEET_AUTH_PASS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(), musicSheet.getMusicSheetName());
        } else if (AuthStatusEnum.UNPASS.getCode().equals(param.getAuthStatus().getCode())) {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSIC_SHEET_AUTH_UNPASS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(), musicSheet.getMusicSheetName(),
                    param.getRemark());
        }
    }


    /*@Override
    public void setAuditDoing(Long musicSheetId, Long originalMusicSheetId, Long lastMusicSheetId) {
        List<MusicSheetAuthRecord> list = this.lambdaQuery()
                                              .eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetId)
                                              .eq(MusicSheetAuthRecord::getAuditState, AuthStatusEnum.DOING.getCode())
                                              .list();
        if (!CollectionUtils.isEmpty(list)) {
            return;
        }
        MusicSheetAuthRecord musicSheetAuthRecord = new MusicSheetAuthRecord();
        musicSheetAuthRecord.setMusicSheetId(musicSheetId);
        musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
        if (originalMusicSheetId == null) {
            originalMusicSheetId = musicSheetId;
            musicSheetAuthRecord.setFirstAuth(0);
        } else {
            musicSheetAuthRecord.setFirstAuth(1);
        }
        musicSheetAuthRecord.setCreateTime(new Date());
        musicSheetAuthRecord.setOriginalMusicSheetId(originalMusicSheetId);
        this.saveOrUpdate(musicSheetAuthRecord);
    }*/

    @Override
    public String selectAuditReason(Long musicSheetId) {
        MusicSheetAuthRecord one = this.lambdaQuery()
                                       .eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetId)
                                       .orderByDesc(MusicSheetAuthRecord::getId)
                                       .last("limit 1")
                                       .one();
        if (one == null) {
            return "";
        }
        return one.getReason();

    }

    private void checkRecord(MusicSheetAuthRecord musicSheetAuthRecord){
        if(StringUtils.isEmpty(musicSheetAuthRecord.getMusicSheetJson())){
            throw new BizException("曲目信息不能为空");
        }
        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetAuthRecord.getMusicSheetJson(), CbsMusicSheetWrapper.AddMusicSheet.class);
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> addMusicSheetApplicationExtend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(org.apache.commons.collections.CollectionUtils.isEmpty(addMusicSheetApplicationExtend)){
            throw new BizException("曲目应用不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addRecord(MusicSheetAuthRecord musicSheetAuthRecord) {
        //保存曲目信息
        MusicSheet musicSheet = musicSheetService.initMusicSheet(musicSheetAuthRecord.getMusicSheetJson());
        Long userId = sysUserService.getUserId();
        musicSheet.setUserId(userId);
        musicSheet.setCreateBy(userId);
        musicSheet.setUpdateBy(userId);
        musicSheetService.save(musicSheet);
        List<MusicSheetAccompaniment> musicSheetAccompaniments = musicSheetAccompanimentService.initMusicSheetAccompaniment(musicSheetAuthRecord.getMusicSheetJson(),musicSheet.getId());
        musicSheetAccompanimentService.saveBatch(musicSheetAccompaniments);
        String batchNo = idGeneratorService.generatorId("payment") + "";
        musicSheetAuthRecord.setBatchNo(batchNo);
        musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
        musicSheetAuthRecord.setMusicSheetId(musicSheet.getId());
        return baseMapper.insert(musicSheetAuthRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRecord(MusicSheetAuthRecord musicSheetAuthRecord) {
        this.checkRecord(musicSheetAuthRecord);
        if(musicSheetAuthRecord.getId() == null){
            throw new BizException("先选择要修改的曲目");
        }
        MusicSheetAuthRecord record = baseMapper.selectById(musicSheetAuthRecord.getId());
        if (record == null){
            throw new BizException("曲目信息不存在");
        }
        MusicSheet musicSheet = musicSheetService.initMusicSheet(musicSheetAuthRecord.getMusicSheetJson());
        MusicSheet musicSheet1 = musicSheetService.getById(record.getMusicSheetId());
        musicSheet.setCbsMusicSheetId(musicSheet1.getCbsMusicSheetId());
        musicSheet.setUserId(musicSheet1.getUserId());
        musicSheet.setCreateBy(musicSheet1.getCreateBy());
        musicSheet.setUpdateBy(musicSheet1.getUpdateBy());
        if(record.getAuditState() == AuthStatusEnum.DOING){
            musicSheetService.removeById(record.getMusicSheetId());
            musicSheetAccompanimentService.delByMusicSheetId(record.getMusicSheetId());
            //保存曲目信息
            musicSheetService.save(musicSheet);
            List<MusicSheetAccompaniment> musicSheetAccompaniments = musicSheetAccompanimentService.initMusicSheetAccompaniment(musicSheetAuthRecord.getMusicSheetJson(),musicSheet.getId());
            musicSheetAccompanimentService.saveBatch(musicSheetAccompaniments);
            record.setMusicSheetId(musicSheet.getId());
            record.setMusicSheetJson(musicSheetAuthRecord.getMusicSheetJson());
            baseMapper.updateById(record);
        }else {
            //保存曲目信息
            musicSheetService.save(musicSheet);
            List<MusicSheetAccompaniment> musicSheetAccompaniments = musicSheetAccompanimentService.initMusicSheetAccompaniment(musicSheetAuthRecord.getMusicSheetJson(),musicSheet.getId());
            musicSheetAccompanimentService.saveBatch(musicSheetAccompaniments);
            musicSheetAuthRecord.setMusicSheetId(musicSheet.getId());
            musicSheetAuthRecord.setBatchNo(record.getBatchNo());
            musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
            baseMapper.insert(musicSheetAuthRecord);
        }
    }

    @Override
    public IPage<TeacherMusicSheetVo> selectAuditPage(IPage<TeacherMusicSheetVo> page, TeacherMusicSheetAuditSearch query) {
        return page.setRecords(baseMapper.selectAuditPage(page, query));
    }

    @Override
    public MusicSheetDetailVo auditDetail(Long musicSheetAuthRecordId) {
        MusicSheetAuthRecord musicSheetAuthRecord = this.getById(musicSheetAuthRecordId);
        MusicSheetDetailVo detail = musicSheetService.getAuditDetail(musicSheetAuthRecord.getMusicSheetId());
//        List<MusicSheetDetailVo> sheetDetailVos = musicSheetService.getDao().auditDetailList(musicSheetAuthRecord.getMusicSheetId(),null);
//        if (CollectionUtils.isNotEmpty(sheetDetailVos)) {
//            detail.setLastMusicSheet(sheetDetailVos.get(0));
//        }
        return detail;
    }

    @Override
    public List<MusicSheetDetailVo> auditDetailList(String batchNo) {
        List<MusicSheetDetailVo> sheetDetailVos = musicSheetService.getDao().auditDetailList(null, batchNo);
        if (CollectionUtils.isNotEmpty(sheetDetailVos)) {
            List<Long> musicSheetIds = sheetDetailVos.stream().map(e -> e.getId()).collect(Collectors.toList());
            List<MusicSheetAccompaniment> musicSheetAccompaniments = musicSheetAccompanimentService.lambdaQuery()
                                                                                                    .in(MusicSheetAccompaniment::getMusicSheetId, musicSheetIds)
                                                                                                    .list();
            if (CollectionUtils.isNotEmpty(musicSheetAccompaniments)) {
                Map<Long, List<MusicSheetAccompaniment>> musicSheetAccompanimentMap = musicSheetAccompaniments.stream().collect(Collectors.groupingBy(MusicSheetAccompaniment::getMusicSheetId));
                for (MusicSheetDetailVo sheetDetailVo : sheetDetailVos) {
                    sheetDetailVo.setBackground(musicSheetAccompanimentMap.get(sheetDetailVo.getId()));
                }
            }
        }
        return sheetDetailVos;
    }
}