package com.dora.service.impl;

import com.dora.entity.WechatQrCode;
import com.dora.mapper.WechatQrCodeMapper;
import com.dora.service.WechatQrCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 企业微信二维码服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatQrCodeServiceImpl implements WechatQrCodeService {

    private final WechatQrCodeMapper wechatQrCodeMapper;

    @Override
    public List<WechatQrCode> getAllQrCodes() {
        log.debug("获取所有企业微信二维码");
        return wechatQrCodeMapper.selectAll();
    }

    @Override
    public WechatQrCode getById(Long id) {
        log.debug("根据ID获取企业微信二维码: {}", id);
        return wechatQrCodeMapper.selectById(id);
    }

    @Override
    @Transactional
    public WechatQrCode createQrCode(WechatQrCode wechatQrCode) {
        log.info("创建新的企业微信二维码");
        
        // 设置默认值
        wechatQrCode.setCreateTime(LocalDateTime.now());
        wechatQrCode.setIsDeleted(false);
        
        int result = wechatQrCodeMapper.insert(wechatQrCode);
        if (result > 0) {
            log.info("企业微信二维码创建成功，ID: {}", wechatQrCode.getId());
            return wechatQrCode;
        } else {
            log.error("企业微信二维码创建失败");
            throw new RuntimeException("创建企业微信二维码失败");
        }
    }

    @Override
    @Transactional
    public WechatQrCode updateQrCode(Long id, WechatQrCode wechatQrCode) {
        log.info("更新企业微信二维码，ID: {}", id);
        
        WechatQrCode existingQrCode = wechatQrCodeMapper.selectById(id);
        if (existingQrCode == null) {
            log.error("未找到企业微信二维码，ID: {}", id);
            throw new RuntimeException("未找到对应的二维码");
        }
        
        wechatQrCode.setId(id);
        
        int result = wechatQrCodeMapper.updateById(wechatQrCode);
        if (result > 0) {
            log.info("企业微信二维码更新成功，ID: {}", id);
            return wechatQrCodeMapper.selectById(id);
        } else {
            log.error("企业微信二维码更新失败，ID: {}", id);
            throw new RuntimeException("更新企业微信二维码失败");
        }
    }

    @Override
    @Transactional
    public boolean deleteQrCode(Long id) {
        log.info("删除企业微信二维码，ID: {}", id);
        
        WechatQrCode existingQrCode = wechatQrCodeMapper.selectById(id);
        if (existingQrCode == null) {
            log.error("未找到企业微信二维码，ID: {}", id);
            return false;
        }
        
        int result = wechatQrCodeMapper.softDelete(id);
        boolean success = result > 0;
        
        if (success) {
            log.info("企业微信二维码删除成功，ID: {}", id);
        } else {
            log.error("企业微信二维码删除失败，ID: {}", id);
        }
        
        return success;
    }
}
