package com.zksy.base.warning.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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.warning.domain.WarningReason;
import com.zksy.base.warning.mapper.WarningReasonMapper;
import com.zksy.base.warning.service.WarningReasonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WarningReasonServiceImpl extends ServiceImpl<WarningReasonMapper, WarningReason> implements WarningReasonService {

    @Override
    public IPage<WarningReason> queryWarningReasons(Page<WarningReason> page, String reasonCode, String reasonName, 
                                                     String warningType, String warningLevel, String status) {
        LambdaQueryWrapper<WarningReason> wrapper = new LambdaQueryWrapper<>();
        
        if (reasonCode != null && !reasonCode.isEmpty()) {
            wrapper.like(WarningReason::getReasonCode, reasonCode);
        }
        if (reasonName != null && !reasonName.isEmpty()) {
            wrapper.like(WarningReason::getReasonName, reasonName);
        }
        if (warningType != null && !warningType.isEmpty()) {
            wrapper.eq(WarningReason::getWarningType, warningType);
        }
        if (warningLevel != null && !warningLevel.isEmpty()) {
            wrapper.eq(WarningReason::getWarningLevel, warningLevel);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(WarningReason::getStatus, status);
        }
        
        wrapper.orderByAsc(WarningReason::getSortOrder).orderByDesc(WarningReason::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public List<WarningReason> getReasonsByTypeAndLevel(String warningType, String warningLevel) {
        LambdaQueryWrapper<WarningReason> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WarningReason::getWarningType, warningType)
               .eq(WarningReason::getWarningLevel, warningLevel)
               .eq(WarningReason::getStatus, "0")
               .orderByAsc(WarningReason::getSortOrder);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWarningReason(WarningReason warningReason) {
        if (warningReason.getReasonCode() == null || warningReason.getReasonCode().isEmpty()) {
            warningReason.setReasonCode(generateReasonCode(warningReason.getWarningType(), warningReason.getWarningLevel()));
        }
        if (warningReason.getStatus() == null) {
            warningReason.setStatus("0");
        }
        if (warningReason.getSortOrder() == null) {
            warningReason.setSortOrder(0);
        }
        return this.save(warningReason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWarningReason(WarningReason warningReason) {
        return this.updateById(warningReason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReasonStatus(String reasonId, String status) {
        WarningReason reason = new WarningReason();
        reason.setReasonId(reasonId);
        reason.setStatus(status);
        return this.updateById(reason);
    }

    @Override
    public WarningReason getReasonDetail(String reasonId) {
        return this.getById(reasonId);
    }

    private String generateReasonCode(String warningType, String warningLevel) {
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String prefix = "WR" + warningType.substring(0, Math.min(3, warningType.length())).toUpperCase() + warningLevel;
        
        LambdaQueryWrapper<WarningReason> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(WarningReason::getReasonCode, prefix + dateStr);
        wrapper.orderByDesc(WarningReason::getReasonCode);
        wrapper.last("LIMIT 1");
        
        WarningReason lastReason = this.getOne(wrapper);
        int sequence = 1;
        
        if (lastReason != null) {
            String lastCode = lastReason.getReasonCode();
            String lastSeqStr = lastCode.substring(lastCode.length() - 4);
            try {
                sequence = Integer.parseInt(lastSeqStr) + 1;
            } catch (NumberFormatException e) {
                sequence = 1;
            }
        }
        
        return prefix + dateStr + String.format("%04d", sequence);
    }
}
