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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.UserOrderDao;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.InOrOutEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.OrderStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.OrderTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.TenantAlbumMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantGroupAlbumMapper;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.UserOrderDetailVo;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.UserPaymentOrderWrapper;
import com.yonge.cooleshow.common.enums.EActivationCode;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 机构专辑
 * 2023-07-21 17:32:49
 */
@Slf4j
@Service
public class TenantAlbumServiceImpl extends ServiceImpl<TenantAlbumMapper, TenantAlbum> implements TenantAlbumService {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TenantStaffService tenantStaffService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private TenantAlbumRefService tenantAlbumRefService;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private TenantAlbumPurchaseService tenantAlbumPurchaseService;

    @Autowired
    private TenantAlbumMusicService tenantAlbumMusicService;

    @Autowired
    private TenantActivationCodeService tenantActivationCodeService;

    @Autowired
    private RedisCacheService redisCacheService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private TenantAccountRecordService tenantAccountRecordService;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TenantAlbumService tenantAlbumService;

    @Autowired
    private UserTenantAlbumRecordService userTenantAlbumRecordService;

    @Autowired
    private TenantGroupAlbumService tenantGroupAlbumService;

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private TenantGroupAlbumMapper tenantGroupAlbumMapper;

    /**
     * 查询详情
     *
     * @param id 详情ID
     * @return TenantAlbum
     */
    @Override
    public TenantAlbum detail(Long id) {

        return baseMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param page  IPage<TenantAlbum>
     * @param query TenantAlbumWrapper.TenantAlbumQuery
     * @return IPage<TenantAlbum>
     */
    @Override
    public IPage<TenantAlbumWrapper.TenantAlbum> selectPage(IPage<TenantAlbumWrapper.TenantAlbum> page,
                                                            TenantAlbumWrapper.TenantAlbumQuery query) {
        //查询机构专辑表数据
        List<TenantAlbumWrapper.TenantAlbum> tenantAlbums = baseMapper.selectPage(page, query);

        if (CollectionUtils.isNotEmpty(tenantAlbums)){
            tenantAlbums.stream().forEach(t->{
                if (t.getMusicNum() == null){
                    //获取每一个机构专辑Id
                    String id = t.getId();
                    //查询机构专辑曲目表里  所对应的曲目数
                    List<TenantAlbumMusic> list = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantAlbumId, id).eq(TenantAlbumMusic::getDelFlag,false).list();
                    //获取曲目数量
                    List<Long> MusicList = list.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());
                    int num = MusicList.size();
                    t.setMusicNum(num);
                }
            });

        }


        return page.setRecords(tenantAlbums);
    }

    /**
     * 添加
     *
     * @param tenantAlbum TenantAlbumWrapper.TenantAlbum
     * @return Boolean
     */
    @Override
    public Boolean add(TenantAlbum tenantAlbum) {

        //return this.save(JSON.parseObject(tenantAlbum.jsonString(), TenantAlbum.class));
        return this.save(tenantAlbum);
    }

    /**
     * 更新
     *
     * @param tenantAlbum TenantAlbumWrapper.TenantAlbum
     * @return Boolean
     */
    @Override
    public Boolean update(TenantAlbumWrapper.TenantAlbum tenantAlbum) {

        return this.updateById(JSON.parseObject(tenantAlbum.jsonString(), TenantAlbum.class));
    }

    /**
     * 订单创建前检测
     *
     * @param orderGoodsInfo
     */
    @Override
    public void orderCreate(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {
        log.info("订单创建前检测");

        //检查曲目数量
        //机构专辑曲目数
        List<TenantAlbumMusic> tenantAlbumMusiclist = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantAlbumId, orderGoodsInfo.getBizId())
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> musicSheetIds = tenantAlbumMusiclist.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(musicSheetIds)){
            Integer count = musicSheetService.lambdaQuery().in(MusicSheet::getId, musicSheetIds)
                    .eq(MusicSheet::getState, true)
                    .eq(MusicSheet::getDelFlag, false).count();
            if(count < 1){
                throw new BizException("当前教程不可购买");
            }
        }else {
            throw new BizException("当前教程不可购买");
        }
        if (orderGoodsInfo == null) {
            log.error("订单创建前检测，订单商品信息为空");
            throw new BizException("订单商品信息为空");
        }


        TenantAlbumWrapper.TenantAlbumContent tenantAlbumContent = JSON
                .parseObject(JSON.toJSONString(orderGoodsInfo.getBizContent()), TenantAlbumWrapper.TenantAlbumContent.class);
        if (tenantAlbumContent == null) {
            log.error("订单创建前检测，订单商品信息为空");
            throw new BizException("订单商品信息为空");
        }


        // 专辑是否存在
        TenantAlbum tenantAlbum = this.getById(orderGoodsInfo.getBizId());
        if (tenantAlbum == null || tenantAlbum.getDelFlag() || Boolean.FALSE.equals(tenantAlbum.getStatus())) {
            log.error("订单创建前检测，专辑不存在，bizId={}", orderGoodsInfo.getBizId());
            throw new BizException("订单商品信息为空");
        }
