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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dayaedu.cbs.common.enums.music.EMusicSourceType;
import com.dayaedu.cbs.common.enums.school.EMusicSheetType;
import com.dayaedu.cbs.openfeign.properties.OpenFeignClientConfigProperties;
import com.dayaedu.cbs.openfeign.service.CbsMusicSheetService;
import com.dayaedu.cbs.openfeign.wrapper.music.*;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.MusicTagService;
import com.yonge.cooleshow.biz.dal.service.SubjectService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.payment.util.DistributedLock;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CbsMusicSheetServiceImpl implements CbsMusicSheetService {

    private static final Logger log = LoggerFactory.getLogger(CbsMusicSheetServiceImpl.class);

    @Resource
    private MusicSheetService musicSheetService;
    @Resource
    private MusicTagService musicTagService;
    @Resource
    private SubjectService subjectService;

    @Autowired
    private SysConfigService sysConfigService;
    @Resource
    private OpenFeignClientConfigProperties openFeignClientConfigProperties;

    @Autowired
    private RedissonClient redissonClient;


    @Override
//    @Transactional(rollbackFor = Exception.class)
    public Boolean saveApplicationExtend(List<CbsMusicSheetApplicationExtendWrapper.MusicSheetApplicationExtend> addMusicSheet) {
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(addMusicSheet)) {
            throw new BizException("请选择曲目信息");
        }
        String defaultMusicUserId = sysConfigService.findConfigValue(SysConfigConstant.DEFAULT_MUSIC_USER_ID);
        String cbsTenantAppId = sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID);
        Long userId = 3L;
        if (StringUtils.isNotBlank(defaultMusicUserId)) {
            userId = Long.parseLong(defaultMusicUserId);
        }

        for (CbsMusicSheetApplicationExtendWrapper.MusicSheetApplicationExtend extend : addMusicSheet) {
            //是否合奏曲目
            CbsMusicSheetApiWrapper.MusicSheetUpdate musicSheetUpdate = extend.getMusicSheetUpdate();

            Long finalUserId = userId;
            RLock lock = redissonClient.getLock("musicSheetUpdate:" + musicSheetUpdate.getId());
            try {
                if (lock.tryLock(10, 10, TimeUnit.SECONDS)) {
                    updateMusicDataFormat(musicSheetUpdate, finalUserId);

                    //需要修改的曲目
                    List<MusicSheet> musicSheets = musicSheetService.lambdaQuery()
                        .in(MusicSheet::getCbsMusicSheetId, extend.getMusicSheetId())
                        .list();
                    if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(musicSheets)) {
                        // 判断是改机构数据，还是平台数据
                        if (extend.getApplicationId() != null && cbsTenantAppId.equals(extend.getApplicationId().toString())) {

                            musicSheetService.getDao().updateTenantByCbsId(extend);
                        } else {
                            musicSheetService.getDao().updatePlatformByCbsId(extend);
                        }
                    } else {
                        if (extend.getApplicationId() != null && cbsTenantAppId.equals(extend.getApplicationId().toString())) {

                            musicSheetService.getDao().tenantInsert(extend);
                        } else {
                            musicSheetService.getDao().platformInsert(extend);
                        }
                    }
                } else {
                    throw new BizException("获取锁失败");
                }
            } catch (BizException e) {
                log.error("BizException error lockName : musicSheetUpdate:" + musicSheetUpdate.getId(), e);
                throw e;
            }  catch (Exception e) {
                log.error("saveApplicationExtend error lockName : musicSheetUpdate:" + musicSheetUpdate.getId(), e);
            } finally {
                if (lock.getHoldCount() != 0 && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

        return true;
    }

    public Boolean updateApplicationExtendStatus(CbsMusicSheetApplicationExtendWrapper.MusicSheetApplicationExtendStatus updateMusicSheet){
        if (updateMusicSheet == null || org.apache.commons.lang3.StringUtils.isEmpty(updateMusicSheet.getIds())){
            throw new BizException("请选择曲目");
        }
        if (updateMusicSheet.getStatus() == null){
            throw new BizException("请选择状态");
        }

        String cbsTenantAppId = sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID);
        if (updateMusicSheet.getApplicationId() != null && cbsTenantAppId.equals(updateMusicSheet.getApplicationId().toString())) {
            musicSheetService.getDao().batchEnable(updateMusicSheet.getIds(),updateMusicSheet.getStatus(),true);
        } else {
            musicSheetService.getDao().batchEnable(updateMusicSheet.getIds(),updateMusicSheet.getStatus(),false);
            musicSheetService.getDao().updateState(updateMusicSheet.getIds());
        }
        return true;
    }

    public Boolean delApplicationExtend(CbsMusicSheetApplicationExtendWrapper.MusicSheetApplicationExtendDel musicSheetApplicationExtendDel){
        if (musicSheetApplicationExtendDel == null || StringUtils.isEmpty(musicSheetApplicationExtendDel.getIds())){
            throw new BizException("请选择曲目");
        }

        String cbsTenantAppId = sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID);
        if (musicSheetApplicationExtendDel.getApplicationId() != null && cbsTenantAppId.equals(musicSheetApplicationExtendDel.getApplicationId().toString())) {
            musicSheetService.getDao().batchDel(musicSheetApplicationExtendDel.getIds(),true);
        } else {
            musicSheetService.getDao().batchDel(musicSheetApplicationExtendDel.getIds(),false);
        }
        return true;
    }

    public List<CbsMusicSheetTagWrapper.MusicSheetTag> tagList(CbsMusicSheetTagWrapper.MusicSheetTagQuery queryInfo){
        return musicTagService.getBaseMapper().tagList(queryInfo);
    }

    public List<CbsMusicSheetCategoryWrapper.MusicSheetCategory> categoryList(CbsMusicSheetCategoryWrapper.MusicSheetCategoryQuery queryInfo){
        return musicTagService.getBaseMapper().categoryList(queryInfo);
    }

    public PageInfo<CbsMusicSheetExtendWrapper.MusicSheetExtend> ownerList(CbsMusicSheetExtendWrapper.MusicSheetExtendQuery queryInfo){
        IPage<CbsMusicSheetExtendWrapper.MusicSheetExtend> page = QueryInfo.getPage(queryInfo);
        if (queryInfo.getSourceType() == null || queryInfo.getSourceType() == EMusicSourceType.PERSON){
            return QueryInfo.pageInfo(musicSheetService.getDao().personOwnerList(page, queryInfo));
        }else {
            return QueryInfo.pageInfo(musicSheetService.getDao().orgOwnerList(page, queryInfo));
        }
    }

    public boolean updateMusicSheet(CbsMusicSheetApiWrapper.MusicSheetUpdate musicSheetUpdate) {
        // 如果所属人存在，判断是否是当前应用的曲目 不是，设置默认所属用户
        String configValue = sysConfigService.findConfigValue(SysConfigConstant.DEFAULT_MUSIC_USER_ID);
        Long userId = 3L;
        if (StringUtils.isNotBlank(configValue)) {
            userId = Long.parseLong(configValue);
        }
        updateMusicDataFormat(musicSheetUpdate, userId);
        musicSheetService.getDao().updateMusicSheet(musicSheetUpdate);
        return true;
    }

    private void updateMusicDataFormat(CbsMusicSheetApiWrapper.MusicSheetUpdate musicSheetUpdate,Long userId) {
        if(StringUtils.isNotBlank(musicSheetUpdate.getSubjectIds())) {
            List<Subject> subjectIds = subjectService.getDao().getByCbsSubjectIds(musicSheetUpdate.getSubjectIds());
            if (CollectionUtils.isNotEmpty(subjectIds)) {
                musicSheetUpdate.setSubjectIds(subjectIds.stream().map(e -> e.getId().toString()).collect(Collectors.joining(",")));
            }
        }

        if (musicSheetUpdate.getUserId() != null && musicSheetUpdate.getUserApplicationId() != null) {
            if (musicSheetUpdate.getUserApplicationId().equals(Long.parseLong(openFeignClientConfigProperties.getAppId()))) {
                musicSheetUpdate.setUserId(musicSheetUpdate.getUserId());
            } else {
                musicSheetUpdate.setUserId(userId);
            }
        } else {
            musicSheetUpdate.setUserId(userId);
        }
    }
}