package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.service.kylin.dao.KylinArtistAssociationStatusDto;
import com.liquidnet.service.kylin.dao.KylinArtistPerformanceDao;
import com.liquidnet.service.kylin.entity.KylinArtist;
import com.liquidnet.service.kylin.entity.KylinArtistPerformance;
import com.liquidnet.service.kylin.mapper.KylinArtistMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistPerformanceMapper;
import com.liquidnet.service.kylin.service.admin.IKylinArtistPerformanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class KylinArtistPerformanceServiceImpl extends ServiceImpl<KylinArtistPerformanceMapper, KylinArtistPerformance> implements IKylinArtistPerformanceService {

    @Autowired
    private KylinArtistPerformanceMapper artistPerformanceMapper;

    @Autowired
    private KylinArtistMapper artistMapper;

    @Autowired
    private DataUtils dataUtils;

    @Override
    public List<KylinArtistPerformanceDao> getSessionArtists(String performancesId, String timesId) {
        // 查询该场次的艺人
        return artistPerformanceMapper.selectArtistsByPerformanceAndTimes(
                performancesId, timesId
        );
    }

    @Override
    public boolean updateArtistOrder(String performanceId, List<Map<String, Object>> orderData) {
        // 更新每个艺人的排序
        for (Map<String, Object> item : orderData) {
            Long mid = Long.valueOf(item.get("mid").toString());
            Integer sort = Integer.valueOf(item.get("sort").toString());
            log.info("[updateArtistOrder] mid: {}, sort: {}", mid, sort);
            KylinArtistPerformance entity = artistPerformanceMapper.selectById(mid);
            if (entity != null) {
                entity.setSort(sort);
                artistPerformanceMapper.updateById(entity);
            }
        }
        // 删除缓存演出阵容
        dataUtils.delPerformanceArtists(performanceId);
        return true;
    }

    @Override
    public int deletePerformanceArtist(Long mid, String performanceId) {
        // 删除缓存演出阵容
        dataUtils.delPerformanceArtists(performanceId);
        return artistPerformanceMapper.deleteById(mid);
    }

    @Override
    public List<KylinArtistAssociationStatusDto> getAllArtists(String performancesId, String timesId, String keyword) {
        // 1. 获取所有艺人
        List<KylinArtist> allArtists = artistMapper.selectList(new QueryWrapper<KylinArtist>()
                .like(keyword != null && !keyword.isEmpty(), "artist_name", keyword)
                .orderByDesc("created_at"));

        // 2. 获取当前场次已关联的艺人，用 Map 保留各自的 sort 值
        List<KylinArtistPerformanceDao> associatedArtists =
                artistPerformanceMapper.selectArtistsByPerformanceAndTimes(performancesId, timesId);
        // key: artistId  value: 演出关联表中的 sort（越大越靠前）
        Map<String, Integer> associatedSortMap = associatedArtists.stream()
                .collect(Collectors.toMap(
                        KylinArtistPerformanceDao::getArtistId,
                        KylinArtistPerformanceDao::getSort,
                        (existing, replacement) -> existing   // 重复 key 保留已有值
                ));

        // 3. 组装返回结果
        List<KylinArtistAssociationStatusDto> resultList = allArtists.stream().map(artist -> {
            KylinArtistAssociationStatusDto dto = new KylinArtistAssociationStatusDto();
            dto.setArtistId(artist.getArtistId());
            dto.setArtistName(artist.getArtistName());
            dto.setAvatarUrl(artist.getAvatarUrl());
            boolean associated = associatedSortMap.containsKey(artist.getArtistId());
            dto.setAssociated(associated);
            // sort 取演出关联表的值；未关联的艺人 sort 置 0
            dto.setSort(associated ? associatedSortMap.get(artist.getArtistId()) : 0);
            return dto;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public boolean updateArtistAssociations(String performancesId, String timesId, List<Map<String, Object>> artistOrders) {
        // 1. 删除当前场次所有已关联的艺人
        artistPerformanceMapper.delete(new QueryWrapper<KylinArtistPerformance>()
                .eq("performances_id", performancesId)
                .eq("times_id", timesId));

        // 2. 按前端传入的顺序重新关联，sort 越大越靠前
        if (artistOrders != null && !artistOrders.isEmpty()) {
            for (Map<String, Object> item : artistOrders) {
                String artistId = (String) item.get("artistId");
                Integer sort = item.get("sort") != null
                        ? Integer.parseInt(item.get("sort").toString()) : 0;

                KylinArtistPerformance newAssociation = new KylinArtistPerformance();
                newAssociation.setPerformancesId(performancesId);
                newAssociation.setTimesId(timesId);
                newAssociation.setArtistId(artistId);
                newAssociation.setSort(sort);
                artistPerformanceMapper.insert(newAssociation);
            }
        }
        // 删除缓存演出阵容
        dataUtils.delPerformanceArtists(performancesId);
        return true;
    }
}