//        tenantAlbumContent.setBuyCycle(tenantAlbum.getPurchaseCycle());
//        tenantAlbumContent.setSalePrice(tenantAlbum.getSalePrice());
//        tenantAlbumContent.setOriginalPrice(tenantAlbum.getOriginalPrice());

        // 查询专辑所在机构
        List<TenantAlbumRef> refList =
                tenantAlbumRefService.getByAlbumId(tenantAlbum.getId());
        if (CollectionUtils.isEmpty(refList)) {
            log.error("订单创建前检测，专辑不在机构下，bizId={}", orderGoodsInfo.getBizId());
            throw new BizException("该专辑已不可购买");
        }

        // 机构ID集合
        List<Long> tenantIdList =
                refList.stream().map(TenantAlbumRef::getTenantId).collect(Collectors.toList());

        UserOrderDetail userOrderDetail = JSON.parseObject(JSON.toJSONString(orderGoodsInfo), UserOrderDetail.class);


        // 设置金额入账去向
        UserPaymentOrderWrapper.AccountTenantTo accountTenantTo = teacherService.teacherSettlementFrom(null, orderGoodsInfo.getRecomUserId());
        BigDecimal originalPrice = BigDecimal.ZERO;
        BigDecimal actualPrice = BigDecimal.ZERO;
        // 学生购买机构专辑
        switch (orderGoodsInfo.getPaymentClient()) {
            case STUDENT: {
                // 判断学生是否在当前专辑机构下
                Student student = studentService.getById(orderGoodsInfo.getUserId());
                if (student == null) {
                    log.error("订单创建前检测，学生不存在，userId={}", orderGoodsInfo.getUserId());
                    throw new BizException("该专辑已不可购买");
                }
                TenantInfo tenantInfo = tenantInfoService.detail(student.getTenantId());
                if (tenantInfo == null || !tenantIdList.contains(tenantInfo.getId())) {
                    log.error("订单创建前检测，学生不在当前机构下，userId={},tenantId={}", orderGoodsInfo.getUserId(), student.getTenantId());
                    throw new BizException("该专辑已不可购买");
                }
                if (orderGoodsInfo.getTenantGroupAlbumId() == null) {
                    log.error("订单创建前检测，学生购买机构专辑，机构小组专辑ID为空，userId={}", orderGoodsInfo.getUserId());
                    throw new BizException("该专辑已不可购买");
                }
                // 判断机构小组专辑ID是否能购买，专辑ID和当前机构专辑ID是否对应
                TenantGroupAlbum tenantGroupAlbum = tenantGroupAlbumService.getById(orderGoodsInfo.getTenantGroupAlbumId());
                if (tenantGroupAlbum == null || tenantGroupAlbum.getDelFlag() || !tenantGroupAlbum.getStatus()) {
                    log.error("订单创建前检测，学生购买机构专辑，机构小组专辑不存在，userId={},tenantGroupAlbumId={}", orderGoodsInfo.getUserId(), orderGoodsInfo.getTenantGroupAlbumId());
                    throw new BizException("该专辑已不可购买");
                }

                // 判断学生是否在小组
                if (orderGoodsInfo.getTenantGroupAlbumId().equals(student.getTenantGroupId())) {
                    log.error("订单创建前检测，学生购买机构专辑，学生不在小组，userId={},tenantGroupAlbumId={}", orderGoodsInfo.getUserId(), orderGoodsInfo.getTenantGroupAlbumId());
                    throw new BizException("该专辑已不可购买");
                }
                if (!tenantGroupAlbum.getTenantAlbumId().equals(orderGoodsInfo.getBizId())) {
                    log.error("订单创建前检测，学生购买机构专辑，机构小组专辑ID和当前机构专辑ID不对应，userId={},tenantGroupAlbumId={},bizId={}", orderGoodsInfo.getUserId(), orderGoodsInfo.getTenantGroupAlbumId(), orderGoodsInfo.getBizId());
                    throw new BizException("该专辑已不可购买");
                }
                // 判断购买次数
                if (tenantGroupAlbum.getBuyTimesFlag()) {
                    List<Long> studentTenantAlbumNum = userOrderDao.getStudentTenantAlbumNum(student.getUserId(), Lists.newArrayList(tenantGroupAlbum.getId()));
                    if (CollectionUtils.isNotEmpty(studentTenantAlbumNum) && studentTenantAlbumNum.size() >= tenantGroupAlbum.getBuyTimes()) {
                        log.error("订单创建前检测，学生购买机构专辑，机构小组专辑购买次数超过限制，userId={},tenantGroupAlbumId={},buyTimes={}", orderGoodsInfo.getUserId(), orderGoodsInfo.getTenantGroupAlbumId(), tenantGroupAlbum.getBuyTimes());
                        throw new BizException("该专辑已不可购买");
                    }
                }

                originalPrice = tenantGroupAlbum.getOriginalPrice();
                actualPrice = tenantGroupAlbum.getActualPrice();
                userOrderDetail.setMerchId(tenantInfo.getId());
                userOrderDetail.setTenantGroupAlbumId(tenantGroupAlbum.getId());
                tenantAlbumContent.setBuyNumber(1);
                tenantAlbumContent.setBuyCycle(tenantGroupAlbum.getPurchaseNum());
                tenantAlbumContent.setPurchaseType(tenantGroupAlbum.getPurchasePeriod());
                tenantAlbumContent.setTenantId(tenantInfo.getId());
                accountTenantTo.setIncomeTenant(tenantInfo.getId());
                break;
            }

            case TENANT: {
                // 专辑是否在机构下
                TenantStaff tenantStaff = tenantStaffService.getByUserId(orderGoodsInfo.getUserId());
                if (tenantStaff == null) {
                    log.error("订单创建前检测，机构员工不存在，userId={}", orderGoodsInfo.getUserId());
                    throw new BizException("用户信息未找到");
                }
                if (!tenantIdList.contains(tenantStaff.getTenantId())) {
                    log.error("订单创建前检测，专辑不在机构下，userId={},tenantId={}", orderGoodsInfo.getUserId(), tenantStaff.getTenantId());
                    throw new BizException("该专辑已不可购买");
                }
                // 根据周期判断能不能购买当前周期的专辑
                if (StringUtil.isEmpty(tenantAlbum.getPurchaseTypes())) {
                    log.error("订单创建前检测，机构购买机构专辑，专辑周期为空，userId={},bizId={}", orderGoodsInfo.getUserId(), orderGoodsInfo.getBizId());
                    throw new BizException("该专辑已不可购买");
                }
                List<String> purchaseTypes = Arrays.asList(tenantAlbum.getPurchaseTypes().split(","));
                if (!purchaseTypes.contains(tenantAlbumContent.getPurchaseType())) {
                    log.error("订单创建前检测，机构购买机构专辑，专辑周期不支持，userId={},bizId={},purchaseType={}", orderGoodsInfo.getUserId(),
                        orderGoodsInfo.getBizId(), tenantAlbumContent.getPurchaseType());
                    throw new BizException("该专辑已不可购买");
                }
                List<TenantAlbumWrapper.TenantAlbumPurchaseJson> tenantAlbumPurchaseJsons = JSON
                    .parseArray(tenantAlbum.getPurchaseJson(), TenantAlbumWrapper.TenantAlbumPurchaseJson.class);
                if (CollectionUtils.isEmpty(tenantAlbumPurchaseJsons)) {
                    log.error("订单创建前检测，机构购买机构专辑，专辑周期不支持，userId={},bizId={},purchaseType={}", orderGoodsInfo.getUserId(),
                        orderGoodsInfo.getBizId(), tenantAlbumContent.getPurchaseType());
                    throw new BizException("该专辑已不可购买");
                }
                Optional<TenantAlbumWrapper.TenantAlbumPurchaseJson> first = tenantAlbumPurchaseJsons.stream().filter(o -> o.getType().equals(tenantAlbumContent.getPurchaseType())).findFirst();
                if (!first.isPresent()) {
                    log.error("订单创建前检测，机构购买机构专辑，专辑周期不支持，userId={},bizId={},purchaseType={}", orderGoodsInfo.getUserId(),
                        orderGoodsInfo.getBizId(), tenantAlbumContent.getPurchaseType());
                    throw new BizException("该专辑已不可购买");
                }
                TenantAlbumWrapper.TenantAlbumPurchaseJson tenantAlbumPurchaseJson = first.get();

                originalPrice = tenantAlbumPurchaseJson.getPrice();
                actualPrice = tenantAlbumPurchaseJson.getPrice();
                userOrderDetail.setMerchId(0L);
                tenantAlbumContent.setTenantId(tenantStaff.getTenantId());
                tenantAlbumContent.setBuyCycle(tenantAlbumContent.getBuyMultiple());
                break;
            }
        }



        userOrderDetail.setGoodUrl(userOrderService.getGoodUrlByType(orderGoodsInfo.getGoodType()));
        userOrderDetail.setBizId(tenantAlbum.getId());
        userOrderDetail.setBizContent(JSON.toJSONString(tenantAlbumContent));
        userOrderDetail.setGoodNum(orderGoodsInfo.getGoodNum());
        userOrderDetail.setOriginalPrice(originalPrice.multiply(new BigDecimal(orderGoodsInfo.getGoodNum()))
                .multiply(new BigDecimal(tenantAlbumContent.getBuyMultiple())));
        userOrderDetail.setCouponAmount(BigDecimal.ZERO);
        userOrderDetail.setExpectPrice(actualPrice.multiply(new BigDecimal(orderGoodsInfo.getGoodNum()))
            .multiply(new BigDecimal(tenantAlbumContent.getBuyMultiple())));
        userOrderDetail.setActualPrice(userOrderDetail.getExpectPrice());
        userOrderDetail.setAccountConfig(accountTenantTo.jsonString());

        orderGoodsInfo.setUserOrderDetail(userOrderDetail);

        userOrderDetail.setAccountConfig(accountTenantTo.jsonString());
        // 存入缓存
