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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.dao.KylinArtistDao;
import com.liquidnet.service.kylin.dto.param.ArtistParam;
import com.liquidnet.service.kylin.dto.param.ArtistSearchParam;
import com.liquidnet.service.kylin.dto.vo.ArtistVo;
import com.liquidnet.service.kylin.entity.KylinArtist;
import com.liquidnet.service.kylin.entity.KylinArtistAlbum;
import com.liquidnet.service.kylin.mapper.KylinArtistAlbumMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistPerformanceMapper;
import com.liquidnet.service.kylin.service.admin.IKylinArtistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 艺人管理 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2026-02-04
 */
@Slf4j
@Service
public class KylinArtistServiceImpl extends ServiceImpl<KylinArtistMapper, KylinArtist> implements IKylinArtistService {

    @Autowired
    private KylinArtistMapper artistMapper;

    @Autowired
    private KylinArtistAlbumMapper artistAlbumMapper;

    @Autowired
    private KylinArtistPerformanceMapper artistPerformanceMapper;

    /**
     * 创建艺人
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(ArtistParam param) {
        try {
            // 校验艺人名称是否已存在
            KylinArtist existArtist = artistMapper.selectByArtistName(param.getArtistName());
            if (existArtist != null) {
                log.warn("艺人名称已存在: {}", param.getArtistName());
                return false;
            }

            String artistId = IDGenerator.nextSnowId();
            LocalDateTime createdAt = LocalDateTime.now();

            // 保存艺人基本信息
            KylinArtist kylinArtist = param.getFields(artistId, createdAt);
            artistMapper.insert(kylinArtist);

            // 保存相册图片
            if (param.getAlbumImages() != null && !param.getAlbumImages().isEmpty()) {
                saveAlbumImages(artistId, param.getAlbumImages());
            }

            return true;
        } catch (Exception e) {
            log.error("创建艺人失败", e);
            throw new RuntimeException("创建艺人失败", e);
        }
    }

    /**
     * 修改艺人
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ArtistParam param) {
        try {
            String artistId = param.getArtistId();
            
            // 校验艺人名称是否已被其他艺人使用
            KylinArtist existArtist = artistMapper.selectByArtistName(param.getArtistName());
            if (existArtist != null && !existArtist.getArtistId().equals(artistId)) {
                log.warn("艺人名称已被其他艺人使用: {}", param.getArtistName());
                return false;
            }

            LocalDateTime updatedAt = LocalDateTime.now();

            // 更新艺人基本信息
            KylinArtist params = param.getFields(null, null);
            params.setUpdatedAt(updatedAt);
            artistMapper.update(params, new UpdateWrapper<KylinArtist>().eq("artist_id", artistId));

            // 删除旧的相册图片（逻辑删除）
            artistAlbumMapper.deleteByArtistId(artistId);

            // 保存新的相册图片
            if (param.getAlbumImages() != null && !param.getAlbumImages().isEmpty()) {
                saveAlbumImages(artistId, param.getAlbumImages());
            }

            return true;
        } catch (Exception e) {
            log.error("修改艺人失败", e);
            throw new RuntimeException("修改艺人失败", e);
        }
    }

    /**
     * 艺人详情
     */
    public ArtistVo detail(String artistId) {
        KylinArtist data = artistMapper.selectOne(
                new UpdateWrapper<KylinArtist>().eq("artist_id", artistId).eq("status", 1)
        );
        
        ArtistVo artistVo = new ArtistVo();
        if (data != null) {
            BeanUtils.copyProperties(data, artistVo);
            
            // 设置艺人类型名称
            if (data.getArtistType() != null) {
                String typeName = "";
                switch (data.getArtistType()) {
                    case 1: typeName = "音乐人"; break;
                    case 2: typeName = "艺术家"; break;
                    case 3: typeName = "厂牌"; break;
                    case 4: typeName = "品牌方"; break;
                    default: typeName = "未知"; break;
                }
                artistVo.setArtistTypeName(typeName);
            }

            // 查询相册图片
            List<KylinArtistAlbum> albumList = artistAlbumMapper.selectByArtistId(artistId);
            if (albumList != null && !albumList.isEmpty()) {
                List<String> imageUrls = albumList.stream()
                        .map(KylinArtistAlbum::getImageUrl)
                        .collect(Collectors.toList());
                artistVo.setAlbumImages(imageUrls);
            }
            
            // 格式化时间显示
            if (data.getCreatedAt() != null) {
                artistVo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(data.getCreatedAt()));
            }
            if (data.getUpdatedAt() != null) {
                artistVo.setUpdatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(data.getUpdatedAt()));
            }

            // TODO 设置关联演出
            artistVo.setPerformanceVoList(Collections.EMPTY_LIST);

        } else {
            log.error("[detail] query artist is null, artistId: {}", artistId);
            return null;
        }

        return artistVo;
    }

    /**
     * 艺人列表
     */
    public PageInfo<KylinArtistDao> artistList(ArtistSearchParam param) {
        PageInfo<KylinArtistDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            
            Map<String, Object> paramMap = BeanUtil.convertBeanToMap(param);
            log.info("艺人列表查询参数: {}", paramMap);
            
            List<KylinArtistDao> list = artistMapper.searchArtistList(paramMap);
            
            pageInfoTmp = new PageInfo<>(list);
        } catch (Exception e) {
            log.error("获取艺人列表失败", e);
            return new PageInfo<>();
        }
        return pageInfoTmp;
    }

    /**
     * 删除艺人（逻辑删除）
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<String> artistIds) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();

            // 删除艺人基本信息
            KylinArtist kylinArtist = new KylinArtist();
            kylinArtist.setUpdatedAt(updatedAt);
            kylinArtist.setStatus(0);
            
            artistMapper.update(
                    kylinArtist,
                    new UpdateWrapper<KylinArtist>().in("artist_id", artistIds)
            );

            // 删除相册图片
            for (String artistId : artistIds) {
                artistAlbumMapper.deleteByArtistId(artistId);
            }

            return true;
        } catch (Exception e) {
            log.error("删除艺人失败", e);
            throw new RuntimeException("删除艺人失败", e);
        }
    }

    /**
     * 检查艺人名称是否存在
     */
    public Boolean checkArtistNameExists(String artistName, String artistId) {
        KylinArtist existArtist = artistMapper.selectByArtistName(artistName);
        if (existArtist == null) {
            return false;
        }
        // 如果是编辑操作，排除自己
        if (artistId != null && existArtist.getArtistId().equals(artistId)) {
            return false;
        }
        return true;
    }

    /**
     * 保存相册图片
     */
    private void saveAlbumImages(String artistId, List<String> imageUrls) {
        LocalDateTime now = LocalDateTime.now();
        int sort = imageUrls.size();
        
        for (String imageUrl : imageUrls) {
            KylinArtistAlbum album = new KylinArtistAlbum();
            album.setAlbumId(IDGenerator.nextSnowId());
            album.setArtistId(artistId);
            album.setImageUrl(imageUrl);
            album.setSort(sort--);
            album.setStatus(1);
            album.setCreatedAt(now);
            album.setUpdatedAt(now);
            
            artistAlbumMapper.insert(album);
        }
    }
}
