package com.fizz.business.service.impl;

import com.fizz.business.mapper.L3PickupRecommendMapper;
import com.fizz.business.service.L3PickupRecommendService;
import com.fizz.business.vo.L3PickupRecommendVO;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class L3PickupRecommendServiceImpl implements L3PickupRecommendService {

    @Resource
    private L3PickupRecommendMapper l3PickupRecommendMapper;

    @Override
    @DataSource(DataSourceType.L3)
    public List<L3PickupRecommendVO> listPickupRecommend(Integer limit) {
        int queryLimit = (limit == null || limit <= 0) ? 10 : Math.min(limit, 50);
        List<Map<String, Object>> pendingActions = l3PickupRecommendMapper.selectPendingActions(queryLimit);
        List<L3PickupRecommendVO> result = new ArrayList<>();

        for (Map<String, Object> action : pendingActions) {
            L3PickupRecommendVO vo = new L3PickupRecommendVO();
            vo.setActionId(toLong(action.get("action_id")));
            vo.setSourceCoilId(toLong(action.get("coil_id")));
            vo.setCoilId(toStringValue(action.get("current_coil_no")));
            vo.setPriority(toInteger(action.get("priority")));
            vo.setScanTime(toLocalDateTime(action.get("scan_time")));

            Long sourceCoilId = vo.getSourceCoilId();
            if (sourceCoilId != null) {
                Map<String, Object> material = l3PickupRecommendMapper.selectMaterialByCoilId(sourceCoilId);
                if (material != null) {
                    vo.setEnterCoilNo(toStringValue(material.get("enter_coil_no")));
                }
            }
            result.add(vo);
        }

        return result;
    }

    private Long toLong(Object value) {
        if (value == null) return null;
        if (value instanceof Number) return ((Number) value).longValue();
        try {
            return Long.parseLong(String.valueOf(value));
        } catch (Exception e) {
            return null;
        }
    }

    private Integer toInteger(Object value) {
        if (value == null) return null;
        if (value instanceof Number) return ((Number) value).intValue();
        try {
            return Integer.parseInt(String.valueOf(value));
        } catch (Exception e) {
            return null;
        }
    }

    private String toStringValue(Object value) {
        return value == null ? null : String.valueOf(value);
    }

    private LocalDateTime toLocalDateTime(Object value) {
        if (value == null) return null;
        if (value instanceof LocalDateTime) return (LocalDateTime) value;
        if (value instanceof Timestamp) return ((Timestamp) value).toLocalDateTime();
        return null;
    }
}
