using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WMS_GIRAF_Interface.Data;
using WMS_GIRAF_Interface.Entities;
using WMS_GIRAF_Interface.Repositories.Implement;
using WMS_GIRAF_Interface.Repositories.Interface;

namespace WMS_GIRAF_Interface.TaskServices;

public class CellLogicService(MichelinDbContext context,IWhCellRepository whCellRepository, ILogger<CellLogicService> logger)
{
    /// <summary>
    /// 自动入库 获取line way number
    /// </summary>
    /// <param name="startCell"></param>
    /// <param name="cellModel"></param>
    /// <param name="stockBarcode"></param>
    /// <param name="endLineNumbers"></param>
    /// <param name="lotNumber"></param>
    /// <param name="sResult"></param>
    /// <returns></returns>
    public bool GetLaneWayFromDecisionPoint(WH_CELL startCell,
        string cellModel,
        string stockBarcode, 
        string[] endLineNumbers,
        string lotNumber,  out int selectedLaneWay , out string  sResult)
    {
        selectedLaneWay = 0;
        sResult = string.Empty;
        string endDeviceList = "";
        foreach (var endLineNumber in endLineNumbers)
        {
            if (endDeviceList=="")
            {
                endDeviceList = $"'{endLineNumber}'";
            }
            else
            {
                endDeviceList += $",'{endLineNumber}'";
            }
        }

        string endDeviceCode = "";
        var getSelectedLaneWay = 
            context.V_ManageInCount.FromSqlRaw($@"SELECT
													t3.START_DEVICE,
													t3.END_DEVICE,
													t3.MANAGE_COUNT,
													t3.ENABLE_CELL_COUNT 
												FROM
												(
												SELECT
													top 4  t1.*,
													ISNULL( t2.LOTCOUNTS, 0 ) LOTCOUNTS 
												FROM
												(
													( SELECT * FROM V_MANAGE_IN_COUNT WHERE START_DEVICE = '{startCell.DEVICE_CODE}' AND ENABLE_CELL_COUNT > 0 
                                                    AND END_DEVICE in (SELECT DEVICE_CODE FROM WH_CELL WHERE CELL_TYPE = 'Cell' and LANE_WAY in ({endDeviceList}))) t1
													LEFT JOIN ( SELECT ISNULL( COUNT ( DEVICE_CODE ), 0 ) LOTCOUNTS, DEVICE_CODE FROM V_STORAGE_LIST t2 
                                                    WHERE LOTNUMBER = '{lotNumber}' GROUP BY DEVICE_CODE ) t2 ON t1.END_DEVICE = t2.DEVICE_CODE 
													) 
												ORDER BY
													LOTCOUNTS,
													ENABLE_CELL_COUNT DESC,
												END_DEVICE DESC 
												) t3").ToList();
        
        if (getSelectedLaneWay.Count > 0)
        {
            endDeviceCode = getSelectedLaneWay[0].END_DEVICE;
            selectedLaneWay = whCellRepository.GetCell(endDeviceCode)!.CELL_ID;
            return true;
        }
        else
        {
            sResult = "did not find the enable lane way";
            return false;
        }

    }

    /// <summary>
    /// 手工入库获取终点货位信息
    /// </summary>
    /// <param name="startCell">起始位置</param>
    /// <param name="endCellId">终点ID</param>
    /// <param name="sResult">错误信息</param>
    /// <returns></returns>
    public bool GetCellLocationFromCheckPoint(WH_CELL startCell, out int endCellId, out string sResult)
    {
        bool bResult = true;
        sResult = string.Empty;
        endCellId = 0;
        switch (startCell.CELL_MODEL)
        {
            case "CP":
                var getPosition = context.Wh_Cell
                    .FromSqlRaw(
                        $@"SELECT TOP 1 CELL_ID,CELL_CODE FROM WH_CELL 
                            WHERE CELL_STATUS = 'Nohave' AND RUN_STATUS = 'Enable' AND CELL_TYPE = 'Cell' AND LANE_WAY = '{startCell.LANE_WAY}' 
                            ORDER BY CELL_X,CELL_Y")
                    .ToList();

                    if (getPosition is { Count: > 0 })
                    {
                        endCellId = getPosition[0].CELL_ID;
                        sResult = $"{startCell.CELL_CODE} (CP): get right end position:{getPosition[0].CELL_CODE}";
                    }
                    else
                    {
                        sResult = $"cell_model:{startCell.CELL_CODE} (CP); not find the enable position !";
                        bResult = false;
                    }

                    break;
            case "MP":
            case "EP":
                var getManualPosition = context.V_WhCellEnable
                    .FromSqlRaw(
                        $@"SELECT TOP 1 CELL_ID,CELL_CODE FROM V_WH_CELL_ENABLE 
                            WHERE LANE_WAY = '{startCell.LANE_WAY}' 
                            ORDER BY PRIORITY,CELL_X,YPRIORITY,CELL_Y")
                    .ToList();
                    if (getManualPosition is { Count : >0})
                    {
                        endCellId = getManualPosition[0].CELL_ID;
                        sResult = $"{startCell.CELL_CODE} (EP): get right end position:{getManualPosition[0].CELL_CODE}";
}
                    else
                    {
                        sResult = $"cell_model:{startCell.CELL_CODE} (EP); not find the enable position !";
                        bResult = false;
                    }
                    break;
            default:
                goto case "EP";
                break;
            
        }
        logger.LogInformation(sResult);
        return bResult;

    }
}