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.PrinterRequest;
import com.erp.common.core.model.PageResponse;
import com.erp.print.entity.Printer;
import com.erp.print.exception.PrintException;
import com.erp.print.repository.PrinterRepository;
import com.erp.print.service.PrinterService;
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 PrinterServiceImpl implements PrinterService {

    private final PrinterRepository printerRepository;

    @Override
    public PageResponse<Printer> listPrinters(Integer page, Integer limit, String printerType, String keyword) {
        Page<Printer> p = new Page<>(page, limit);
        IPage<Printer> result = printerRepository.selectPrinterPage(p, printerType);
        return PageResponse.of(result.getTotal(), page, limit, result.getRecords());
    }

    @Override
    public Printer getPrinterById(Long id) {
        return printerRepository.selectById(id);
    }

    @Override
    public Printer getPrinterByCode(String printerCode) {
        return printerRepository.selectByPrinterCode(printerCode);
    }

    @Override
    @Transactional
    public Printer createPrinter(PrinterRequest request) {
        if (printerRepository.selectByPrinterCode(request.getPrinterCode()) != null) {
            throw new PrintException("打印机编码已存在: " + request.getPrinterCode());
        }

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

        Printer printer = new Printer();
        BeanUtils.copyProperties(request, printer);
        printer.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        printerRepository.insert(printer);
        log.info("创建打印机成功: {}", printer.getPrinterCode());
        return printer;
    }

    @Override
    @Transactional
    public Printer updatePrinter(PrinterRequest request) {
        Printer printer = printerRepository.selectById(request.getId());
        if (printer == null) {
            throw new PrintException("打印机不存在: " + request.getId());
        }

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

        BeanUtils.copyProperties(request, printer);
        printerRepository.updateById(printer);
        log.info("更新打印机成功: {}", printer.getPrinterCode());
        return printer;
    }

    @Override
    @Transactional
    public void deletePrinter(Long id) {
        printerRepository.deleteById(id);
        log.info("删除打印机: {}", id);
    }

    @Override
    @Transactional
    public void setDefaultPrinter(Long id) {
        Printer printer = printerRepository.selectById(id);
        if (printer == null) {
            throw new PrintException("打印机不存在: " + id);
        }
        clearDefaultPrinter();
        printer.setIsDefault(1);
        printerRepository.updateById(printer);
        log.info("设置默认打印机: {}", printer.getPrinterCode());
    }

    @Override
    @Transactional
    public void updatePrinterStatus(Long id, Integer status) {
        Printer printer = printerRepository.selectById(id);
        if (printer == null) {
            throw new PrintException("打印机不存在: " + id);
        }
        printer.setStatus(status);
        printerRepository.updateById(printer);
        log.info("更新打印机状态: {} -> {}", printer.getPrinterCode(), status);
    }

    @Override
    public List<Printer> getAvailablePrinters() {
        LambdaQueryWrapper<Printer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Printer::getStatus, 1)
               .orderByDesc(Printer::getIsDefault)
               .orderByAsc(Printer::getCreatedAt);
        return printerRepository.selectList(wrapper);
    }

    @Override
    public IPage<Printer> selectPrinterPage(Page<Printer> page, String printerType) {
        LambdaQueryWrapper<Printer> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(printerType)) {
            wrapper.eq(Printer::getPrinterType, printerType);
        }
        wrapper.orderByDesc(Printer::getCreatedAt);
        return printerRepository.selectPage(page, wrapper);
    }

    private void clearDefaultPrinter() {
        LambdaQueryWrapper<Printer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Printer::getIsDefault, 1);
        List<Printer> defaults = printerRepository.selectList(wrapper);
        defaults.forEach(p -> {
            p.setIsDefault(0);
            printerRepository.updateById(p);
        });
    }
}
