package com.nanri.aiimage.modules.convert.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.convert.mapper.ConvertTemplateMapper;
import com.nanri.aiimage.modules.convert.model.dto.ConvertTemplateImportRequest;
import com.nanri.aiimage.modules.convert.model.entity.ConvertTemplateEntity;
import com.nanri.aiimage.modules.convert.model.vo.ConvertTemplateVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ConvertTemplateService {

    private final ConvertTemplateMapper convertTemplateMapper;

    public List<ConvertTemplateVo> listEnabledTemplates() {
        return convertTemplateMapper.selectList(new LambdaQueryWrapper<ConvertTemplateEntity>()
                        .eq(ConvertTemplateEntity::getEnabled, 1)
                        .orderByDesc(ConvertTemplateEntity::getIsDefault)
                        .orderByAsc(ConvertTemplateEntity::getId))
                .stream()
                .map(this::toVo)
                .toList();
    }

    public ConvertTemplateEntity getByCode(String templateCode) {
        ConvertTemplateEntity entity = convertTemplateMapper.selectOne(new LambdaQueryWrapper<ConvertTemplateEntity>()
                .eq(ConvertTemplateEntity::getTemplateCode, templateCode)
                .eq(ConvertTemplateEntity::getEnabled, 1)
                .last("limit 1"));
        if (entity == null) {
            throw new BusinessException("模板不存在或已禁用");
        }
        return entity;
    }

    @Transactional
    public ConvertTemplateVo importTemplate(ConvertTemplateImportRequest request) {
        if (request.getTemplateContent() == null || request.getTemplateContent().isBlank()) {
            throw new BusinessException("模板内容不能为空");
        }
        ConvertTemplateEntity entity = new ConvertTemplateEntity();
        entity.setTemplateCode("user_" + System.currentTimeMillis());
        entity.setTemplateName((request.getTemplateName() == null || request.getTemplateName().isBlank()) ? "自定义 Offer 模板" : request.getTemplateName().trim());
        entity.setOutputFilename(entity.getTemplateName().endsWith(".txt") ? entity.getTemplateName() : entity.getTemplateName() + ".txt");
        entity.setRequiredSourceColumnsJson("[\"ASIN\",\"价格\"]");
        entity.setHeaderColumnsJson("[\"sku\",\"price\",\"quantity\",\"product-id\",\"product-id-type\",\"condition-type\",\"condition-note\",\"ASIN-hint\",\"title\",\"product-tax-code\",\"operation-type\",\"sale-price\",\"sale-start-date\",\"sale-end-date\",\"leadtime-to-ship\",\"launch-date\",\"is-giftwrap-available\",\"is-gift-message-available\"]");
        entity.setFieldMappingJson("{\"price\":\"价格\",\"product-id\":\"ASIN\"}");
        entity.setDefaultsJson("{\"quantity\":\"100\",\"product-id-type\":\"ASIN\",\"condition-type\":\"new\",\"leadtime-to-ship\":\"4\"}");
        entity.setPreambleLinesJson("[\"TemplateType=Offer\\tVersion=1.4\"]");
        entity.setBlankHeaderRowsAfterSchema(1);
        entity.setIsDefault(0);
        entity.setBuiltIn(0);
        entity.setEnabled(1);
        entity.setCreatedAt(LocalDateTime.now());
        entity.setUpdatedAt(LocalDateTime.now());
        convertTemplateMapper.insert(entity);
        return toVo(entity);
    }

    @Transactional
    public void setDefaultTemplate(String templateCode) {
        ConvertTemplateEntity entity = getByCode(templateCode);
        convertTemplateMapper.selectList(new LambdaQueryWrapper<ConvertTemplateEntity>().eq(ConvertTemplateEntity::getEnabled, 1))
                .forEach(item -> {
                    item.setIsDefault(item.getId().equals(entity.getId()) ? 1 : 0);
                    item.setUpdatedAt(LocalDateTime.now());
                    convertTemplateMapper.updateById(item);
                });
    }

    @Transactional
    public void deleteTemplate(String templateCode) {
        ConvertTemplateEntity entity = getByCode(templateCode);
        if (Integer.valueOf(1).equals(entity.getBuiltIn())) {
            throw new BusinessException("内置模板不允许删除");
        }
        entity.setEnabled(0);
        entity.setUpdatedAt(LocalDateTime.now());
        convertTemplateMapper.updateById(entity);
    }

    private ConvertTemplateVo toVo(ConvertTemplateEntity entity) {
        ConvertTemplateVo vo = new ConvertTemplateVo();
        vo.setId(entity.getTemplateCode());
        vo.setTemplateCode(entity.getTemplateCode());
        vo.setTemplateName(entity.getTemplateName());
        vo.setOutputFilename(entity.getOutputFilename());
        vo.setIsDefault(Integer.valueOf(1).equals(entity.getIsDefault()));
        vo.setBuiltIn(Integer.valueOf(1).equals(entity.getBuiltIn()));
        return vo;
    }
}
