package com.erp.print.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.print.dto.request.PrintTemplateRequest;
import com.erp.common.core.model.PageResponse;
import com.erp.print.entity.PrintTemplate;
import com.erp.print.exception.PrintException;
import com.erp.print.repository.PrintTemplateRepository;
import com.erp.print.service.PrintTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PrintTemplateServiceImpl implements PrintTemplateService {

    private final PrintTemplateRepository templateRepository;

    @Override
    public PageResponse<PrintTemplate> listTemplates(Integer page, Integer limit, String templateType, String keyword) {
        Page<PrintTemplate> p = new Page<>(page, limit);
        IPage<PrintTemplate> result = templateRepository.selectTemplatePage(p, templateType);
        return PageResponse.of(result.getTotal(), page, limit, result.getRecords());
    }

    @Override
    public PrintTemplate getTemplateById(Long id) {
        return templateRepository.selectById(id);
    }

    @Override
    public PrintTemplate getTemplateByCode(String templateCode) {
        return templateRepository.selectByTemplateCode(templateCode);
    }

    @Override
    @Transactional
    public PrintTemplate createTemplate(PrintTemplateRequest request) {
        if (templateRepository.selectByTemplateCode(request.getTemplateCode()) != null) {
            throw new PrintException("模板编码已存在: " + request.getTemplateCode());
        }

        if (request.getIsDefault() != null && request.getIsDefault() == 1) {
            clearDefaultByType(request.getTemplateType());
        }

        PrintTemplate template = new PrintTemplate();
        BeanUtils.copyProperties(request, template);
        template.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        templateRepository.insert(template);
        log.info("创建打印模板成功: {}", template.getTemplateCode());
        return template;
    }

    @Override
    @Transactional
    public PrintTemplate updateTemplate(PrintTemplateRequest request) {
        PrintTemplate template = templateRepository.selectById(request.getId());
        if (template == null) {
            throw new PrintException("模板不存在: " + request.getId());
        }

        if (!template.getTemplateCode().equals(request.getTemplateCode())) {
            PrintTemplate existing = templateRepository.selectByTemplateCode(request.getTemplateCode());
            if (existing != null) {
                throw new PrintException("模板编码已存在: " + request.getTemplateCode());
            }
        }

        if (request.getIsDefault() != null && request.getIsDefault() == 1) {
            clearDefaultByType(request.getTemplateType());
        }

        BeanUtils.copyProperties(request, template);
        templateRepository.updateById(template);
        log.info("更新打印模板成功: {}", template.getTemplateCode());
        return template;
    }

    @Override
    @Transactional
    public void deleteTemplate(Long id) {
        templateRepository.deleteById(id);
        log.info("删除打印模板: {}", id);
    }

    @Override
    @Transactional
    public void setDefaultTemplate(Long id) {
        PrintTemplate template = templateRepository.selectById(id);
        if (template == null) {
            throw new PrintException("模板不存在: " + id);
        }
        clearDefaultByType(template.getTemplateType());
        template.setIsDefault(1);
        templateRepository.updateById(template);
        log.info("设置默认模板: {}", template.getTemplateCode());
    }

    @Override
    public IPage<PrintTemplate> selectTemplatePage(Page<PrintTemplate> page, String templateType) {
        LambdaQueryWrapper<PrintTemplate> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(templateType)) {
            wrapper.eq(PrintTemplate::getTemplateType, templateType);
        }
        wrapper.orderByDesc(PrintTemplate::getCreatedAt);
        return templateRepository.selectPage(page, wrapper);
    }

    private void clearDefaultByType(String templateType) {
        LambdaQueryWrapper<PrintTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PrintTemplate::getTemplateType, templateType)
               .eq(PrintTemplate::getIsDefault, 1);
        List<PrintTemplate> defaults = templateRepository.selectList(wrapper);
        defaults.forEach(t -> {
            t.setIsDefault(0);
            templateRepository.updateById(t);
        });
    }
}
