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.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.AiPaintingTemplate;
import org.dromara.ai.domain.bo.AiPaintingTemplateBo;
import org.dromara.ai.domain.vo.AiPaintingTemplateVo;
import org.dromara.ai.mapper.AiPaintingTemplateMapper;
import org.dromara.ai.service.AiPaintingTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * AI绘画参数模板Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiPaintingTemplateServiceImpl implements AiPaintingTemplateService {

    private final AiPaintingTemplateMapper baseMapper;

    /**
     * 查询AI绘画参数模板
     */
    @Override
    public AiPaintingTemplateVo queryById(Long id) {
        AiPaintingTemplateVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            convertFields(vo);
        }
        return vo;
    }

    /**
     * 查询AI绘画参数模板列表
     */
    @Override
    public TableDataInfo<AiPaintingTemplateVo> queryPageList(AiPaintingTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiPaintingTemplate> lqw = buildQueryWrapper(bo);
        Page<AiPaintingTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(this::convertFields);
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI绘画参数模板列表
     */
    @Override
    public List<AiPaintingTemplateVo> queryList(AiPaintingTemplateBo bo) {
        LambdaQueryWrapper<AiPaintingTemplate> lqw = buildQueryWrapper(bo);
        List<AiPaintingTemplateVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::convertFields);
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiPaintingTemplate> buildQueryWrapper(AiPaintingTemplateBo bo) {
        LambdaQueryWrapper<AiPaintingTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), AiPaintingTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(bo.getUserId() != null, AiPaintingTemplate::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getEngineType()), AiPaintingTemplate::getEngineType, bo.getEngineType());
        lqw.eq(bo.getIsPublic() != null, AiPaintingTemplate::getIsPublic, bo.getIsPublic());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiPaintingTemplate::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiPaintingTemplate::getCreateTime, bo.getCreateTimeEnd());
        // 按排序和创建时间排序
        lqw.orderByAsc(AiPaintingTemplate::getSort);
        lqw.orderByDesc(AiPaintingTemplate::getCreateTime);
        return lqw;
    }

    /**
     * 转换字段（用于显示）
     */
    private void convertFields(AiPaintingTemplateVo vo) {
        // 转换引擎类型
        vo.setEngineTypeStr(convertEngineType(vo.getEngineType()));
        // 转换公开状态
        vo.setIsPublicStr(vo.getIsPublic() != null && vo.getIsPublic() == 1 ? "公开" : "私有");
    }

    /**
     * 转换引擎类型
     */
    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;
        };
    }

    /**
     * 新增AI绘画参数模板
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiPaintingTemplateBo bo) {
        AiPaintingTemplate add = MapstructUtils.convert(bo, AiPaintingTemplate.class);
        // 设置默认值
        if (add.getIsPublic() == null) {
            add.setIsPublic(0); // 默认私有
        }
        if (add.getSort() == null) {
            add.setSort(0);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改AI绘画参数模板
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AiPaintingTemplateBo bo) {
        AiPaintingTemplate update = MapstructUtils.convert(bo, AiPaintingTemplate.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;
    }

    /**
     * 根据引擎类型查询可用的模板列表（公开模板 + 用户私有模板）
     */
    @Override
    public List<AiPaintingTemplateVo> queryAvailableTemplates(String engineType, Long userId) {
        LambdaQueryWrapper<AiPaintingTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingTemplate::getEngineType, engineType);
        // 查询公开模板或用户私有模板
        if (userId != null) {
            lqw.and(wrapper -> wrapper
                    .eq(AiPaintingTemplate::getIsPublic, 1)  // 公开模板
                    .or(w -> w.eq(AiPaintingTemplate::getUserId, userId).eq(AiPaintingTemplate::getIsPublic, 0))  // 用户私有模板
            );
        } else {
            // 未登录用户只能看到公开模板
            lqw.eq(AiPaintingTemplate::getIsPublic, 1);
        }
        // 按排序和创建时间排序
        lqw.orderByAsc(AiPaintingTemplate::getSort);
        lqw.orderByDesc(AiPaintingTemplate::getCreateTime);
        List<AiPaintingTemplateVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::convertFields);
        return list;
    }

}