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.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.stream.Collectors;
import com.liquidnet.service.kylin.service.admin.IKylinArtistOperationLogService;


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

    @Autowired
    private KylinArtistPerformanceMapper artistPerformanceMapper;

    @Autowired
    private KylinArtistMapper artistMapper;

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private IKylinArtistOperationLogService operationLogService;

    @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) {
        KylinArtistPerformance association = artistPerformanceMapper.selectById(mid);
        if (association == null) {
            return 0;
        }
        String artistId = association.getArtistId();

        // 记录删除前的关联数量
        Integer beforeCount = artistPerformanceMapper.selectCount(new QueryWrapper<KylinArtistPerformance>().eq("artist_id", artistId));
        beforeCount = beforeCount == null ? 0 : beforeCount;

        // 删除缓存演出阵容
        dataUtils.delPerformanceArtists(performanceId);
        int result = artistPerformanceMapper.deleteById(mid);

        // 记录删除后的关联数量
        Integer afterCount = artistPerformanceMapper.selectCount(new QueryWrapper<KylinArtistPerformance>().eq("artist_id", artistId));
        afterCount = afterCount == null ? 0 : afterCount;

        if (!beforeCount.equals(afterCount)) {
            String logContent = String.format("更新关联演出数量:从[%d]场改为[%d]场,", beforeCount, afterCount);
            operationLogService.recordLog(artistId, 2, logContent);
        }

        return result;
    }

    @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) {
        // 先查询该演出、场次下关联的旧艺人
        List<KylinArtistPerformance> oldAssociations = artistPerformanceMapper.selectList(new QueryWrapper<KylinArtistPerformance>()
                .eq("performances_id", performancesId)
                .eq("times_id", timesId));

        Set<String> affectedArtistIds = new HashSet<>(); // 旧关联的艺人ID set
        if (oldAssociations != null) {
            for (KylinArtistPerformance a : oldAssociations) {
                affectedArtistIds.add(a.getArtistId());
            }
        }
        
        if (artistOrders != null && !artistOrders.isEmpty()) {
            for (Map<String, Object> item : artistOrders) {
                String artistId = (String) item.get("artistId");
                if (artistId != null) {
                    affectedArtistIds.add(artistId);
                }
            }
        }

        // Record before counts
        Map<String, Integer> beforeCounts = new HashMap<>();
        for (String artistId : affectedArtistIds) {
            Integer count = artistPerformanceMapper.selectCount(new QueryWrapper<KylinArtistPerformance>().eq("artist_id", artistId));
            beforeCounts.put(artistId, count == null ? 0 : count);
        }

        // 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);
            }
        }

        // 3. Compare and log
        for (String artistId : affectedArtistIds) {
            Integer afterCount = artistPerformanceMapper.selectCount(new QueryWrapper<KylinArtistPerformance>().eq("artist_id", artistId));
            afterCount = afterCount == null ? 0 : afterCount;
            Integer beforeCount = beforeCounts.get(artistId);
            if (!beforeCount.equals(afterCount)) {
                String logContent = String.format("更新关联演出数量:从[%d]场改为[%d]场,", beforeCount, afterCount);
                operationLogService.recordLog(artistId, 2, logContent);
            }
        }

        // 删除缓存演出阵容
        dataUtils.delPerformanceArtists(performancesId);
        return true;
    }
}