//        redisCacheService.saveUserAccountConfig(orderGoodsInfo.getSubOrderNo(), accountTenantTo.jsonString());

    }

    /**
     * 订单完成后
     *
     * @param userOrderDetailVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderSuccess(UserOrderDetailVo userOrderDetailVo) {

        // 学生 插入机构专辑购买数据
        // 学生购买机构专辑
        switch (userOrderDetailVo.getOrderClient()) {
            case STUDENT: {
                tenantActivationCodeService.addUserTenantAlbumRecord(userOrderDetailVo.getUserId(),userOrderDetailVo);

                sendMsg(userOrderDetailVo);
                break;
            }

            case TENANT: {
                // 机构   插入机构专辑购买记录，生成机构专辑激活码

                TenantAlbumWrapper.TenantAlbumContent tenantAlbumContent = JSON
                        .parseObject(userOrderDetailVo.getBizContent(), TenantAlbumWrapper.TenantAlbumContent.class);
                TenantAlbumPurchase tenantAlbumPurchase =  tenantAlbumPurchaseService.getByOrderNo(userOrderDetailVo.getOrderNo());
                tenantAlbumPurchase.setTenantId(tenantAlbumContent.getTenantId());
                tenantAlbumPurchase.setTenantAlbumId(userOrderDetailVo.getBizId());
                tenantAlbumPurchase.setPurchaseTime(userOrderDetailVo.getCreateTime());
                tenantAlbumPurchase.setPurchaseQuantity(userOrderDetailVo.getGoodNum());
                tenantAlbumPurchase.setPurchaseCycle(tenantAlbumContent.getBuyCycle());
                tenantAlbumPurchase.setActiveQuantity(0);
                tenantAlbumPurchase.setOrderNo(userOrderDetailVo.getOrderNo());
                tenantAlbumPurchase.setPurchasePrice(userOrderDetailVo.getActualPrice());
                tenantAlbumPurchase.setPurchaseStatus(OrderStatusEnum.PAID.getCode());
                tenantAlbumPurchaseService.updateById(tenantAlbumPurchase);

                List<TenantActivationCode> tenantActivationCodes = new ArrayList<>();
                for (int i = 0; i < userOrderDetailVo.getGoodNum(); i++) {
                    TenantActivationCode tenantActivationCode = new TenantActivationCode();
                    tenantActivationCode.setTenantId(tenantAlbumContent.getTenantId());
                    tenantActivationCode.setTenantAlbumId(tenantAlbumContent.getTenantAlbumId());
                    tenantActivationCode.setTenantAlbumPurchaseId(tenantAlbumPurchase.getId());
                    String s = String.valueOf(tenantAlbumPurchase.getId());
                    long l = Long.parseLong(new Date().getTime() + i + s.substring(s.length()-6));
                    tenantActivationCode.setActivationCode(StringUtil.DeciamlToThirtySix(l,7));
//                    tenantActivationCode.setActivationCode(IdWorker.get32UUID());
                    tenantActivationCode.setSendStatus(EActivationCode.WAIT);
                    tenantActivationCodes.add(tenantActivationCode);
                }
                tenantActivationCodeService.saveBatch(tenantActivationCodes);

                // 写入机构流水表
                TenantAccountRecord tenantAccountRecord = TenantAccountRecord.builder()
                        .tenantId(tenantAlbumPurchase.getTenantId())
                        .transAmount(userOrderDetailVo.getActualPrice())
                        .inOrOut(InOrOutEnum.OUT.getCode())
                        .sourceType(SourceTypeEnum.ORDER)
                        .postStatus(PostStatusEnum.RECORDED.getCode())
                        .bizType(OrderTypeEnum.TENANT_ALBUM.getCode())
                        .bizId(userOrderDetailVo.getBizId())
                        .bizName(userOrderDetailVo.getGoodName())
                        .orderNo(userOrderDetailVo.getOrderNo())
                        .build();
                tenantAccountRecordService.save(tenantAccountRecord);
                break;
            }
        }
    }

    private void sendMsg(UserOrderDetailVo userOrderDetailVo) {
        try {
            SysUser user = sysUserFeignService.queryUserById(userOrderDetailVo.getUserId());

            if (user == null) {
                return;
            }
            Long userId = userOrderDetailVo.getUserId();

            // 查询机构专辑信息
            TenantAlbum tenantAlbum = tenantAlbumService.getById(userOrderDetailVo.getBizId());
            if (tenantAlbum == null) {
                return;
            }

            // 查询学生当前机构有效时间
            UserTenantAlbumRecord albumRecord = userTenantAlbumRecordService
                    .getNewestByTenantAlbumId(tenantAlbum.getId(), userId, userOrderDetailVo.getOrderClient());
            if (albumRecord == null) {
                return;
            }
            String dateStr = DateUtil.format(albumRecord.getEndTime(), DateUtil.DEFAULT_PATTERN);


            Map<Long, String> receivers = new HashMap<>();
            receivers.put(userId, user.getPhone());

            if (userOrderDetailVo.getOrderClient().equals(ClientEnum.STUDENT)) {
                Student student = studentService.getById(userId);
                if (student.getTenantId() != null && student.getTenantId() >0) {
                    try {
                        String url = sysMessageService.selectConfigUrlJumpType(MessageTypeEnum.TENANT_ALBUM_BUY.getCode(),ClientEnum.TENANT_STUDENT.getCode(),userOrderDetailVo.getOrderNo());
                        sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TENANT_ALBUM_BUY,
                                receivers, null, 0, url, ClientEnum.TENANT_STUDENT.getCode(),tenantAlbum.getName(),dateStr);
                    } catch (Exception e) {
                        log.error("机构学生购买训练教材", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("机构学生购买训练教材 ： {}",e.getMessage());
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertTenantAlbum(Long tenantId, TenantAlbum tenantAlbum,
                                  List<TenantAlbumWrapper.MusicSheetData> musicSheetDataList) {

        List<String> subjectTypeNames = musicSheetDataList.stream().map(next -> next.getSubjectType().name())
                .distinct().collect(Collectors.toList());
        tenantAlbum.setSubjectTypes(String.join(",", subjectTypeNames));
        //给机构专辑赋值
        tenantAlbum.setStatus(false);
        tenantAlbum.setDelFlag(false);
        this.add(tenantAlbum);

        //关联表赋值
        TenantAlbumRef ref = new TenantAlbumRef();
        ref.setTenantAlbumId(tenantAlbum.getId());
        ref.setTenantId(tenantId);
        tenantAlbumRefService.add(ref);

        //曲目表赋值
        insertAlbumMusic(tenantId, tenantAlbum, musicSheetDataList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAlbum(Long tenantId, TenantAlbum tenantAlbum,
                            List<TenantAlbumWrapper.MusicSheetData> musicSheetDataList) {

        List<String> subjectTypeNames = musicSheetDataList.stream().map(next -> next.getSubjectType().name())
                .distinct().collect(Collectors.toList());
        tenantAlbum.setSubjectTypes(String.join(",", subjectTypeNames));
        this.updateById(tenantAlbum);

        tenantAlbumMusicService.lambdaUpdate()
                .set(TenantAlbumMusic::getDelFlag, true)
                .eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbum.getId())
                .update();

        insertAlbumMusic(tenantId, tenantAlbum, musicSheetDataList);

        // 删除原始关联数据，添加新关联数据
        tenantAlbumRefService.lambdaUpdate()
                .eq(TenantAlbumRef::getTenantAlbumId, tenantAlbum.getId())
                .remove();

        TenantAlbumRef ref = new TenantAlbumRef();
        ref.setTenantAlbumId(tenantAlbum.getId());
        ref.setTenantId(tenantId);
        tenantAlbumRefService.add(ref);
    }

    @Override
    public Map<Long, TenantAlbum> getMapByIds(List<Long> bizIds) {
        if (CollectionUtils.isEmpty(bizIds)) {
            return new HashMap<>();
        }
        List<TenantAlbum> tenantAlbums = this.lambdaQuery()
                .in(TenantAlbum::getId, bizIds)
                .list();
        if (CollectionUtils.isEmpty(tenantAlbums)) {
            return new HashMap<>();
        }
        return tenantAlbums.stream().collect(Collectors.toMap(TenantAlbum::getId, v -> v));

    }

    @Override
    public Map<Long, Long> getMusicCountByIds(List<Long> bizIds) {
        if (CollectionUtils.isEmpty(bizIds)) {
            return new HashMap<>();
        }
        List<TenantAlbumMusic> list = tenantAlbumMusicService.lambdaQuery()
                .in(TenantAlbumMusic::getTenantAlbumId, bizIds)
                .eq(TenantAlbumMusic::getDelFlag,0)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        List<Long> musicIds = list.stream().map(o -> o.getMusicSheetId()).collect(Collectors.toList());
        List<MusicSheet> musicList = musicSheetService.lambdaQuery()
                .eq(MusicSheet::getDelFlag, false)
                .eq(MusicSheet::getState, YesOrNoEnum.YES)
                .eq(MusicSheet::getAuditVersion, YesOrNoEnum.NO)
                .in(MusicSheet::getId, musicIds)
                .list();
        if (CollectionUtils.isEmpty(musicList)) {
            return new HashMap<>();
        }
        // 曲目ID集合
        List<Long> musicSheetIds = musicList.stream().map(o -> o.getId()).collect(Collectors.toList());

        return list.stream().filter(o -> musicSheetIds.contains(o.getMusicSheetId()))
                .collect(Collectors.groupingBy(TenantAlbumMusic::getTenantAlbumId, Collectors.counting()));
    }

    @Override
    public void orderAfterSheet(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {
        // 机构   插入机构专辑购买记录，生成机构专辑激活码

        if (!orderGoodsInfo.getPaymentClient().equals(ClientEnum.TENANT)) {
            return;
        }


        TenantAlbumWrapper.TenantAlbumContent tenantAlbumContent = JSON
                .parseObject(orderGoodsInfo.getUserOrderDetail().getBizContent(), TenantAlbumWrapper.TenantAlbumContent.class);
        TenantAlbumPurchase tenantAlbumPurchase = new TenantAlbumPurchase();
        tenantAlbumPurchase.setTenantId(tenantAlbumContent.getTenantId());
        tenantAlbumPurchase.setTenantAlbumId(orderGoodsInfo.getBizId());
        tenantAlbumPurchase.setPurchaseTime(new Date());
        tenantAlbumPurchase.setPurchaseQuantity(orderGoodsInfo.getUserOrderDetail().getGoodNum());
        tenantAlbumPurchase.setPurchaseCycle(tenantAlbumContent.getBuyCycle());
        tenantAlbumPurchase.setActiveQuantity(0);
        tenantAlbumPurchase.setOrderNo(orderGoodsInfo.getOrderNo());
        tenantAlbumPurchase.setPurchaseType(tenantAlbumContent.getPurchaseType());
        tenantAlbumPurchase.setPurchasePrice(orderGoodsInfo.getUserOrderDetail().getActualPrice());
        tenantAlbumPurchase.setPurchaseStatus(OrderStatusEnum.WAIT_PAY.getCode());
        tenantAlbumPurchaseService.save(tenantAlbumPurchase);
    }

    @Override
    public void buyCancel(UserOrderDetailVo userOrderDetailVo) {

        TenantAlbumPurchase tenantAlbumPurchase =  tenantAlbumPurchaseService.getByOrderNo(userOrderDetailVo.getOrderNo());
        if (tenantAlbumPurchase == null) {
            return;
        }
        tenantAlbumPurchase.setPurchaseStatus(OrderStatusEnum.CLOSE.getCode());
        tenantAlbumPurchase.setUpdateTime(new Date());
        tenantAlbumPurchaseService.updateById(tenantAlbumPurchase);
    }

    @Override
    public List<TenantAlbum> getByTenantId(Long tenantId,Boolean status) {
        if (tenantId == null) {
            return new ArrayList<>();
        }
        List<TenantAlbumRef> list = tenantAlbumRefService.lambdaQuery().eq(TenantAlbumRef::getTenantId, tenantId).list();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        Set<Long> tenantAlbumId = list.stream().map(TenantAlbumRef::getTenantAlbumId).collect(Collectors.toSet());
        return this.lambdaQuery().in(TenantAlbum::getId, tenantAlbumId)
                .eq(status != null, TenantAlbum::getStatus, status)
                .eq(TenantAlbum::getDelFlag,false).list();


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long id, Boolean status) {
        tenantAlbumService.lambdaUpdate()
                .set(TenantAlbum::getStatus, status)
                .eq(TenantAlbum::getId, id)
                .update();

        if (Boolean.FALSE.equals(status)) {
            UpdateWrapper<TenantGroupAlbum> queryWrapper = new UpdateWrapper<>();
            queryWrapper.lambda()
                    .set(TenantGroupAlbum::getStatus, false)
                    .eq(TenantGroupAlbum::getTenantAlbumId, id)
                    .eq(TenantGroupAlbum::getDelFlag, false);
            tenantGroupAlbumMapper.update(null, queryWrapper);
        }
    }

    private void insertAlbumMusic(Long tenantId, TenantAlbum tenantAlbum,
                                  List<TenantAlbumWrapper.MusicSheetData> musicSheetDataList) {
        //曲目表赋值
        List<TenantAlbumMusic> tenantAlbumMusics = musicSheetDataList.stream().map(next -> {

            AtomicInteger sort = new AtomicInteger(1);
            return next.getTenantAlbumSheetList().stream().map(tenantAlbumMusic -> {
                TenantAlbumMusic tenantAlbumMusic1 = new TenantAlbumMusic();
                tenantAlbumMusic1.setTenantId(tenantId);
                tenantAlbumMusic1.setSubjectType(next.getSubjectType());
                tenantAlbumMusic1.setTenantAlbumId(tenantAlbum.getId());
                tenantAlbumMusic1.setMusicSheetId(Long.valueOf(tenantAlbumMusic.getId()));
                tenantAlbumMusic1.setSortNumber(sort.getAndIncrement());
                tenantAlbumMusic1.setDelFlag(false);
                tenantAlbumMusic1.setLevel(tenantAlbumMusic.getLevel());
                tenantAlbumMusic1.setType(tenantAlbumMusic.getType());
                return tenantAlbumMusic1;
            }).collect(Collectors.toList());
        }).flatMap(Collection::stream).collect(Collectors.toList());

        if (!tenantAlbumMusics.isEmpty()) {
            tenantAlbumMusicService.saveBatch(tenantAlbumMusics, 100);
        }
    }

}