package org.dromara.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.ai.domain.AiPaintingRecord;
import org.dromara.ai.domain.bo.AiPaintingRecordBo;
import org.dromara.ai.domain.vo.AiPaintingRecordVo;
import org.dromara.ai.mapper.AiPaintingRecordMapper;
import org.dromara.ai.service.AiPaintingRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * AI绘画历史记录Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiPaintingRecordServiceImpl implements AiPaintingRecordService {

    private final AiPaintingRecordMapper baseMapper;

    /**
     * 查询AI绘画历史记录
     */
    @Override
    public AiPaintingRecordVo queryById(Long id) {
        AiPaintingRecordVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            convertFields(vo);
        }
        return vo;
    }

    /**
     * 查询AI绘画历史记录列表
     */
    @Override
    public TableDataInfo<AiPaintingRecordVo> queryPageList(AiPaintingRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiPaintingRecord> lqw = buildQueryWrapper(bo);
        Page<AiPaintingRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(this::convertFields);
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI绘画历史记录列表
     */
    @Override
    public List<AiPaintingRecordVo> queryList(AiPaintingRecordBo bo) {
        LambdaQueryWrapper<AiPaintingRecord> lqw = buildQueryWrapper(bo);
        List<AiPaintingRecordVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::convertFields);
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiPaintingRecord> buildQueryWrapper(AiPaintingRecordBo bo) {
        LambdaQueryWrapper<AiPaintingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getTaskId()), AiPaintingRecord::getTaskId, bo.getTaskId());
        lqw.eq(bo.getUserId() != null, AiPaintingRecord::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getEngineType()), AiPaintingRecord::getEngineType, bo.getEngineType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AiPaintingRecord::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getPrompt()), AiPaintingRecord::getPrompt, bo.getPrompt());
        lqw.eq(StringUtils.isNotBlank(bo.getShareCode()), AiPaintingRecord::getShareCode, bo.getShareCode());
        lqw.eq(bo.getIsPublic() != null, AiPaintingRecord::getIsPublic, bo.getIsPublic());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiPaintingRecord::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiPaintingRecord::getCreateTime, bo.getCreateTimeEnd());
        // 按创建时间倒序排序
        lqw.orderByDesc(AiPaintingRecord::getCreateTime);
        return lqw;
    }

    /**
     * 转换字段（用于显示）
     */
    private void convertFields(AiPaintingRecordVo vo) {
        // 转换引擎类型
        vo.setEngineTypeStr(convertEngineType(vo.getEngineType()));
        // 转换状态
        vo.setStatusStr(convertStatus(vo.getStatus()));
        // 转换是否公开
        vo.setIsPublicStr(convertIsPublic(vo.getIsPublic()));
    }

    /**
     * 转换引擎类型
     */
    private String convertEngineType(String engineType) {
        if (StringUtils.isBlank(engineType)) {
            return "";
        }
        return switch (engineType) {
            case "DALL_E_3" -> "DALL·E 3";
            case "MIDJOURNEY" -> "MidJourney";
            case "STABLE_DIFFUSION" -> "Stable Diffusion";
            default -> engineType;
        };
    }

    /**
     * 转换状态
     */
    private String convertStatus(String status) {
        if (StringUtils.isBlank(status)) {
            return "";
        }
        return switch (status) {
            case "PENDING" -> "待处理";
            case "RUNNING" -> "处理中";
            case "SUCCESS" -> "成功";
            case "FAILED" -> "失败";
            default -> status;
        };
    }

    /**
     * 转换是否公开
     */
    private String convertIsPublic(Integer isPublic) {
        if (isPublic == null) {
            return "私有";
        }
        return isPublic == 1 ? "公开" : "私有";
    }

    /**
     * 新增AI绘画历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiPaintingRecordBo bo) {
        AiPaintingRecord add = MapstructUtils.convert(bo, AiPaintingRecord.class);
        // 设置默认值
        if (add.getProgress() == null) {
            add.setProgress(0);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改AI绘画历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AiPaintingRecordBo bo) {
        AiPaintingRecord update = MapstructUtils.convert(bo, AiPaintingRecord.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除AI绘画历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据任务ID查询记录
     */
    @Override
    public AiPaintingRecordVo queryByTaskId(String taskId) {
        LambdaQueryWrapper<AiPaintingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingRecord::getTaskId, taskId);
        AiPaintingRecord record = baseMapper.selectOne(lqw);
        if (record != null) {
            AiPaintingRecordVo vo = MapstructUtils.convert(record, AiPaintingRecordVo.class);
            convertFields(vo);
            return vo;
        }
        return null;
    }

    /**
     * 根据任务ID更新记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByTaskId(AiPaintingRecordBo bo) {
        LambdaQueryWrapper<AiPaintingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingRecord::getTaskId, bo.getTaskId());
        AiPaintingRecord record = baseMapper.selectOne(lqw);
        if (record == null) {
            // 如果记录不存在，则插入
            return insertByBo(bo);
        } else {
            // 如果记录存在，则更新
            bo.setId(record.getId());
            return updateByBo(bo);
        }
    }

    /**
     * 生成分享码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String generateShareCode(Long id) {
        AiPaintingRecord record = baseMapper.selectById(id);
        if (record == null) {
            throw new ServiceException("绘画记录不存在");
        }
        // 生成唯一分享码（使用UUID，去除横线）
        String shareCode = UUID.randomUUID().toString().replace("-", "");
        record.setShareCode(shareCode);
        record.setIsPublic(1); // 设置为公开分享
        baseMapper.updateById(record);
        return shareCode;
    }

    /**
     * 取消分享
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelShare(Long id) {
        AiPaintingRecord record = baseMapper.selectById(id);
        if (record == null) {
            throw new ServiceException("绘画记录不存在");
        }
        record.setShareCode(null);
        record.setIsPublic(0); // 设置为私有
        return baseMapper.updateById(record) > 0;
    }

    /**
     * 根据分享码查询记录
     */
    @Override
    public AiPaintingRecordVo queryByShareCode(String shareCode) {
        if (StringUtils.isBlank(shareCode)) {
            return null;
        }
        LambdaQueryWrapper<AiPaintingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingRecord::getShareCode, shareCode);
        lqw.eq(AiPaintingRecord::getIsPublic, 1); // 只查询公开分享的记录
        AiPaintingRecord record = baseMapper.selectOne(lqw);
        if (record != null) {
            AiPaintingRecordVo vo = MapstructUtils.convert(record, AiPaintingRecordVo.class);
            convertFields(vo);
            return vo;
        }
        return null;
    }

}